From 7d78a880201d25b8e7b9de1f7bd22199f92a2705 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 21:24:58 -0300 Subject: Move the File namespace out of panes.zig into File.zig Pure move: the body of `pub const File = struct { ... }` is now the file File.zig, dedented, with the imports it uses; panes.zig keeps `pub const File = @import("File.zig");`, so `panes.File.x` callers and the `File.State` field of Pane are unchanged. File.zig joins the embedded source list. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 1305 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1305 insertions(+) create mode 100644 src/File.zig (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig new file mode 100644 index 00000000..eb1c6a7c --- /dev/null +++ b/src/File.zig @@ -0,0 +1,1305 @@ +//! A file pane's text: its content and undo history, display columns, line +//! index, syntax highlights and the body it fills. +const panes = @import("panes.zig"); +const std = @import("std"); +const vaxis = @import("vaxis"); +const pardes = @import("pardes.zig"); +const config = @import("config.zig"); +const Pardes = pardes.Pardes; +const modal = @import("modal.zig"); +const filesystem = @import("fs.zig"); +const syntax = @import("syntax.zig"); +const tracy = @import("tracy.zig"); +const dump = @import("dump.zig"); +const limits = @import("memory.zig").limits; +const locations = @import("locations.zig"); +const Pane = panes.Pane; +const Output = panes.Output; +const Mini = panes.Mini; +const Terminal = panes.Terminal; + +const SYNTAX_CONTEXT_AFTER_ROWS: usize = 2; + +/// Content and primary selection at one file edit boundary. Keeping only the +/// primary avoids putting Pane.max_selections ranges in every history entry. +pub const Snapshot = struct { + content: []u8, + cur_row: i32, + cur_col: i32, + vsel: Pane.CharSel, +}; + +pub const History = struct { + undo: [limits.undo_max]Snapshot = undefined, + undo_len: usize = 0, + redo: [limits.undo_max]Snapshot = undefined, + redo_len: usize = 0, + + pub fn create(gpa: std.mem.Allocator) !*History { + const history = try gpa.create(History); + history.undo_len = 0; + history.redo_len = 0; + return history; + } +}; + +/// A file pane's backing: owned content, its derived caches, and undo history. +pub const State = struct { + path: []u8, + content: []u8, + revision: u32 = 0, + /// Revision last known to match disk, after Save or an external reload. + /// Equal means the screen matches disk. + saved_revision: u32 = 0, + watch_after_save: bool = false, + /// Seconds of the last content change, for the filesystem's stat; zero until edited. + mtime: u32 = 0, + /// Non-null for a generated output buffer rather than an on-disk file. + output: ?Output.State = null, + mini: ?Mini.State = null, + scroll: usize = 0, + /// `line_starts[i]` is line i's byte offset. Empty means not built yet. + line_starts: []usize = &.{}, + /// One tree_sitter_gpa-owned syntax.Syn byte per highlighted source byte. + highlights: []u8 = &.{}, + location_rows: []locations.Row = &.{}, + highlight_start: usize = 0, + syntax_dirty: bool = true, + tree_context: bool = false, + context_declarations: []syntax.ContextDeclaration = &.{}, + context_revision: ?u32 = null, + history: *History, +}; + +pub fn dumpPane( + arena: std.mem.Allocator, + pane: *const Pane, + file: *const State, + tag: []const u8, + body: []const u8, + scroll: usize, + origin: []const u8, + origin_arg: []const u8, +) !dump.Pane { + return .{ + .kind = .file, + .tag = tag, + .body = body, + .scroll = scroll, + .cols = pane.cols, + .rows = pane.rows, + .vweight = pane.vweight, + .collapsed = pane.collapsed, + .file = .{ + .tree_context = file.tree_context, + .location_rows = try dumpLocationRows(arena, file.location_rows), + .path = file.path, + .content = file.content, + .content_b64 = try dump.encodeBytes(arena, file.content), + .dirty = file.revision != file.saved_revision, + .origin = origin, + .origin_arg = origin_arg, + .mini_source = if (file.mini) |mini| mini.source else "", + .mini_colors_b64 = if (file.mini) |mini| try dump.encodeBytes(arena, mini.colors) else "", + }, + }; +} + +fn dumpLocationRows(arena: std.mem.Allocator, rows: []const locations.Row) ![]const dump.LocationRow { + const saved = try arena.alloc(dump.LocationRow, rows.len); + for (rows, saved) |row, *out| out.* = .{ + .kind = @enumFromInt(@intFromEnum(row.kind)), + .declaration = row.declaration, + .path = row.path, + .line = row.at.line, + .col = row.at.col, + .end_line = row.at.end_line, + .end_col = row.at.end_col, + .location_end = row.location_end, + .code_start = row.code_start, + .colors_b64 = try dump.encodeBytes(arena, row.colors), + }; + return saved; +} + +fn sameSavedLocation(a: dump.LocationRow, b: dump.LocationRow) bool { + return std.mem.eql(u8, a.path, b.path) and a.line == b.line and a.col == b.col and + a.end_line == b.end_line and a.end_col == b.end_col; +} + +fn restoreLocationRows(gpa: std.mem.Allocator, content: []const u8, saved: []const dump.LocationRow) ![]locations.Row { + if (saved.len == 0) return &.{}; + if (saved.len > std.mem.count(u8, content, "\n") + 1) return error.InvalidLocationRows; + const rows = try gpa.alloc(locations.Row, saved.len); + var initialized: usize = 0; + errdefer { + for (rows[0..initialized]) |row| { + gpa.free(row.path); + gpa.free(row.colors); + } + gpa.free(rows); + } + var lines = std.mem.splitScalar(u8, content, '\n'); + var previous_line: []const u8 = ""; + for (saved, rows, 0..) |row, *out, index| { + const line = lines.next() orelse return error.InvalidLocationRows; + if (row.path.len == 0 or row.path.len >= 4096 or + row.location_end > row.code_start or row.code_start > line.len or + (row.kind == .match and row.location_end == 0) or + (row.declaration and row.kind != .context) or + row.line > std.math.maxInt(i32) or row.col > std.math.maxInt(i32) or + row.end_line > std.math.maxInt(i32) or row.end_col > std.math.maxInt(i32)) + return error.InvalidLocationRows; + const inline_row = row.code_start > row.location_end and row.code_start > 0 and line[row.code_start - 1] == '\t'; + const address_row = !inline_row and row.location_end > 0 and row.code_start == line.len; + const source_row = row.location_end == 0 and row.code_start == 0; + if (!inline_row and !address_row and !source_row) return error.InvalidLocationRows; + if (row.kind == .preview) { + if (!source_row or index == 0) return error.InvalidLocationRows; + const previous = saved[index - 1]; + if (previous.kind != .match or previous.location_end == 0 or previous.code_start != previous_line.len or previous_line[previous_line.len - 1] == '\t' or + !sameSavedLocation(previous, row)) return error.InvalidLocationRows; + } + if (address_row) { + if (index + 1 >= saved.len) return error.InvalidLocationRows; + const following = saved[index + 1]; + const expected: @TypeOf(row.kind) = if (row.kind == .match) .preview else .context; + if (following.kind != expected or following.code_start != 0 or following.location_end != 0 or + following.declaration != row.declaration or !sameSavedLocation(row, following)) return error.InvalidLocationRows; + } + const code_len = line.len - row.code_start; + if (row.colors_b64.len > std.base64.standard.Encoder.calcSize(code_len)) return error.InvalidLocationRows; + const colors = try dump.decodeBytes(gpa, row.colors_b64); + errdefer gpa.free(colors); + if (colors.len != 0 and colors.len != code_len) return error.InvalidLocationRows; + for (colors) |color| if (color > @intFromEnum(syntax.Syn.comment)) return error.InvalidLocationRows; + const path = try gpa.dupe(u8, row.path); + out.* = .{ + .kind = @enumFromInt(@intFromEnum(row.kind)), + .declaration = row.declaration, + .path = path, + .at = .{ .line = row.line, .col = row.col, .end_line = row.end_line, .end_col = row.end_col }, + .location_end = row.location_end, + .code_start = row.code_start, + .colors = colors, + }; + initialized += 1; + previous_line = line; + } + if (lines.next()) |remaining| if (remaining.len != 0 or lines.next() != null) return error.InvalidLocationRows; + return rows; +} + +test "location metadata restore rejects offsets and invalid syntax bytes" { + const gpa = std.testing.allocator; + var row: dump.LocationRow = .{ + .kind = .context, + .path = "x.zig", + .line = 1, + .location_end = 0, + .code_start = 3, + }; + const rows = try restoreLocationRows(gpa, "| \tx\n", &.{row}); + defer locations.freeRows(gpa, rows); + try std.testing.expectEqualStrings("x.zig", rows[0].path); + row.code_start = 8; + try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, "| \tx\n", &.{row})); + row.code_start = 3; + row.colors_b64 = "/w=="; + try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, "| \tx\n", &.{row})); + row.colors_b64 = ""; + row.kind = .match; + try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, "| \tx\n", &.{row})); +} + +test "stacked location metadata requires matching adjacent preview ownership" { + const gpa = std.testing.allocator; + const header = "x.c:2:1-3"; + const content = header ++ "\nfoo\n"; + const match: dump.LocationRow = .{ .kind = .match, .path = "x.c", .line = 2, .col = 1, .end_line = 2, .end_col = 3, .location_end = header.len, .code_start = header.len }; + const preview: dump.LocationRow = .{ .kind = .preview, .path = "x.c", .line = 2, .col = 1, .end_line = 2, .end_col = 3, .location_end = 0, .code_start = 0 }; + const restored = try restoreLocationRows(gpa, content, &.{ match, preview }); + defer locations.freeRows(gpa, restored); + try std.testing.expectEqual(.preview, restored[1].kind); + try std.testing.expectEqual(restored[0].at, restored[1].at); + try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, "foo\n", &.{preview})); + try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, header ++ "\n", &.{match})); + var inline_match = match; + inline_match.code_start += 1; + try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, header ++ "\t\nfoo\n", &.{ inline_match, preview })); + var wrong = preview; + wrong.path = "other.c"; + try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, content, &.{ match, wrong })); + wrong = preview; + wrong.line = 3; + try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, content, &.{ match, wrong })); + wrong = preview; + wrong.code_start = 1; + try std.testing.expectError(error.InvalidLocationRows, restoreLocationRows(gpa, content, &.{ match, wrong })); +} + +pub fn graphemeDisplayWidth(grapheme: []const u8) usize { + if (std.mem.eql(u8, grapheme, "\t")) return config.tab_width; + if (grapheme.len == 1 and grapheme[0] >= 0x20 and grapheme[0] < 0x7f) return 1; + return @max(1, @as(usize, vaxis.gwidth.gwidth(grapheme, .unicode))); +} + +pub fn byteDisplayWidth(byte: u8) usize { + return if (byte == '\t') config.tab_width else 1; +} + +pub fn displayWidth(text: []const u8) usize { + var width: usize = 0; + var at: usize = 0; + while (at < text.len) { + const end = modal.nextGrapheme(text, at); + width +|= graphemeDisplayWidth(text[at..end]); + at = end; + } + return width; +} + +/// Source byte at a zero-based display column. Every cell occupied by a tab +/// maps back to that one tab byte. +pub fn byteAtDisplay(text: []const u8, display_col: usize) usize { + var col: usize = 0; + var at: usize = 0; + while (at < text.len) { + const end = modal.nextGrapheme(text, at); + const next = col +| graphemeDisplayWidth(text[at..end]); + if (display_col < next) return at; + col = next; + at = end; + } + return text.len; +} + +/// File cursor columns may live past EOL. Tabs expand before that boundary; +/// every virtual column after it remains one screen cell. +pub fn rawDisplayCol(line_text: []const u8, raw_col: usize) usize { + const bounded = modal.graphemeStart(line_text, @min(raw_col, line_text.len)); + return displayWidth(line_text[0..bounded]) +| (raw_col -| line_text.len); +} + +pub fn rawAtDisplay(line_text: []const u8, display_col: usize) usize { + const width = displayWidth(line_text); + if (display_col > width) return line_text.len +| (display_col - width); + return byteAtDisplay(line_text, display_col); +} + +pub fn byteAtDisplayFrom(line_text: []const u8, from_raw: usize, display_col: usize) usize { + if (from_raw >= line_text.len) return from_raw +| display_col; + const from = modal.graphemeStart(line_text, from_raw); + return from +| rawAtDisplay(line_text[from..], display_col); +} + +pub fn lineDisplayOffset(line_text: []const u8, from_raw: usize, to_raw: usize) i32 { + const from_display = rawDisplayCol(line_text, from_raw); + const to_display = rawDisplayCol(line_text, to_raw); + if (to_display >= from_display) return @intCast(to_display - from_display); + return -@as(i32, @intCast(from_display - to_display)); +} + +pub fn lineDisplayEndOffset(line_text: []const u8, from_raw: usize, at_raw: usize) i32 { + const start = lineDisplayOffset(line_text, from_raw, at_raw); + if (at_raw >= line_text.len) return start; + const at = modal.graphemeStart(line_text, at_raw); + const end = modal.nextGrapheme(line_text, at); + return start + @as(i32, @intCast(graphemeDisplayWidth(line_text[at..end]))) - 1; +} + +pub fn sourceLine(pane: *const Pane, row: i32) []const u8 { + const f = if (pane.file) |*file| file else return ""; + if (row < 0) return ""; + const line: usize = @intCast(row); + if (f.line_starts.len == 0) return modal.lineSlice(f.content, line); + if (line >= f.line_starts.len) return ""; + const start = f.line_starts[line]; + const end = if (line + 1 < f.line_starts.len) f.line_starts[line + 1] - 1 else f.content.len; + return f.content[start..end]; +} + +test "indexed source rows match uncached scans across content changes" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile(""); + const file = &pane.file.?; + for ([_][]const u8{ "", "one", "one\n", "a\r\nλ界\nlast", "\n\n", "\tλ e\u{301}\n\r\n" }) |content| { + setContent(p, file, try p.gpa.dupe(u8, content)); + // An edit carries a built index forward; it must equal a fresh one. + if (file.line_starts.len > 0) { + const carried = file.line_starts; + defer p.gpa.free(carried); + file.line_starts = &.{}; + try std.testing.expectEqualSlices(usize, try lineIndex(p.gpa, file), carried); + p.gpa.free(file.line_starts); + file.line_starts = &.{}; + } + const rows = lineCount(content) + 2; + for ([_]bool{ false, true }) |indexed| { + if (indexed) _ = try lineIndex(p.gpa, file); + try std.testing.expectEqualStrings("", sourceLine(pane, -1)); + for (0..rows) |row| try std.testing.expectEqualStrings( + modal.lineSlice(content, row), + sourceLine(pane, @intCast(row)), + ); + if (!indexed) try std.testing.expectEqual(@as(usize, 0), file.line_starts.len); + } + } +} + +pub fn displayOffset(pane: *const Pane, row: i32, from_raw: i32, to_raw: i32) i32 { + const line_text = sourceLine(pane, row); + const from: usize = @intCast(@max(0, from_raw)); + const to: usize = @intCast(@max(0, to_raw)); + return lineDisplayOffset(line_text, from, to); +} + +pub fn displayEndOffset(pane: *const Pane, row: i32, from_raw: i32, at_raw: i32) i32 { + const line_text = sourceLine(pane, row); + return lineDisplayEndOffset(line_text, @intCast(@max(0, from_raw)), @intCast(@max(0, at_raw))); +} + +pub fn byteAtRowDisplay(pane: *const Pane, row: i32, from_raw: i32, display_col: i32) i32 { + const line_text = sourceLine(pane, row); + return @intCast(byteAtDisplayFrom(line_text, @intCast(@max(0, from_raw)), @intCast(@max(0, display_col)))); +} + +pub fn gutterWidth(pane: *const Pane) u16 { + if (pane.file == null) return 0; + const file = &pane.file.?; + var lines = if (file.line_starts.len > 0) file.line_starts.len else lineCount(file.content); + var digits: u16 = 1; + while (lines >= 10) : (lines /= 10) digits += 1; + return @max(config.PREFIX_W, digits + 1); +} + +/// Convert between rendered cells and UTF-8 byte columns. Tag rows always +/// need grapheme conversion; file body rows additionally skip the gutter. +pub fn renderedLineByteCol(pane: *const Pane, row: i32, line_text: []const u8, display_col: usize) usize { + if (row < pardes.BOX_H) return rawAtDisplay(line_text, display_col); + if (pane.file == null) return rawAtDisplay(line_text, display_col); + const prefix = @min(@as(usize, gutterWidth(pane)), line_text.len); + if (display_col <= prefix) return display_col; + return prefix +| rawAtDisplay(line_text[prefix..], display_col - prefix); +} + +pub fn renderedLineDisplayCol(pane: *const Pane, row: i32, line_text: []const u8, byte_col: usize) usize { + if (row < pardes.BOX_H) return rawDisplayCol(line_text, byte_col); + if (pane.file == null) return rawDisplayCol(line_text, byte_col); + const prefix = @min(@as(usize, gutterWidth(pane)), line_text.len); + if (byte_col <= prefix) return byte_col; + return prefix +| rawDisplayCol(line_text[prefix..], byte_col - prefix); +} + +test "the ASCII arm of graphemeDisplayWidth matches the gwidth it skips" { + const ref = struct { + fn width(grapheme: []const u8) usize { + if (std.mem.eql(u8, grapheme, "\t")) return config.tab_width; + return @max(1, @as(usize, vaxis.gwidth.gwidth(grapheme, .unicode))); + } + }.width; + + var one: [1]u8 = undefined; + var b: u8 = 0; + while (b < 0x80) : (b += 1) { + one[0] = b; + try std.testing.expectEqual(ref(one[0..1]), graphemeDisplayWidth(one[0..1])); + } + for ([_][]const u8{ + "e\u{301}", "a\u{903}", "1\u{fe0f}\u{20e3}", "\u{4e16}", + "\u{1f642}", "\u{1f1e6}\u{1f1e7}", "\xff", "\xe4\xb8", + }) |g| try std.testing.expectEqual(ref(g), graphemeDisplayWidth(g)); +} + +test "the ASCII run in fitEnd survives an exhaustive byte sweep" { + const reference = struct { + fn fitEnd(text: []const u8, start: usize, width: usize) usize { + var end = start; + var used: usize = 0; + while (end < text.len) { + const next_end = modal.nextGrapheme(text, end); + const next_used = used +| graphemeDisplayWidth(text[end..next_end]); + if (next_used > width) return if (end == start) next_end else end; + used = next_used; + end = next_end; + } + return end; + } + }.fitEnd; + + const neighbours = [_][]const u8{ + "", "z", "\u{301}", "\u{200d}\u{1f680}", + "\u{903}", "\u{fe0f}", "\u{4e16}", "\u{1f642}", + "\u{1f1e6}\u{1f1e7}", "\xff", "\xe4\xb8", "\xe4\x28\xb8", + }; + var buf: [16]u8 = undefined; + // The same pair again behind an ASCII prefix, so a break can land exactly at the run boundary + // as well as before it and inside the multi-byte cluster that follows it. + var prefixed: [18]u8 = undefined; + prefixed[0] = 'a'; + prefixed[1] = 'b'; + var b: u8 = 0; + while (b < 0x80) : (b += 1) { + buf[0] = b; + for (neighbours) |tail| { + @memcpy(buf[1..][0..tail.len], tail); + const pair = buf[0 .. 1 + tail.len]; + @memcpy(prefixed[2..][0..pair.len], pair); + for ([_][]const u8{ pair, prefixed[0 .. 2 + pair.len] }) |text| { + var width: usize = 0; + while (width <= text.len + 3) : (width += 1) { + var start: usize = 0; + while (start <= text.len) : (start += 1) { + std.testing.expectEqual( + reference(text, start, width), + fitEnd(text, start, width), + ) catch |e| { + std.debug.print("fitEnd({any}, {d}, {d})\n", .{ text, start, width }); + return e; + }; + } + } + } + } + } +} + +fn fitEnd(text: []const u8, start: usize, width: usize) usize { + var end = start; + var used: usize = 0; + while (used < width and end < text.len) { + const b = text[end]; + if (b < 0x20 or b >= 0x7f) break; + if (end + 1 < text.len and text[end + 1] >= 0x80) break; + used += 1; + end += 1; + } + while (end < text.len) { + const next_end = modal.nextGrapheme(text, end); + const next_used = used +| graphemeDisplayWidth(text[end..next_end]); + if (next_used > width) return if (end == start) next_end else end; + used = next_used; + end = next_end; + } + return end; +} + +test "the ASCII run in fitEnd cuts where the grapheme walk would" { + const reference = struct { + fn fitEnd(text: []const u8, start: usize, width: usize) usize { + var end = start; + var used: usize = 0; + while (end < text.len) { + const next_end = modal.nextGrapheme(text, end); + const next_used = used +| graphemeDisplayWidth(text[end..next_end]); + if (next_used > width) return if (end == start) next_end else end; + used = next_used; + end = next_end; + } + return end; + } + }.fitEnd; + + const cases = [_][]const u8{ + "", + "hello world", + // the fast path must hand over at the first non-ASCII byte, mid-run + "abc\u{00e9}def", + // a wide glyph is two columns, so a width boundary can land inside it + "ab\u{4e16}\u{754c}cd", + // a cluster the fast path must not split + "a\u{0301}bc", + // tabs and controls are excluded from the fast path by the range test + "ab\tcd", + "ab\rcd", + // an ASCII byte followed by a continuation byte is NOT its own cluster + "e\u{0301}x", + "\u{1f1e6}\u{1f1e7}ok", + }; + for (cases) |text| { + var width: usize = 0; + while (width <= text.len + 3) : (width += 1) { + var start: usize = 0; + while (start <= text.len) : (start += 1) { + try std.testing.expectEqual( + reference(text, start, width), + fitEnd(text, start, width), + ); + } + } + } +} + +pub fn lineCount(content: []const u8) usize { + return std.mem.count(u8, content, "\n") + 1; +} + +// Content changes invalidate this lazily rebuilt byte-offset index. +pub fn lineIndex(gpa: std.mem.Allocator, f: *State) ![]const usize { + if (f.line_starts.len > 0) return f.line_starts; + // Exact allocation: deinitPane frees `line_starts` itself, so the stored + // slice must span the complete allocation rather than spare capacity. + const starts = try gpa.alloc(usize, lineCount(f.content)); + starts[0] = 0; + var i: usize = 1; + var off: usize = 0; + while (std.mem.indexOfScalarPos(u8, f.content, off, '\n')) |nl| { + off = nl + 1; + starts[i] = off; + i += 1; + } + f.line_starts = starts; + return starts; +} + +/// The line index of `new` from `old`'s: an edit replaces one span, so +/// line starts before it stand, starts after it shift, and only the span +/// is scanned. Rebuilding scanned the whole file on every keystroke. +fn editedLineStarts(gpa: std.mem.Allocator, starts: []const usize, old: []const u8, new: []const u8) ![]usize { + const n = @min(old.len, new.len); + var head: usize = 0; + while (head + 64 <= n and std.mem.eql(u8, old[head..][0..64], new[head..][0..64])) head += 64; + while (head < n and old[head] == new[head]) head += 1; + var tail: usize = 0; + while (tail + 64 <= n - head and std.mem.eql(u8, old[old.len - tail - 64 ..][0..64], new[new.len - tail - 64 ..][0..64])) tail += 64; + while (tail < n - head and old[old.len - tail - 1] == new[new.len - tail - 1]) tail += 1; + // A start s follows the newline at s-1: kept while that newline is in + // the common head, shifted while it is in the common tail. + const kept = std.sort.upperBound(usize, starts, head, struct { + fn order(key: usize, item: usize) std.math.Order { + return std.math.order(key, item); + } + }.order); + const old_tail_at = old.len - tail; + const moved = starts.len - std.sort.upperBound(usize, starts, old_tail_at, struct { + fn order(key: usize, item: usize) std.math.Order { + return std.math.order(key, item); + } + }.order); + const middle = new[head .. new.len - tail]; + const out = try gpa.alloc(usize, kept + std.mem.count(u8, middle, "\n") + moved); + @memcpy(out[0..kept], starts[0..kept]); + var i = kept; + var off: usize = 0; + while (std.mem.indexOfScalarPos(u8, middle, off, '\n')) |nl| { + off = nl + 1; + out[i] = head + off; + i += 1; + } + for (starts[starts.len - moved ..]) |start| { + out[i] = start + new.len - old.len; + i += 1; + } + return out; +} + +test "edited line index equals a rebuilt one" { + const gpa = std.testing.allocator; + var prng = std.Random.DefaultPrng.init(7); + const r = prng.random(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(gpa); + for (0..300) |_| try text.append(gpa, "ab\n"[r.uintLessThan(usize, 3)]); + for (0..2000) |_| { + var old_state: State = undefined; + old_state.content = text.items; + old_state.line_starts = &.{}; + const starts = try lineIndex(gpa, &old_state); + defer gpa.free(starts); + // one random replace, like any edit through setContent + const at = r.uintAtMost(usize, text.items.len); + const del = r.uintAtMost(usize, @min(8, text.items.len - at)); + var ins: [8]u8 = undefined; + const ins_len = r.uintAtMost(usize, 8); + for (ins[0..ins_len]) |*c| c.* = "ab\n"[r.uintLessThan(usize, 3)]; + const old = try gpa.dupe(u8, text.items); + defer gpa.free(old); + try text.replaceRange(gpa, at, del, ins[0..ins_len]); + const edited = try editedLineStarts(gpa, starts, old, text.items); + defer gpa.free(edited); + var fresh_state: State = undefined; + fresh_state.content = text.items; + fresh_state.line_starts = &.{}; + const fresh = try lineIndex(gpa, &fresh_state); + defer gpa.free(fresh); + try std.testing.expectEqualSlices(usize, fresh, edited); + } +} + +/// line count, O(1) once the index is warm +pub fn nlines(gpa: std.mem.Allocator, f: *State) usize { + const idx = lineIndex(gpa, f) catch return lineCount(f.content); + return idx.len; +} + +/// byte offset of line `row`, or content.len past the end — modal +/// .lineStartOffset's contract exactly, without its walk +pub fn lineStart(gpa: std.mem.Allocator, f: *State, row: usize) usize { + const idx = lineIndex(gpa, f) catch return modal.lineStartOffset(f.content, row); + return if (row >= idx.len) f.content.len else idx[row]; +} + +pub fn cursorLines(arena: std.mem.Allocator, pane: *Pane, f: *State) ![]const []const u8 { + const index = try lineIndex(pane.gpa, f); + const lines = try arena.alloc([]const u8, index.len); + for (index, 0..) |start, i| { + const end = if (i + 1 < index.len) index[i + 1] - 1 else f.content.len; + lines[i] = f.content[start..end]; + } + return lines; +} + +/// Use the file's line index only when `text` is its complete live content. +/// Edit-buffer fragments and other temporary text retain modal's scan path. +fn contentIndex(pane: *Pane, text: []const u8) ?[]const usize { + const f = if (pane.file) |*file| file else return null; + if (text.ptr != f.content.ptr or text.len != f.content.len) return null; + return lineIndex(pane.gpa, f) catch null; +} + +pub fn textOffset(pane: *Pane, text: []const u8, cursor: modal.Cursor) usize { + const index = contentIndex(pane, text) orelse return modal.offsetAt(text, cursor); + const row = @min(cursor.row, index.len - 1); + const start = index[row]; + const end = if (row + 1 < index.len) index[row + 1] - 1 else text.len; + return start + modal.graphemeStart(text[start..end], @min(cursor.col, end - start)); +} + +pub fn textLineStart(pane: *Pane, text: []const u8, row: usize) usize { + const index = contentIndex(pane, text) orelse return modal.lineStartOffset(text, row); + return if (row >= index.len) text.len else index[row]; +} + +pub fn textLine(pane: *Pane, text: []const u8, row: usize) []const u8 { + const index = contentIndex(pane, text) orelse return modal.lineSlice(text, row); + if (row >= index.len) return ""; + const start = index[row]; + const end = if (row + 1 < index.len) index[row + 1] - 1 else text.len; + return text[start..end]; +} + +test "indexed text rows preserve fragment and allocation failure semantics" { + var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + const p = try Pardes.init(allocator.allocator(), .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("first\n\tλ界\n\nlast\n"); + const text = pane.file.?.content; + allocator.fail_index = allocator.alloc_index; + for (0..lineCount(text) + 2) |row| try std.testing.expectEqualStrings(modal.lineSlice(text, row), textLine(pane, text, row)); + try std.testing.expectEqual(@as(usize, 0), pane.file.?.line_starts.len); + allocator.fail_index = std.math.maxInt(usize); + _ = try lineIndex(p.gpa, &pane.file.?); + allocator.fail_index = allocator.alloc_index; + const allocations = allocator.allocations; + for ([_][]const u8{ text, text[2..], text[0..8], "other\nrows\n\n", "" }) |fragment| { + for (0..lineCount(fragment) + 2) |row| try std.testing.expectEqualStrings( + modal.lineSlice(fragment, row), + textLine(pane, fragment, row), + ); + } + try std.testing.expectEqual(allocations, allocator.allocations); +} + +pub fn textLineCount(pane: *Pane, text: []const u8) usize { + const index = contentIndex(pane, text) orelse return modal.cursorLineCount(text); + return index.len; +} + +pub fn textPosition(pane: *Pane, text: []const u8, offset: usize) modal.Cursor { + const index = contentIndex(pane, text) orelse return modal.positionAt(text, offset); + const bounded = @min(offset, text.len); + const row = std.sort.upperBound(usize, index, bounded, struct { + fn cmp(key: usize, item: usize) std.math.Order { + return std.math.order(key, item); + } + }.cmp) - 1; + const start = index[row]; + const end = if (row + 1 < index.len) index[row + 1] - 1 else text.len; + return .{ .row = row, .col = modal.graphemeStart(text[start..end], @min(bounded - start, end - start)) }; +} + +pub fn open(p: *Pardes, id: usize, path: []const u8, line: usize) !*Pane { + std.debug.assert(p.panes[id] == null and !p.reserved_slots[id]); + const path_copy = try p.gpa.dupe(u8, path); + errdefer p.gpa.free(path_copy); + const pane = try Terminal.createDoc(p.gpa, p.screen_w, p.screen_h); + errdefer p.gpa.destroy(pane); + const history = try History.create(p.gpa); + errdefer p.gpa.destroy(history); + p.reserved_slots[id] = true; + defer p.reserved_slots[id] = false; + const content = try filesystem.read(p, path); + errdefer p.gpa.free(content); + const total = lineCount(content); + const scroll: usize = if (line > 0 and line <= total) line - 1 else 0; + pane.file = .{ .path = path_copy, .content = content, .scroll = scroll, .history = history }; + pane.cur_pinned = true; + pane.cur_row = @intCast(scroll); + p.installPane(id, pane); + if (filesystem.localPath(path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } }); + return pane; +} + +pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { + const saved = src.file.?; + if (saved.mini_source.len > 0) { + const encoded_limit = std.base64.standard.Encoder.calcSize(Mini.max_output_bytes); + if (saved.mini_source.len >= 4096 or saved.content.len > Mini.max_output_bytes or + saved.content_b64.len > encoded_limit or saved.mini_colors_b64.len > encoded_limit) + return error.InvalidMini; + } + const content: []u8 = if (saved.content_b64.len > 0) + try dump.decodeBytes(p.gpa, saved.content_b64) + else + try p.gpa.dupe(u8, saved.content); + errdefer p.gpa.free(content); + const path = try p.gpa.dupe(u8, saved.path); + errdefer p.gpa.free(path); + + const output: ?Output.State = if (Output.fromWord(saved.origin)) |origin| blk: { + var value: Output.State = .{ .from = origin }; + try Output.setArg(&value, saved.origin_arg); + break :blk value; + } else null; + + if (saved.location_rows.len != 0 and output == null) return error.InvalidLocationRows; + const location_rows = try restoreLocationRows(p.gpa, content, saved.location_rows); + errdefer locations.freeRows(p.gpa, location_rows); + + var mini: ?Mini.State = null; + errdefer if (mini) |*state| state.deinit(p.gpa); + if (saved.mini_source.len > 0) { + if (output == null or !std.meta.eql(output.?.from, Output.Origin{ .cmd = .Mini })) return error.InvalidMini; + const source = try p.gpa.dupe(u8, saved.mini_source); + errdefer p.gpa.free(source); + const colors = try dump.decodeBytes(p.gpa, saved.mini_colors_b64); + errdefer p.gpa.free(colors); + if (colors.len != content.len or colors.len > Mini.max_output_bytes) return error.InvalidMini; + for (colors) |color| if (color > @intFromEnum(syntax.Syn.comment)) return error.InvalidMini; + mini = .{ .source = source, .colors = colors }; + } else if (saved.mini_colors_b64.len > 0) return error.InvalidMini; + + const history = try History.create(p.gpa); + errdefer p.gpa.destroy(history); + const pane = try p.newDocPane(id); + pane.file = .{ + .path = path, + .content = content, + .output = output, + .mini = mini, + .location_rows = location_rows, + .scroll = src.scroll, + .revision = @intFromBool(saved.dirty), + .history = history, + }; + pane.file.?.tree_context = saved.tree_context and supportsContext(pane); + pane.cur_pinned = true; + pane.cur_row = @intCast(src.scroll); + pane.cols = @max(1, src.cols); + pane.rows = @max(1, src.rows); + if (output == null and filesystem.localPath(path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true, .mode = .baseline_disk } }); + return pane; +} + +pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { + if (file.output == null) for (p.panes, 0..) |slot, id| { + if (slot == pane) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); + }; + p.gpa.free(file.path); + p.gpa.free(file.content); + if (file.mini) |*mini| mini.deinit(p.gpa); + if (file.line_starts.len > 0) p.gpa.free(file.line_starts); + if (file.highlights.len > 0) p.tree_sitter_gpa.free(file.highlights); + locations.freeRows(p.gpa, file.location_rows); + if (file.context_declarations.len > 0) p.tree_sitter_gpa.free(file.context_declarations); + for (file.history.undo[0..file.history.undo_len]) |snap| p.gpa.free(snap.content); + for (file.history.redo[0..file.history.redo_len]) |snap| p.gpa.free(snap.content); + p.gpa.destroy(file.history); +} + +fn reportEdit(p: *Pardes, f: *State, new: []const u8) void { + if (p.fs.listeners == 0) return; + const id = for (p.panes, 0..) |slot, i| { + const pane = slot orelse continue; + if (pane.file) |*state| if (state == f) break i; + } else return; + pardes.ctlfs.events.noteReplace(p, id, false, f.content, new); +} + +pub fn setContent(p: *Pardes, f: *State, new: []u8) void { + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = &.{}; + for (p.panes) |slot| if (slot) |pane| { + if (pane.file) |*file| if (file == f) { + for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + } + }; + }; + reportEdit(p, f, new); + if (f.mini) |*mini| mini.deinit(p.gpa); + f.mini = null; + const starts: []usize = if (f.line_starts.len > 0) editedLineStarts(p.gpa, f.line_starts, f.content, new) catch &.{} else &.{}; + p.gpa.free(f.content); + f.content = new; + f.revision +%= 1; + f.mtime = pardes.ctlfs.events.now(); + if (f.line_starts.len > 0) p.gpa.free(f.line_starts); + f.line_starts = starts; + if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); + f.highlights = &.{}; + f.highlight_start = 0; + f.syntax_dirty = true; +} + +pub fn restoreSnap(pane: *Pane, f: *State, snap: Snapshot) void { + const n = nlines(pane.gpa, f); + const row: usize = @min(@as(usize, @intCast(@max(0, snap.cur_row))), n - 1); + const llen = modal.lineSlice(f.content, row).len; + pane.cur_row = @intCast(row); + pane.cur_col = @intCast(@min(@as(usize, @intCast(@max(0, snap.cur_col))), llen)); + pane.vsel = snap.vsel; + pane.msel.active = false; + pane.cur_pinned = true; + pane.sticky_col = -1; + pane.ensureCursorVisible(); +} + +fn pushHistory(gpa: std.mem.Allocator, slots: []Snapshot, len: *usize, snap: Snapshot) void { + if (len.* == slots.len) { + gpa.free(slots[0].content); + std.mem.copyForwards(Snapshot, slots[0 .. slots.len - 1], slots[1..]); + len.* -= 1; + } + slots[len.*] = snap; + len.* += 1; +} + +pub fn pushUndo(p: *Pardes, pane: *Pane) void { + const f = if (pane.file) |*file| file else return; + const history = f.history; + if (history.undo_len > 0 and std.mem.eql(u8, history.undo[history.undo_len - 1].content, f.content)) return; + const snap: Snapshot = .{ + .content = p.gpa.dupe(u8, f.content) catch return, + .cur_row = pane.cur_row, + .cur_col = pane.cur_col, + .vsel = pane.vsel, + }; + pushHistory(p.gpa, &history.undo, &history.undo_len, snap); + for (history.redo[0..history.redo_len]) |item| p.gpa.free(item.content); + history.redo_len = 0; +} + +pub fn undo(p: *Pardes, pane: *Pane) void { + const f = if (pane.file) |*file| file else return; + const history = f.history; + if (history.undo_len == 0) return; + const current: Snapshot = .{ + .content = p.gpa.dupe(u8, f.content) catch return, + .cur_row = pane.cur_row, + .cur_col = pane.cur_col, + .vsel = pane.vsel, + }; + pushHistory(p.gpa, &history.redo, &history.redo_len, current); + history.undo_len -= 1; + const previous = history.undo[history.undo_len]; + setContent(p, f, previous.content); + restoreSnap(pane, f, previous); +} + +pub fn redo(p: *Pardes, pane: *Pane) void { + const f = if (pane.file) |*file| file else return; + const history = f.history; + if (history.redo_len == 0) return; + const current: Snapshot = .{ + .content = p.gpa.dupe(u8, f.content) catch return, + .cur_row = pane.cur_row, + .cur_col = pane.cur_col, + .vsel = pane.vsel, + }; + pushHistory(p.gpa, &history.undo, &history.undo_len, current); + history.redo_len -= 1; + const next = history.redo[history.redo_len]; + setContent(p, f, next.content); + restoreSnap(pane, f, next); +} + +/// Commit an externally rewritten file onto the same undo history as typed +/// edits. Unsaved work remains one `u` away; there is no third merge state. +pub fn changed(p: *Pardes, id: u8, bytes: []const u8) void { + const pane = p.panes[id] orelse return; + const f = if (pane.file) |*file| file else return; + if (std.mem.eql(u8, f.content, bytes)) return; + const new = p.gpa.dupe(u8, bytes) catch return; + pushUndo(p, pane); + setContent(p, f, new); + f.saved_revision = f.revision; + // restoreSnap only consumes cursor/selection from this synthetic snapshot. + restoreSnap(pane, f, .{ + .content = undefined, + .cur_row = pane.cur_row, + .cur_col = pane.cur_col, + .vsel = pane.vsel, + }); +} + +/// re-highlight the visible window of any file whose syntax went stale +/// (edit, scroll, load) — visible-range-first so big files stay snappy +pub fn refreshHighlights(p: *Pardes) void { + const tz = tracy.zone(@src(), "refreshHighlights"); + defer tz.end(); + for (p.panes) |slot| { + const pane = slot orelse continue; + if (pane.file == null) continue; + const f = &pane.file.?; + if (f.tree_context and supportsContext(pane) and f.context_revision != f.revision) { + const declarations = syntax.contextDeclarations(p.tree_sitter_gpa, f.path, f.content) catch continue; + if (f.context_declarations.len > 0) p.tree_sitter_gpa.free(f.context_declarations); + f.context_declarations = declarations; + f.context_revision = f.revision; + } + if (f.mini != null) { + f.syntax_dirty = false; + continue; + } + if (!f.syntax_dirty) continue; + if (!p.settings.colors) { + if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); + f.highlights = &.{}; + f.highlight_start = 0; + f.syntax_dirty = false; + continue; + } + const need_start = lineStart(p.gpa, f, f.scroll); + const need_end = @max(need_start, lineStart(p.gpa, f, f.scroll + pane.rows + SYNTAX_CONTEXT_AFTER_ROWS)); + if ((!f.tree_context or (f.highlight_start == 0 and f.highlights.len == f.content.len)) and + f.highlights.len > 0 and need_start >= f.highlight_start and + need_end <= f.highlight_start + f.highlights.len) + { + f.syntax_dirty = false; + continue; + } + const slack: usize = if (f.highlights.len == 0) 0 else pane.rows; + const whole = pane.colorAlgo() == .locations or f.tree_context; + const start = if (whole) 0 else lineStart(p.gpa, f, f.scroll -| slack); + const end = if (whole) + f.content.len + else + @max(start, lineStart(p.gpa, f, f.scroll + pane.rows + SYNTAX_CONTEXT_AFTER_ROWS + slack)); + const new_highlights = (switch (pane.colorAlgo()) { + .none => @as([]u8, &.{}), + .diff => syntax.highlightDiff(p.tree_sitter_gpa, f.content, start, end), + .locations => if (f.location_rows.len > 0) + syntax.highlightLocationRows(p.tree_sitter_gpa, f.content, f.location_rows) + else + syntax.highlightLocations(p.tree_sitter_gpa, f.content, start, end), + else => syntax.highlightFileRange(p.tree_sitter_gpa, f.path, f.content, start, end), + }) catch { + f.syntax_dirty = false; + continue; + }; + if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); + f.highlights = new_highlights; + f.highlight_start = if (f.highlights.len > 0) start else 0; + f.syntax_dirty = false; + } +} + +pub fn supportsContext(pane: *const Pane) bool { + const file = pane.file orelse return false; + return file.output == null and file.mini == null and syntax.supportsPath(file.path); +} + +fn prepareContextRows(pane: *Pane, file: *State) void { + pane.context_rows = 0; + if (!file.tree_context or !supportsContext(pane) or pane.rows > pane.wrap_line.len) return; + const capacity = @min(pane.rows -| 1, pane.context_row_limit orelse std.math.maxInt(u16)); // retain an ordinary body row + for (file.context_declarations) |declaration| { + if (declaration.start_line >= file.scroll) break; + if (declaration.end_line < file.scroll) continue; + var row = declaration.start_line; + while (row <= declaration.header_end_line and row < file.scroll) : (row += 1) { + if (pane.context_rows >= capacity) return; + if (pane.context_rows > 0 and row <= pane.wrap_line[pane.context_rows - 1]) continue; + pane.wrap_line[pane.context_rows] = @intCast(row); + pane.context_rows += 1; + } + } +} + +pub fn wrapWidth(pane: *const Pane, wrap: bool) usize { + if (!wrap or pane.rows > pane.wrap_line.len) return 0; + return @max(1, @as(usize, pane.cols -| gutterWidth(pane)) -| 1); +} + +pub const VisualRow = struct { start: usize, end: usize }; + +pub fn visualRow(line: []const u8, col: usize, width: usize) VisualRow { + if (width == 0) return .{ .start = 0, .end = line.len }; + var start: usize = 0; + while (true) { + const end = fitEnd(line, start, width); + if (col < end or end >= line.len) return .{ .start = start, .end = end }; + start = end; + } +} + +pub fn bodyText(arena: std.mem.Allocator, pane: *Pane, f: *State, wrap: bool) ![]const u8 { + const width = wrapWidth(pane, wrap); + pane.body_wrapped = width > 0; + prepareContextRows(pane, f); + pane.wrap_n = 0; + + const len = fillBody(null, pane, f, width, false); + const out = try arena.alloc(u8, len); + const filled = fillBody(out, pane, f, width, true); + std.debug.assert(filled == out.len); + return out; +} + +/// Run the file-body row walk. With no destination it is the exact sizing +/// pass; with one it fills that allocation and records the wrapping map. +fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) usize { + if (record_wrap) pane.wrap_n = 0; + const prefix_width = gutterWidth(pane); + const total = nlines(pane.gpa, f); + var body_line: usize = f.scroll; + var body_at: usize = 0; + var written: usize = 0; + for (0..if (pane.body_rows > 0) pane.body_rows else pane.rows) |i| { + if (i > 0) { + if (dst) |out| out[written] = '\n'; + written += 1; + } + const context = i < pane.context_rows; + const row = if (context) @as(usize, @intCast(pane.wrap_line[i])) else body_line; + const at = if (context) 0 else body_at; + const text = if (row < total) sourceLine(pane, @intCast(row)) else ""; + // Headers use one screen row per source row, preserving signatures + // without allowing a long ancestor to consume the whole viewport. + const end = if (width == 0 or context) text.len else fitEnd(text, at, width); + const cut = if (pane.hscroll > 0 and width == 0) + modal.graphemeStart(text, @min(@as(usize, @intCast(pane.hscroll)), text.len)) + else + at; + if ((width > 0 or pane.context_rows > 0) and record_wrap) { + pane.wrap_line[i] = @intCast(row); + pane.wrap_col[i] = @intCast(cut); + pane.wrap_n = @intCast(i + 1); + } + if (row < total) { + var lbuf: [@max(config.PREFIX_W, 32)]u8 = undefined; + const prefix = lbuf[0..prefix_width]; + @memset(prefix, ' '); + if (at == 0) { + var lineno = row + 1; + var digit: usize = prefix.len - 1; + while (true) { + digit -= 1; + prefix[digit] = '0' + @as(u8, @intCast(lineno % 10)); + lineno /= 10; + if (lineno == 0) break; + } + } + if (dst) |out| @memcpy(out[written..][0..prefix.len], prefix); + written += prefix.len; + const shown = text[cut..end]; + if (dst) |out| @memcpy(out[written..][0..shown.len], shown); + written += shown.len; + } + if (!context) { + if (width > 0 and end < text.len) { + body_at = end; + } else { + body_line += 1; + body_at = 0; + } + } + } + return written; +} + +pub fn drawGutter(p: *Pardes, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, active: bool) void { + const s = &p.surface; + const prefix_width = gutterWidth(pane); + const goff = pane.scroll(); + const gcur = Terminal.gridCursor(pane); + const gcrow = if (pane.cur_pinned) pane.cur_row else @as(i32, gcur.y) + goff; + const cur_line: i32 = if (active and !pane.tag_edit) gcrow else std.math.minInt(i32); + // the body's first row, the way renderPane derives it (Tagbottom) + const body_y = p.bodyTop(r); + const context_bg = p.theme().tag_bg; + for (0..@min(pane.context_rows, body_h)) |context_row| { + for (0..tw) |col| { + const cell = s.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(context_row))); + cell.default = false; + cell.style.bg = .{ .rgb = context_bg }; + if (p.settings.tree_context_tag_style) cell.style.font_role = .tagline; + } + } + var vr: u16 = 0; + while (vr < body_h) : (vr += 1) { + const row_line: i32 = if (pane.wrap_n == 0) + goff + @as(i32, vr) + else if (vr < pane.wrap_n) pane.wrap_line[vr] else std.math.maxInt(i32); + const on_cursor = row_line == cur_line; + var c: u16 = 0; + while (c < prefix_width and c < tw) : (c += 1) { + const cell = s.at(tx + c, body_y + vr); + cell.default = false; // paints blank gutter rows too + cell.style.fg = .{ .rgb = if (on_cursor) + p.theme().lineno_active orelse p.theme().lineno + else + p.theme().lineno }; + cell.style.bold = on_cursor; + } + } +} + +const SynStyle = struct { fg: [3]u8, bold: bool }; + +fn synStyle(p: *Pardes, sy: syntax.Syn) ?SynStyle { + return switch (sy) { + .none => null, + .keyword => .{ .fg = p.theme().kw, .bold = p.settings.syntax_bold }, + .string => .{ .fg = p.theme().str, .bold = false }, + .number => .{ .fg = p.theme().num, .bold = false }, + .comment => .{ .fg = p.theme().comment, .bold = false }, + }; +} + +/// syntax colors: recolor each content cell from its tree-sitter style byte; +/// content starts after the lineno gutter +pub fn recolorSyntax(p: *Pardes, pane: *Pane, f: *State, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void { + const highlights = if (f.mini) |mini| mini.colors else f.highlights; + const highlight_start = if (f.mini != null) 0 else f.highlight_start; + if (highlights.len == 0 and f.output == null) return; + const s = &p.surface; + const prefix_width = gutterWidth(pane); + const tz_recolor = tracy.zone(@src(), "synRecolor"); + defer tz_recolor.end(); + // indexed start, same as bodyText — an empty tail simply paints nothing + var flines = std.mem.splitScalar(u8, f.content[lineStart(p.gpa, f, f.scroll)..], '\n'); + const total = nlines(p.gpa, f); + const body_y = p.bodyTop(r); + var vr: u16 = 0; + while (vr < body_h) : (vr += 1) { + var base: usize = undefined; + var line: []const u8 = undefined; + var hs: usize = @intCast(@max(0, pane.hscroll)); + var limit: usize = undefined; + if (pane.wrap_n == 0) { + line = flines.next() orelse break; + base = @intFromPtr(line.ptr) - @intFromPtr(f.content.ptr); + limit = line.len; + } else { + if (vr >= pane.wrap_n) break; + const lrow: usize = @intCast(@max(0, pane.wrap_line[vr])); + if (lrow >= total) break; + base = lineStart(p.gpa, f, lrow); + const lend = if (lrow + 1 < total) lineStart(p.gpa, f, lrow + 1) -| 1 else f.content.len; + line = f.content[base..lend]; + hs = @intCast(pane.wrap_col[vr]); + limit = if (vr + 1 < pane.wrap_n and pane.wrap_line[vr + 1] == pane.wrap_line[vr]) + @min(line.len, @as(usize, @intCast(pane.wrap_col[vr + 1]))) + else + line.len; + } + hs = modal.graphemeStart(line, @min(hs, line.len)); + const row_index: usize = @intCast(@max(0, pane.wrapAt(vr).line)); + const metadata: ?locations.Row = if (row_index < f.location_rows.len) f.location_rows[row_index] else null; + const decoration = Output.decorateRow(f.output, line, metadata); + var c: usize = 0; + var screen_c: usize = 0; + while (hs + c < limit and prefix_width + screen_c < tw) { + const grapheme_end = @min(limit, modal.nextGrapheme(line, hs + c)); + const cells = graphemeDisplayWidth(line[hs + c .. grapheme_end]); + const idx = base + hs + c; + if (idx >= highlight_start) { + const hidx = idx - highlight_start; + if (hidx < highlights.len) { + if (synStyle(p, @enumFromInt(highlights[hidx]))) |ss| { + var fill: usize = 0; + while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) { + const cell = s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr); + if (cell.default) continue; + cell.style.fg = .{ .rgb = ss.fg }; + cell.style.bold = ss.bold; + } + } + } + } + // Results keep their exact live text. Only the location, + // matched source range and diagnostic label gain emphasis. + if (decoration.styleAt(p, hs + c)) |style| { + var fill: usize = 0; + while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) { + const cell = s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr); + if (cell.default) continue; + cell.style.fg = style.fg; + cell.style.bold = style.bold; + if (style.bg != .default) cell.style.bg = style.bg; + } + } + screen_c += cells; + c = grapheme_end - hs; + } + } +} + +pub fn drawWrapMarkers( + p: *Pardes, + pane: *const Pane, + r: pardes.Rect, + tx: u16, + tw: u16, + body_h: u16, + pane_bg: pardes.Color, +) void { + if (tw <= gutterWidth(pane) + 1) return; + const body_y = p.bodyTop(r); + const marker_fg = p.chromeTheme().lineno; + var row: u16 = 0; + while (row + 1 < pane.wrap_n and row + 1 < body_h) : (row += 1) { + if (pane.wrap_line[row + 1] != pane.wrap_line[row]) continue; + p.surface.set(tx + tw - 1, body_y + row, config.wrap_marker, .{ + .fg = .{ .rgb = marker_fg }, + .bg = pane_bg, + }); + } +} + +pub fn paintWordSelection( + p: *Pardes, + pane: *Pane, + r: pardes.Rect, + row: i32, + word_lo: i32, + word_hi: i32, + bg: [3]u8, +) void { + const tx = r.x + config.GUTTER; + const tw = r.w - config.GUTTER; + const prefix_width = gutterWidth(pane); + const body_y = p.bodyTop(r); + var vr: i32 = 0; + while (vr + @as(i32, pardes.BOX_H) < @as(i32, r.h)) : (vr += 1) { + const here = pane.wrapAt(vr); + if (here.line != row) continue; + var hi = word_hi; + const next = pane.wrapAt(vr + 1); + if (next.line == row) hi = @min(hi, next.at); + const lo = @max(word_lo, here.at); + if (hi <= lo) continue; + const c0 = @as(i32, prefix_width) + displayOffset(pane, row, here.at, lo); + const c1 = @as(i32, prefix_width) + displayEndOffset(pane, row, here.at, hi - 1); + var col = @max(@as(i32, prefix_width), c0); + while (col <= c1 and col < @as(i32, tw)) : (col += 1) { + const cell = p.surface.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(vr))); + cell.default = false; + cell.style.bg = .{ .rgb = bg }; + } + } +} -- cgit v1.3 From 95a3a1bb822e583988bfe0f312d0ef219b27a454 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 23:06:11 -0300 Subject: Give a pane's body its own Text holding the cursor, selections, mode and undo acme keeps what edits a text in its Text (dat.h:171-190) and the window holds a body and a tag of that type. The cursor, the selections, the modal state and the edit-buffer undo move off Pane into Text.zig, Pane holds them as its body, and the edit and normal-mode operations take the Text they edit. Nothing changes in behaviour; this is the step that lets the tag become a second Text. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 78 ++-- src/Mini.zig | 2 +- src/Output.zig | 22 +- src/Pipe.zig | 52 +-- src/Terminal.zig | 114 +++--- src/Text.zig | 606 ++++++++++++++++++++++++++++ src/body_layer.zig | 44 +- src/colors.zig | 6 +- src/config.zig | 6 +- src/detached/client.zig | 6 +- src/detached/server.zig | 4 +- src/dump.zig | 4 +- src/edit.zig | 1020 ++++++++++++++++++++++++----------------------- src/exec.zig | 40 +- src/gui/gui.zig | 14 +- src/host_io.zig | 2 +- src/layout.zig | 2 +- src/look.zig | 106 ++--- src/macos.zig | 8 +- src/mouse.zig | 130 +++--- src/ninep/ctl.zig | 18 +- src/ninep/pane.zig | 26 +- src/normal.zig | 464 ++++++++++----------- src/panes.zig | 623 +---------------------------- src/pardes.zig | 239 +++++------ src/pdf_view.zig | 48 +-- src/tty/tty.zig | 6 +- test/fs_bench.zig | 4 +- test/hxdiff.zig | 34 +- test/mode.zig | 28 +- test/output.zig | 128 +++--- test/panes.zig | 398 +++++++++--------- test/pdf.zig | 42 +- test/perf.zig | 78 ++-- 34 files changed, 2224 insertions(+), 2178 deletions(-) create mode 100644 src/Text.zig (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index eb1c6a7c..239aa4ba 100644 --- a/src/File.zig +++ b/src/File.zig @@ -17,16 +17,17 @@ const Pane = panes.Pane; const Output = panes.Output; const Mini = panes.Mini; const Terminal = panes.Terminal; +const Text = panes.Text; const SYNTAX_CONTEXT_AFTER_ROWS: usize = 2; /// Content and primary selection at one file edit boundary. Keeping only the -/// primary avoids putting Pane.max_selections ranges in every history entry. +/// primary avoids putting Text.max_selections ranges in every history entry. pub const Snapshot = struct { content: []u8, cur_row: i32, cur_col: i32, - vsel: Pane.CharSel, + vsel: Text.CharSel, }; pub const History = struct { @@ -652,27 +653,28 @@ pub fn cursorLines(arena: std.mem.Allocator, pane: *Pane, f: *State) ![]const [] /// Use the file's line index only when `text` is its complete live content. /// Edit-buffer fragments and other temporary text retain modal's scan path. -fn contentIndex(pane: *Pane, text: []const u8) ?[]const usize { +fn contentIndex(t: *Text, text: []const u8) ?[]const usize { + const pane = t.pane(); const f = if (pane.file) |*file| file else return null; if (text.ptr != f.content.ptr or text.len != f.content.len) return null; return lineIndex(pane.gpa, f) catch null; } -pub fn textOffset(pane: *Pane, text: []const u8, cursor: modal.Cursor) usize { - const index = contentIndex(pane, text) orelse return modal.offsetAt(text, cursor); +pub fn textOffset(t: *Text, text: []const u8, cursor: modal.Cursor) usize { + const index = contentIndex(t, text) orelse return modal.offsetAt(text, cursor); const row = @min(cursor.row, index.len - 1); const start = index[row]; const end = if (row + 1 < index.len) index[row + 1] - 1 else text.len; return start + modal.graphemeStart(text[start..end], @min(cursor.col, end - start)); } -pub fn textLineStart(pane: *Pane, text: []const u8, row: usize) usize { - const index = contentIndex(pane, text) orelse return modal.lineStartOffset(text, row); +pub fn textLineStart(t: *Text, text: []const u8, row: usize) usize { + const index = contentIndex(t, text) orelse return modal.lineStartOffset(text, row); return if (row >= index.len) text.len else index[row]; } -pub fn textLine(pane: *Pane, text: []const u8, row: usize) []const u8 { - const index = contentIndex(pane, text) orelse return modal.lineSlice(text, row); +pub fn textLine(t: *Text, text: []const u8, row: usize) []const u8 { + const index = contentIndex(t, text) orelse return modal.lineSlice(text, row); if (row >= index.len) return ""; const start = index[row]; const end = if (row + 1 < index.len) index[row + 1] - 1 else text.len; @@ -686,7 +688,7 @@ test "indexed text rows preserve fragment and allocation failure semantics" { const pane = try p.setTestFile("first\n\tλ界\n\nlast\n"); const text = pane.file.?.content; allocator.fail_index = allocator.alloc_index; - for (0..lineCount(text) + 2) |row| try std.testing.expectEqualStrings(modal.lineSlice(text, row), textLine(pane, text, row)); + for (0..lineCount(text) + 2) |row| try std.testing.expectEqualStrings(modal.lineSlice(text, row), textLine(&pane.body, text, row)); try std.testing.expectEqual(@as(usize, 0), pane.file.?.line_starts.len); allocator.fail_index = std.math.maxInt(usize); _ = try lineIndex(p.gpa, &pane.file.?); @@ -695,19 +697,19 @@ test "indexed text rows preserve fragment and allocation failure semantics" { for ([_][]const u8{ text, text[2..], text[0..8], "other\nrows\n\n", "" }) |fragment| { for (0..lineCount(fragment) + 2) |row| try std.testing.expectEqualStrings( modal.lineSlice(fragment, row), - textLine(pane, fragment, row), + textLine(&pane.body, fragment, row), ); } try std.testing.expectEqual(allocations, allocator.allocations); } -pub fn textLineCount(pane: *Pane, text: []const u8) usize { - const index = contentIndex(pane, text) orelse return modal.cursorLineCount(text); +pub fn textLineCount(t: *Text, text: []const u8) usize { + const index = contentIndex(t, text) orelse return modal.cursorLineCount(text); return index.len; } -pub fn textPosition(pane: *Pane, text: []const u8, offset: usize) modal.Cursor { - const index = contentIndex(pane, text) orelse return modal.positionAt(text, offset); +pub fn textPosition(t: *Text, text: []const u8, offset: usize) modal.Cursor { + const index = contentIndex(t, text) orelse return modal.positionAt(text, offset); const bounded = @min(offset, text.len); const row = std.sort.upperBound(usize, index, bounded, struct { fn cmp(key: usize, item: usize) std.math.Order { @@ -734,8 +736,8 @@ pub fn open(p: *Pardes, id: usize, path: []const u8, line: usize) !*Pane { const total = lineCount(content); const scroll: usize = if (line > 0 and line <= total) line - 1 else 0; pane.file = .{ .path = path_copy, .content = content, .scroll = scroll, .history = history }; - pane.cur_pinned = true; - pane.cur_row = @intCast(scroll); + pane.body.cur_pinned = true; + pane.body.cur_row = @intCast(scroll); p.installPane(id, pane); if (filesystem.localPath(path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } }); return pane; @@ -794,8 +796,8 @@ pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { .history = history, }; pane.file.?.tree_context = saved.tree_context and supportsContext(pane); - pane.cur_pinned = true; - pane.cur_row = @intCast(src.scroll); + pane.body.cur_pinned = true; + pane.body.cur_row = @intCast(src.scroll); pane.cols = @max(1, src.cols); pane.rows = @max(1, src.rows); if (output == null and filesystem.localPath(path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true, .mode = .baseline_disk } }); @@ -858,12 +860,12 @@ pub fn restoreSnap(pane: *Pane, f: *State, snap: Snapshot) void { const n = nlines(pane.gpa, f); const row: usize = @min(@as(usize, @intCast(@max(0, snap.cur_row))), n - 1); const llen = modal.lineSlice(f.content, row).len; - pane.cur_row = @intCast(row); - pane.cur_col = @intCast(@min(@as(usize, @intCast(@max(0, snap.cur_col))), llen)); - pane.vsel = snap.vsel; - pane.msel.active = false; - pane.cur_pinned = true; - pane.sticky_col = -1; + pane.body.cur_row = @intCast(row); + pane.body.cur_col = @intCast(@min(@as(usize, @intCast(@max(0, snap.cur_col))), llen)); + pane.body.vsel = snap.vsel; + pane.body.msel.active = false; + pane.body.cur_pinned = true; + pane.body.sticky_col = -1; pane.ensureCursorVisible(); } @@ -883,9 +885,9 @@ pub fn pushUndo(p: *Pardes, pane: *Pane) void { if (history.undo_len > 0 and std.mem.eql(u8, history.undo[history.undo_len - 1].content, f.content)) return; const snap: Snapshot = .{ .content = p.gpa.dupe(u8, f.content) catch return, - .cur_row = pane.cur_row, - .cur_col = pane.cur_col, - .vsel = pane.vsel, + .cur_row = pane.body.cur_row, + .cur_col = pane.body.cur_col, + .vsel = pane.body.vsel, }; pushHistory(p.gpa, &history.undo, &history.undo_len, snap); for (history.redo[0..history.redo_len]) |item| p.gpa.free(item.content); @@ -898,9 +900,9 @@ pub fn undo(p: *Pardes, pane: *Pane) void { if (history.undo_len == 0) return; const current: Snapshot = .{ .content = p.gpa.dupe(u8, f.content) catch return, - .cur_row = pane.cur_row, - .cur_col = pane.cur_col, - .vsel = pane.vsel, + .cur_row = pane.body.cur_row, + .cur_col = pane.body.cur_col, + .vsel = pane.body.vsel, }; pushHistory(p.gpa, &history.redo, &history.redo_len, current); history.undo_len -= 1; @@ -915,9 +917,9 @@ pub fn redo(p: *Pardes, pane: *Pane) void { if (history.redo_len == 0) return; const current: Snapshot = .{ .content = p.gpa.dupe(u8, f.content) catch return, - .cur_row = pane.cur_row, - .cur_col = pane.cur_col, - .vsel = pane.vsel, + .cur_row = pane.body.cur_row, + .cur_col = pane.body.cur_col, + .vsel = pane.body.vsel, }; pushHistory(p.gpa, &history.undo, &history.undo_len, current); history.redo_len -= 1; @@ -939,9 +941,9 @@ pub fn changed(p: *Pardes, id: u8, bytes: []const u8) void { // restoreSnap only consumes cursor/selection from this synthetic snapshot. restoreSnap(pane, f, .{ .content = undefined, - .cur_row = pane.cur_row, - .cur_col = pane.cur_col, - .vsel = pane.vsel, + .cur_row = pane.body.cur_row, + .cur_col = pane.body.cur_col, + .vsel = pane.body.vsel, }); } @@ -1126,7 +1128,7 @@ pub fn drawGutter(p: *Pardes, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, bod const prefix_width = gutterWidth(pane); const goff = pane.scroll(); const gcur = Terminal.gridCursor(pane); - const gcrow = if (pane.cur_pinned) pane.cur_row else @as(i32, gcur.y) + goff; + const gcrow = if (pane.body.cur_pinned) pane.body.cur_row else @as(i32, gcur.y) + goff; const cur_line: i32 = if (active and !pane.tag_edit) gcrow else std.math.minInt(i32); // the body's first row, the way renderPane derives it (Tagbottom) const body_y = p.bodyTop(r); diff --git a/src/Mini.zig b/src/Mini.zig index 52e26a37..e118e738 100644 --- a/src/Mini.zig +++ b/src/Mini.zig @@ -187,7 +187,7 @@ pub fn open(p: *Pardes, id: usize, argument: []const u8) !void { .history = history, .syntax_dirty = false, }; - pane.cur_pinned = true; + pane.body.cur_pinned = true; exec.placeDoc(p, id, free, pane); p.active = free; } diff --git a/src/Output.zig b/src/Output.zig index 6df2fd34..6e1765a7 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -402,7 +402,7 @@ pub fn open(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []const u errdefer p.gpa.destroy(history); const pane = try p.newDocPane(id); pane.file = .{ .path = path, .content = content, .output = out, .history = history }; - pane.cur_pinned = true; + pane.body.cur_pinned = true; return pane; } @@ -737,20 +737,20 @@ pub fn openErrors(p: *Pardes, id: usize, content: []u8) !void { pub fn resetBody(p: *Pardes, pane: *Pane) void { pane.file.?.scroll = 0; - pane.cur_row = 0; - pane.cur_col = 0; - pane.cur_pinned = true; + pane.body.cur_row = 0; + pane.body.cur_col = 0; + pane.body.cur_pinned = true; pane.hscroll = 0; pane.wrap_n = 0; - pane.msel = .{}; - pane.vsel = .{}; - pane.nsel = 0; + pane.body.msel = .{}; + pane.body.vsel = .{}; + pane.body.nsel = 0; pane.nsel_snap = 0; - pane.select = false; + pane.body.select = false; pane.sel = @splat(.{}); - pane.sticky_col = -1; - pane.append_at = null; - pane.normal.clear(); + pane.body.sticky_col = -1; + pane.body.append_at = null; + pane.body.normal.clear(); pane.look_at = null; if (p.look_hover_wait) |wait| if (wait.serial == pane.serial) { p.look_hover_wait = null; diff --git a/src/Pipe.zig b/src/Pipe.zig index c01098ff..c2b49f31 100644 --- a/src/Pipe.zig +++ b/src/Pipe.zig @@ -45,7 +45,7 @@ pub const PendingPipe = struct { command: []u8, cwd: []u8, inputs: []selection_pipe.Input, - ranges: [Pane.max_selections]modal.Selection, + ranges: [panes.Text.max_selections]modal.Selection, primary: u8, explicit: bool, how: modal.Normal.PipeBehavior, @@ -84,8 +84,8 @@ pub fn submitPipe(p: *Pardes, id: usize) void { const command = armed[marker.len..]; if (command.len == 0) return; - var ranges: [Pane.max_selections]modal.Selection = undefined; - const got = pane.ranges(f.content, 0, &ranges); + var ranges: [panes.Text.max_selections]modal.Selection = undefined; + const got = pane.body.ranges(f.content, 0, &ranges); // `!`/`A-!` take no stdin and run ONCE — see `PendingPipe.nranges`. const ninputs = if (prompt.how.pipes()) got.n else 1; const inputs = p.gpa.alloc(selection_pipe.Input, ninputs) catch return; @@ -130,7 +130,7 @@ pub fn submitPipe(p: *Pardes, id: usize) void { .inputs = inputs, .ranges = ranges, .primary = @intCast(got.pri), - .explicit = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active, + .explicit = (pane.body.vsel.active and pane.body.vsel.explicit) or pane.body.msel.active, .how = prompt.how, .nranges = @intCast(got.n), }; @@ -255,7 +255,7 @@ pub fn pipeResponse( const final_len = std.math.add(usize, kept, total_output) catch return; const replacement = p.gpa.alloc(u8, final_len) catch return; - var new_ranges: [Pane.max_selections]modal.Selection = undefined; + var new_ranges: [panes.Text.max_selections]modal.Selection = undefined; var read_at: usize = 0; var write_at: usize = 0; for (0..n) |i| { @@ -277,10 +277,10 @@ pub fn pipeResponse( @memcpy(replacement[write_at..], f.content[read_at..]); // One async request is one history transaction, even at 64 cursors. - edit.pushUndo(p, pane); + edit.pushUndo(p, &pane.body); panes.File.setContent(p, f, replacement); - pane.setRanges(f.content, new_ranges[0..n], &.{}, wait.primary, wait.explicit); - pane.select = false; + pane.body.setRanges(f.content, new_ranges[0..n], &.{}, wait.primary, wait.explicit); + pane.body.select = false; pane.ensureCursorVisible(); } @@ -290,9 +290,9 @@ test "selection pipe prompt submits exact request and Escape cancels" { defer p.deinit(); while (p.nextEffect()) |_| {} const pane = try p.setTestFile("one\ntwo\n"); - pane.cur_row = 0; - pane.cur_col = 2; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + pane.body.cur_row = 0; + pane.body.cur_col = 2; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; p.update(.{ .key = .{ .cp = '|' } }); try std.testing.expect(pane.tag_edit and pane.prompt == .pipe); @@ -327,7 +327,7 @@ test "selection pipe replaces all ranges atomically and undo restores them" { .{ .anchor = 0, .head = 2 }, .{ .anchor = 6, .head = 8 }, }; - pane.setRanges(pane.file.?.content, &ranges, &.{}, 0, true); + pane.body.setRanges(pane.file.?.content, &ranges, &.{}, 0, true); p.update(.{ .key = .{ .cp = '|' } }); p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); @@ -345,9 +345,9 @@ test "selection pipe replaces all ranges atomically and undo restores them" { p.update(.{ .pipe_resp = .{ .id = id, .success = true, .outputs = outputs } }); try std.testing.expectEqualSlices(u8, "AA bb \n", pane.file.?.content); try std.testing.expectEqual(@as(usize, 1), pane.file.?.history.undo_len); - try std.testing.expectEqual(@as(u8, 1), pane.nsel); - try std.testing.expectEqual(@as(i32, 1), pane.cur_col); - try std.testing.expectEqual(@as(i32, 6), pane.sels[0].col); + try std.testing.expectEqual(@as(u8, 1), pane.body.nsel); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); + try std.testing.expectEqual(@as(i32, 6), pane.body.sels[0].col); try std.testing.expect(!denied.has_induced_failure); p.update(.{ .key = .{ .cp = 'u' } }); @@ -378,7 +378,7 @@ test "the four shell behaviours put their output where helix puts it" { defer p.deinit(); while (p.nextEffect()) |_| {} const pane = try p.setTestFile("aa bb cc\n"); - pane.setRanges(pane.file.?.content, &.{.{ .anchor = 3, .head = 5 }}, &.{}, 0, true); + pane.body.setRanges(pane.file.?.content, &.{.{ .anchor = 3, .head = 5 }}, &.{}, 0, true); p.update(.{ .key = case.key }); for ("cmd") |c| p.update(.{ .key = .{ .cp = c, .text = &.{c} } }); @@ -399,7 +399,7 @@ test "a command with no stdin runs once and every cursor gets that one answer" { .{ .anchor = 0, .head = 2 }, .{ .anchor = 6, .head = 8 }, }; - pane.setRanges(pane.file.?.content, &ranges, &.{}, 0, true); + pane.body.setRanges(pane.file.?.content, &ranges, &.{}, 0, true); p.update(.{ .key = .{ .cp = '!' } }); // insert-output: no stdin for ("date") |c| p.update(.{ .key = .{ .cp = c, .text = &.{c} } }); @@ -421,8 +421,8 @@ test "selection pipe failure and stale completion never mutate the file" { defer p.deinit(); while (p.nextEffect()) |_| {} const pane = try p.setTestFile("abc\n"); - pane.cur_col = 2; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + pane.body.cur_col = 2; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; p.update(.{ .key = .{ .cp = '|' } }); p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); @@ -448,8 +448,8 @@ test "a failed filter opens an errors buffer carrying the command's own words" { defer p.deinit(); while (p.nextEffect()) |_| {} const pane = try p.setTestFile("abc\n"); - pane.cur_col = 2; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + pane.body.cur_col = 2; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; p.update(.{ .key = .{ .cp = '|' } }); for ("trr") |c| p.update(.{ .key = .{ .cp = c, .text = &.{c} } }); @@ -491,8 +491,8 @@ test "selection pipe rejects a reused pane slot and a superseded request" { defer p.deinit(); while (p.nextEffect()) |_| {} var pane = try p.setTestFile("old\n"); - pane.cur_col = 2; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + pane.body.cur_col = 2; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; p.update(.{ .key = .{ .cp = '|' } }); p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); @@ -503,8 +503,8 @@ test "selection pipe rejects a reused pane slot and a superseded request" { try std.testing.expectEqualSlices(u8, "new\n", pane.file.?.content); try std.testing.expectEqual(@as(usize, 0), pane.file.?.history.undo_len); - pane.cur_col = 2; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + pane.body.cur_col = 2; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; p.update(.{ .key = .{ .cp = '|' } }); p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); p.update(.{ .key = .{ .cp = Key.enter } }); @@ -533,7 +533,7 @@ test "selection pipe binding is file-normal-only" { p.update(.{ .key = .{ .cp = '|' } }); try std.testing.expect(pane.prompt != .pipe); pane.file.?.output = null; - pane.mode = .insert; + pane.body.mode = .insert; p.update(.{ .key = .{ .cp = '|', .text = "|" } }); try std.testing.expect(pane.prompt != .pipe); try std.testing.expectEqualSlices(u8, "|x", pane.file.?.content); diff --git a/src/Terminal.zig b/src/Terminal.zig index cb752613..fbe7bfc0 100644 --- a/src/Terminal.zig +++ b/src/Terminal.zig @@ -200,7 +200,7 @@ pub const Snapshot = struct { ovl: ?EditBuffer, cur_row: i32, cur_col: i32, - vsel: Pane.CharSel, + vsel: panes.Text.CharSel, }; pub const PendingCommand = struct { @@ -677,16 +677,16 @@ pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void { // There are no pty reads at all without an emulator to parse them into. if (comptime !enabled) return; if (pane.terminal == null) return; - const has_positions = pane.ovl != null or pane.cur_pinned or pane.vsel.active or - pane.msel.active or pane.nsel > 0 or pane.append_at != null or pane.look_at != null or - pane.ed_undo_len > 0 or pane.ed_redo_len > 0 or pointerRowCount(pane) > 0; + const has_positions = pane.ovl != null or pane.body.cur_pinned or pane.body.vsel.active or + pane.body.msel.active or pane.body.nsel > 0 or pane.body.append_at != null or pane.look_at != null or + pane.body.ed_undo_len > 0 or pane.body.ed_redo_len > 0 or pointerRowCount(pane) > 0; // Sticky bottom, as every other terminal does it: output drags the // viewport down only when the viewport was already on the last row, so // a reader scrolled back into the scrollback stays where they scrolled. const at_bottom = atBottom(pane); if (has_positions) ingestWithPositions(pane, bytes) else ingest(pane, bytes); p.shell_rows.markStale(pane); - const body_mode = if (pane.tag_edit) pane.tag_mode else pane.mode; + const body_mode = if (pane.tag_edit) pane.tag_mode else pane.body.mode; if (body_mode == .tty and at_bottom) followOutput(pane); } @@ -752,15 +752,15 @@ fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { const key = screens.active_key; const generation = screens.generation(key); const pages = &screens.active.pages; - const Group = struct { overlay: ?*EditBuffer, cursor: *i32, selection: *Pane.CharSel }; + const Group = struct { overlay: ?*EditBuffer, cursor: *i32, selection: *panes.Text.CharSel }; var groups: [history_max * 2 + 1]Group = undefined; groups[0] = .{ .overlay = if (pane.ovl) |*overlay| overlay else null, - .cursor = &pane.cur_row, - .selection = &pane.vsel, + .cursor = &pane.body.cur_row, + .selection = &pane.body.vsel, }; var ngroups: usize = 1; - for ([_][]Snapshot{ pane.ed_undo[0..pane.ed_undo_len], pane.ed_redo[0..pane.ed_redo_len] }) |history| { + for ([_][]Snapshot{ pane.body.ed_undo[0..pane.body.ed_undo_len], pane.body.ed_redo[0..pane.body.ed_redo_len] }) |history| { for (history) |*snapshot| { groups[ngroups] = .{ .overlay = if (snapshot.ovl) |*overlay| overlay else null, @@ -773,7 +773,7 @@ fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { const Span = struct { overlay: *EditBuffer, start: RowPin, end: RowPin }; var spans: [groups.len]Span = undefined; var nspans: usize = 0; - var positions: [groups.len * 2 + Pane.max_selections * 2 + 4]PositionPin = undefined; + var positions: [groups.len * 2 + panes.Text.max_selections * 2 + 4]PositionPin = undefined; var npositions: usize = 0; var failed = false; for (groups[0..ngroups]) |group| { @@ -793,19 +793,19 @@ fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { } } const overlay = groups[0].overlay; - var extra: [Pane.max_selections * 2 + 4]*i32 = undefined; + var extra: [panes.Text.max_selections * 2 + 4]*i32 = undefined; var nextra: usize = 0; - if (pane.msel.active) { - extra[nextra] = &pane.msel.r0; - extra[nextra + 1] = &pane.msel.r1; + if (pane.body.msel.active) { + extra[nextra] = &pane.body.msel.r0; + extra[nextra + 1] = &pane.body.msel.r1; nextra += 2; } - for (pane.sels[0..pane.nsel]) |*selection| { + for (pane.body.sels[0..pane.body.nsel]) |*selection| { extra[nextra] = &selection.row; extra[nextra + 1] = &selection.arow; nextra += 2; } - if (pane.append_at) |*at| { + if (pane.body.append_at) |*at| { extra[nextra] = &at.row; nextra += 1; } @@ -883,7 +883,7 @@ test "raw terminal output needs no position tracking allocations" { const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); const pane = p.panes[0].?; - pane.mode = .tty; + pane.body.mode = .tty; feedOutput(p, pane, "warm"); const allocations = failing.alloc_index; failing.fail_index = allocations; @@ -1045,13 +1045,13 @@ pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { pub fn enterTty(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; const selected = pane.rawPointerText(pane.sel[@intFromEnum(config.select_button)]) != null; - if (comptime enabled) if (!selected and pane.terminal != null and pane.cur_pinned and pane.terminal.?.vt.cursorIsAtPrompt()) handoff: { + if (comptime enabled) if (!selected and pane.terminal != null and pane.body.cur_pinned and pane.terminal.?.vt.cursorIsAtPrompt()) handoff: { const screen = pane.terminal.?.vt.screens.active; const goff: i32 = @intCast(screen.pages.scrollbar().offset); - const vp_row = pane.gridRow(pane.cur_row) - goff; + const vp_row = pane.gridRow(pane.body.cur_row) - goff; if (vp_row < 0) break :handoff; - var grid_col: i32 = @max(0, pane.cur_col); + var grid_col: i32 = @max(0, pane.body.cur_col); if (screen.pages.pin(.{ .viewport = .{ .x = 0, .y = @intCast(vp_row) } })) |row_pin| { if (row_pin.rowAndCell().row.semantic_prompt != .none) switch (promptCut(row_pin)) { .cut => |cols| grid_col += @intCast(cols), @@ -1070,18 +1070,18 @@ pub fn enterTty(p: *Pardes, id: usize) void { for (0..moves.right) |_| p.emitWrite(id, "\x1b[C"); }; - pane.mode = .tty; + pane.body.mode = .tty; followOutput(pane); // entering raw mode is a request for the live shell - pane.msel.active = false; - pane.vsel.active = false; - pane.nsel = 0; + pane.body.msel.active = false; + pane.body.vsel.active = false; + pane.body.nsel = 0; // The raw renderer follows the live cursor. A captured mouse selection // keeps its modal endpoint for the next return to editor mode. - pane.cur_pinned = selected; - pane.select = false; - pane.append_at = null; - pane.sticky_col = -1; - pane.normal.clear(); + pane.body.cur_pinned = selected; + pane.body.select = false; + pane.body.append_at = null; + pane.body.sticky_col = -1; + pane.body.normal.clear(); } // Returned slices remain valid until the next cache rebuild or reset. @@ -1397,7 +1397,7 @@ pub fn dumpPane( var skip: i32 = 0; while (lines.next()) |raw| : (row += 1) { // Hidden overlay rows still consume prompt pins to keep them aligned. - const prompt = if (pane.mode != .tty) prompts.next() else null; + const prompt = if (pane.body.mode != .tty) prompts.next() else null; if (skip > 0) { skip -= 1; continue; @@ -1406,7 +1406,7 @@ pub fn dumpPane( stream[len] = '\n'; len += 1; } - if (pane.mode != .tty) if (pane.ovl) |overlay| if (row == overlay.row) { + if (pane.body.mode != .tty) if (pane.ovl) |overlay| if (row == overlay.row) { @memcpy(stream[len..][0..overlay.text.len], overlay.text); len += overlay.text.len; skip = overlay.rows - 1; @@ -1493,7 +1493,7 @@ pub fn bodyText(arena: std.mem.Allocator, pane: *Pane) ![]const u8 { var lines = std.mem.splitScalar(u8, raw, '\n'); var n: usize = 0; while (lines.next()) |ln| { - vp[n] = if (pane.mode != .tty) + vp[n] = if (pane.body.mode != .tty) if (prompts.next()) |pin| if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, ln) else ln else @@ -1535,7 +1535,7 @@ const BodyWalk = struct { return .{ .pane = pane, .goff = goff, - .g = if (pane.mode == .tty) goff else pane.gridRow(off), + .g = if (pane.body.mode == .tty) goff else pane.gridRow(off), .skip = if (pane.ovl) |o| @intCast(@max(0, off - pane.surfRow(o.row))) else 0, }; } @@ -1562,7 +1562,7 @@ const BodyWalk = struct { w.lines = null; continue; } - if (w.pane.mode != .tty) if (w.pane.ovl) |o| if (w.g == o.row) { + if (w.pane.body.mode != .tty) if (w.pane.ovl) |o| if (w.g == o.row) { w.lines = std.mem.splitScalar(u8, o.text, '\n'); w.covered = o.rows; w.line_idx = 0; @@ -1759,7 +1759,7 @@ pub fn recolorAnsi(p: *Pardes, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, bo const vi = anchor.row; if (vi < 0 or vi >= vp_rows) continue; const row_pin = pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; - const cut: u16 = if (pane.mode == .tty) 0 else cut: { + const cut: u16 = if (pane.body.mode == .tty) 0 else cut: { if (row_pin.rowAndCell().row.semantic_prompt == .none) break :cut 0; break :cut switch (promptCut(row_pin)) { .keep => 0, @@ -2388,13 +2388,13 @@ test "tty ansi colors follow the prompt hug into normal mode" { const blue: pardes.Color = .{ .rgb = p.theme().palette.?[4] }; // tty mode projects the emulator's ansi colours cell for cell. - pane.mode = .tty; + pane.body.mode = .tty; p.shell_rows.stale = true; const tty = try p.render(frame.allocator()); try testing.expectEqual(red, tty.at(tx + 2, body_y).style.fg); try testing.expectEqual(blue, tty.at(tx + 3, body_y).style.fg); - pane.mode = .normal; + pane.body.mode = .normal; p.shell_rows.stale = true; _ = frame.reset(.retain_capacity); const norm = try p.render(frame.allocator()); @@ -2411,7 +2411,7 @@ test "a prompt row hidden end to end paints nothing at all" { while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tty_filter = false; - pane.mode = .normal; + pane.body.mode = .normal; p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32maaaaaaaaa\x1b]133;B\x1b\\\x1b[41;36m\u{754C}\x1b[0m\r\n" } }); var frame = std.heap.ArenaAllocator.init(testing.allocator); @@ -2467,7 +2467,7 @@ pub fn padOutputBelowEdits(p: *Pardes, id: usize) void { pub fn snap(p: *Pardes, pane: *Pane) ?Snapshot { var ovl: ?EditBuffer = null; if (pane.ovl) |o| ovl = .{ .row = o.row, .rows = o.rows, .text = p.gpa.dupe(u8, o.text) catch return null }; - return .{ .ovl = ovl, .cur_row = pane.cur_row, .cur_col = pane.cur_col, .vsel = pane.vsel }; + return .{ .ovl = ovl, .cur_row = pane.body.cur_row, .cur_col = pane.body.cur_col, .vsel = pane.body.vsel }; } /// undo/redo restores the selection recorded with the snapshot (helix @@ -2475,11 +2475,11 @@ pub fn snap(p: *Pardes, pane: *Pane) ?Snapshot { pub fn restoreSnap(p: *Pardes, pane: *Pane, s: Snapshot) void { if (pane.ovl) |o| p.gpa.free(o.text); pane.ovl = s.ovl; - pane.cur_row = s.cur_row; - pane.cur_col = s.cur_col; - pane.cur_pinned = true; - pane.vsel = s.vsel; - pane.msel.active = false; + pane.body.cur_row = s.cur_row; + pane.body.cur_col = s.cur_col; + pane.body.cur_pinned = true; + pane.body.vsel = s.vsel; + pane.body.msel.active = false; pane.ensureCursorVisible(); } @@ -2495,32 +2495,32 @@ fn pushHistory(gpa: std.mem.Allocator, slots: []Snapshot, len: *usize, value: Sn pub fn pushUndo(p: *Pardes, pane: *Pane) void { const current = pane.ovl orelse EditBuffer{ .rows = 0 }; - if (pane.ed_undo_len > 0) { - const top = pane.ed_undo[pane.ed_undo_len - 1]; + if (pane.body.ed_undo_len > 0) { + const top = pane.body.ed_undo[pane.body.ed_undo_len - 1]; const same = if (top.ovl) |overlay| pane.ovl != null and overlay.row == current.row and overlay.rows == current.rows and std.mem.eql(u8, overlay.text, current.text) else pane.ovl == null; if (same) return; } const value = snap(p, pane) orelse return; - pushHistory(p.gpa, &pane.ed_undo, &pane.ed_undo_len, value); - for (pane.ed_redo[0..pane.ed_redo_len]) |item| if (item.ovl) |overlay| p.gpa.free(overlay.text); - pane.ed_redo_len = 0; + pushHistory(p.gpa, &pane.body.ed_undo, &pane.body.ed_undo_len, value); + for (pane.body.ed_redo[0..pane.body.ed_redo_len]) |item| if (item.ovl) |overlay| p.gpa.free(overlay.text); + pane.body.ed_redo_len = 0; } pub fn undo(p: *Pardes, pane: *Pane) void { - if (pane.ed_undo_len == 0) return; + if (pane.body.ed_undo_len == 0) return; const current = snap(p, pane) orelse return; - pushHistory(p.gpa, &pane.ed_redo, &pane.ed_redo_len, current); - pane.ed_undo_len -= 1; - restoreSnap(p, pane, pane.ed_undo[pane.ed_undo_len]); + pushHistory(p.gpa, &pane.body.ed_redo, &pane.body.ed_redo_len, current); + pane.body.ed_undo_len -= 1; + restoreSnap(p, pane, pane.body.ed_undo[pane.body.ed_undo_len]); } pub fn redo(p: *Pardes, pane: *Pane) void { - if (pane.ed_redo_len == 0) return; + if (pane.body.ed_redo_len == 0) return; const current = snap(p, pane) orelse return; - pushHistory(p.gpa, &pane.ed_undo, &pane.ed_undo_len, current); - pane.ed_redo_len -= 1; - restoreSnap(p, pane, pane.ed_redo[pane.ed_redo_len]); + pushHistory(p.gpa, &pane.body.ed_undo, &pane.body.ed_undo_len, current); + pane.body.ed_redo_len -= 1; + restoreSnap(p, pane, pane.body.ed_redo[pane.body.ed_redo_len]); } pub fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: [:0]const u8) void { diff --git a/src/Text.zig b/src/Text.zig new file mode 100644 index 00000000..ad5aa186 --- /dev/null +++ b/src/Text.zig @@ -0,0 +1,606 @@ +//! One editable text, acme's Text (editors/acme/dat.h:171-190, text.c): the +//! cursor, the selections and the modal state that edit it, and the undo of +//! an edit buffer. A pane's body is one. Where its characters come from -- a +//! file's content, a terminal's edit overlay, a PDF's text -- is the window's +//! business (edit.zig's editText and flatSurface), the way acme's Text reads +//! its File; everything here works on the flat text it is handed. +const std = @import("std"); +const panes = @import("panes.zig"); +const modal = @import("modal.zig"); +const config = @import("config.zig"); +const Pane = panes.Pane; +const File = panes.File; +const Terminal = panes.Terminal; +const Text = @This(); + +pub const Mode = enum { normal, insert, tty }; + +/// A modal line selection (helix `x`): whole rows [r0, r1], absolute. +pub const LineSel = struct { + active: bool = false, + r0: i32 = 0, + r1: i32 = 0, +}; + +pub const CharSel = struct { + active: bool = false, + row: i32 = 0, + col: i32 = 0, + explicit: bool = false, +}; + +pub const max_selections = 64; + +pub const SelRange = struct { + row: i32, + col: i32, + arow: i32, + acol: i32, + /// this range's own j/k goal column (helix Range::old_visual_position); + /// the PRIMARY's copy is Text.sticky_col + sticky: i32 = -1, +}; + +mode: Mode = .normal, +cur_pinned: bool = false, +cur_row: i32 = 0, +cur_col: i32 = 0, +msel: LineSel = .{}, +vsel: CharSel = .{}, +sels: [max_selections - 1]SelRange = undefined, +nsel: u8 = 0, +select: bool = false, +/// sticky goal column for j/k runs (helix old_visual_position): any +/// non-vertical range write resets it to -1. +sticky_col: i32 = -1, +append_at: ?struct { row: i32, col: i32 } = null, +normal: modal.Normal.State = .{}, +/// last f/F/t/T motion, for Alt-. repeat +find_op: u8 = 0, +find_ch: u21 = 0, +ed_undo: [Terminal.history_max]Terminal.Snapshot = undefined, +ed_undo_len: usize = 0, +ed_redo: [Terminal.history_max]Terminal.Snapshot = undefined, +ed_redo_len: usize = 0, + +/// The window this text belongs to (acme's t->w). +pub fn pane(t: *Text) *Pane { + return @alignCast(@fieldParentPtr("body", t)); +} + +pub fn toModalCursor(t: *Text) modal.Cursor { + return .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) }; +} + +pub fn fromModalCursor(t: *Text, c: modal.Cursor) void { + t.cur_row = @as(i32, @intCast(c.row)); + t.cur_col = @intCast(c.col); + t.cur_pinned = true; +} + +pub fn insertVerticalCursor(lines: []const []const u8, c: modal.Cursor, down: bool) modal.Cursor { + if (lines.len == 0) return c; + const row = if (down) @min(c.row + 1, lines.len - 1) else c.row -| 1; + const target = lines[row]; + if (target.len == 0) return .{ .row = row, .col = 0 }; + const source = if (c.row < lines.len) lines[c.row] else ""; + const goal = File.rawDisplayCol(source, c.col); + const mapped = File.rawAtDisplay(target, goal); + const last = modal.prevGrapheme(target, target.len); + return .{ .row = row, .col = modal.graphemeStart(target, @min(mapped, last)) }; +} + +pub fn primaryRange(t: *Text, text: []const u8, row0: i32) modal.Selection { + const c = File.textOffset(t, text, .{ .row = @intCast(@max(0, t.cur_row - row0)), .col = @intCast(@max(0, t.cur_col)) }); + if (t.msel.active) { + // legacy line selection (file-search results highlight): linewise + const r0: usize = @intCast(@max(0, @min(t.msel.r0, t.msel.r1) - row0)); + const r1: usize = @intCast(@max(0, @max(t.msel.r0, t.msel.r1) - row0)); + const s = modal.lineStartOffset(text, r0); + const e = if (r1 + 1 >= modal.cursorLineCount(text)) text.len else modal.lineStartOffset(text, r1 + 1); + return .{ .anchor = s, .head = @max(e, modal.nextGrapheme(text, c)) }; + } + if (t.vsel.active) return cellRange(text, t.vsel.row - row0, t.vsel.col, t.cur_row - row0, t.cur_col); + return .{ .anchor = c, .head = modal.nextGrapheme(text, c) }; +} + +pub fn cellRange(text: []const u8, arow: i32, acol: i32, hrow: i32, hcol: i32) modal.Selection { + const a = modal.offsetAt(text, .{ .row = @intCast(@max(0, arow)), .col = @intCast(@max(0, acol)) }); + const c = modal.offsetAt(text, .{ .row = @intCast(@max(0, hrow)), .col = @intCast(@max(0, hcol)) }); + return cellOffRange(text, a, c); +} + +/// the same, from the two cells' gap offsets +pub fn cellOffRange(text: []const u8, a: usize, c: usize) modal.Selection { + if (a <= c) return .{ .anchor = a, .head = modal.nextGrapheme(text, c) }; + return .{ .anchor = modal.nextGrapheme(text, a), .head = c }; +} + +pub fn rangeCells(text: []const u8, r: modal.Selection) struct { cur: usize, anc: usize } { + if (r.head > r.anchor) return .{ .cur = modal.prevGrapheme(text, r.head), .anc = r.anchor }; + if (r.head < r.anchor) return .{ .cur = r.head, .anc = modal.prevGrapheme(text, r.anchor) }; + return .{ .cur = r.head, .anc = r.head }; +} + +pub fn setRange(t: *Text, text: []const u8, row0: i32, r0: modal.Selection, explicit: bool) void { + var r = r0; + if (r.anchor == r.head) r.head = modal.nextGrapheme(text, r.head); // min_width_1 + const off = rangeCells(text, r); + const cc = File.textPosition(t, text, off.cur); + // a bare block cursor has both cells on the same offset — the common + // case by far — and this conversion is not free even indexed + const ac = if (off.anc == off.cur) cc else File.textPosition(t, text, off.anc); + t.cur_row = @as(i32, @intCast(cc.row)) + row0; + t.cur_col = @intCast(cc.col); + t.vsel = .{ + .active = off.anc != off.cur or t.select, + .row = @as(i32, @intCast(ac.row)) + row0, + .col = @intCast(ac.col), + .explicit = explicit or t.select, + }; + t.msel.active = false; + t.nsel = 0; // writing ONE range means the selection IS that range + t.cur_pinned = true; + t.sticky_col = -1; + t.normal.clear(); + t.pane().ensureCursorVisible(); +} + +pub fn ranges(t: *Text, text: []const u8, row0: i32, out: *[max_selections]modal.Selection) struct { n: usize, pri: usize } { + const pr = primaryRange(t, text, row0); + var n: usize = 0; + var pri: usize = 0; + var placed = false; + for (t.sels[0..t.nsel]) |s| { + const r = cellRange(text, s.arow - row0, s.acol, s.row - row0, s.col); + if (!placed and @min(pr.anchor, pr.head) <= @min(r.anchor, r.head)) { + pri = n; + out[n] = pr; + n += 1; + placed = true; + } + out[n] = r; + n += 1; + } + if (!placed) { + pri = n; + out[n] = pr; + n += 1; + } + return .{ .n = n, .pri = pri }; +} + +pub fn setRanges(t: *Text, text: []const u8, in: []const modal.Selection, sticky: []const i32, pri0: usize, explicit: bool) void { + if (in.len == 0) return; // helix asserts non-empty; here it just means "no change" + var r: [max_selections]modal.Selection = undefined; + var st: [max_selections]i32 = undefined; + var n: usize = @min(in.len, max_selections); + var pri: usize = @min(pri0, n - 1); + for (in[0..n], 0..) |x, i| { + r[i] = x; + if (r[i].anchor == r[i].head) r[i].head = modal.nextGrapheme(text, r[i].head); + st[i] = if (i < sticky.len) sticky[i] else -1; + } + // insertion sort by start — n is tiny and usually already ordered + var i: usize = 1; + while (i < n) : (i += 1) { + var j = i; + while (j > 0 and @min(r[j].anchor, r[j].head) < @min(r[j - 1].anchor, r[j - 1].head)) : (j -= 1) { + std.mem.swap(modal.Selection, &r[j], &r[j - 1]); + std.mem.swap(i32, &st[j], &st[j - 1]); + if (pri == j) pri = j - 1 else if (pri == j - 1) pri = j; + } + } + var k: usize = 0; + i = 1; + while (i < n) : (i += 1) { + const a = r[k]; + const b = r[i]; + const af = @min(a.anchor, a.head); + const at = @max(a.anchor, a.head); + const bf = @min(b.anchor, b.head); + const bt = @max(b.anchor, b.head); + if (af == bf or (at > bf and bt > af)) { + r[k] = if (a.anchor > a.head and b.anchor > b.head) + .{ .anchor = @max(a.anchor, b.anchor), .head = @min(a.head, b.head) } + else + .{ .anchor = @min(af, bf), .head = @max(at, bt) }; + if (pri == i) pri = k; + if (st[k] < 0) st[k] = st[i]; + continue; + } + k += 1; + r[k] = b; + st[k] = st[i]; + if (pri == i) pri = k; + } + n = k + 1; + setRange(t, text, 0, r[pri], explicit); + t.sticky_col = st[pri]; + var w: usize = 0; + for (r[0..n], 0..) |x, idx| { + if (idx == pri) continue; + const c = rangeCells(text, x); + const cc = modal.positionAt(text, c.cur); + const ac = modal.positionAt(text, c.anc); + t.sels[w] = .{ + .row = @as(i32, @intCast(cc.row)), + .col = @intCast(cc.col), + .arow = @as(i32, @intCast(ac.row)), + .acol = @intCast(ac.col), + .sticky = st[idx], + }; + w += 1; + } + t.nsel = @intCast(w); +} + +pub fn multiSelAction(t: *Text, text: []const u8, kind: modal.Normal.Multi, cnt: usize) void { + var rs: [max_selections]modal.Selection = undefined; + const got = ranges(t, text, 0, &rs); + const n = got.n; + const expl = (t.vsel.active and t.vsel.explicit) or t.msel.active; + if (kind == .remove_primary) { + if (n < 2) return; // helix: "no selections remaining" + var out: [max_selections]modal.Selection = undefined; + var m: usize = 0; + for (rs[0..n], 0..) |r, i| { + if (i == got.pri) continue; + out[m] = r; + m += 1; + } + // helix Selection::remove: the NEXT range takes over, or the + // previous one when the primary was last + return setRanges(t, text, out[0..m], &.{}, @min(got.pri, m - 1), expl); + } + if (kind == .rotate_forward or kind == .rotate_backward) { + const step = cnt % n; + const pri = if (kind == .rotate_forward) (got.pri + step) % n else (got.pri + (n - step)) % n; + return setRanges(t, text, rs[0..n], &.{}, pri, expl); + } + if (kind == .merge) { + // helix merge_selections: first.merge(last) — the ranges are + // sorted, so that is simply the whole span + const lo = @min(rs[0].anchor, rs[0].head); + const hi = @max(rs[n - 1].anchor, rs[n - 1].head); + const rev = rs[0].anchor > rs[0].head and rs[n - 1].anchor > rs[n - 1].head; + const one: modal.Selection = if (rev) .{ .anchor = hi, .head = lo } else .{ .anchor = lo, .head = hi }; + return setRanges(t, text, &.{one}, &.{}, 0, expl); + } + if (kind == .merge_consecutive) { + var out: [max_selections]modal.Selection = undefined; + var m: usize = 0; + var pri: usize = 0; + for (rs[0..n], 0..) |r, i| { + if (m > 0 and @min(r.anchor, r.head) == @max(out[m - 1].anchor, out[m - 1].head)) { + const lo = @min(@min(out[m - 1].anchor, out[m - 1].head), @min(r.anchor, r.head)); + const hi = @max(@max(out[m - 1].anchor, out[m - 1].head), @max(r.anchor, r.head)); + out[m - 1] = .{ .anchor = lo, .head = hi }; + if (i == got.pri) pri = m - 1; + continue; + } + if (i == got.pri) pri = m; + out[m] = r; + m += 1; + } + return setRanges(t, text, out[0..m], &.{}, pri, expl); + } + if (kind == .split_newline) { + // helix selection::split_on_newline — one range per line the + // selection covers, the newlines themselves left out + var out: [max_selections]modal.Selection = undefined; + var m: usize = 0; + for (rs[0..n]) |r| { + const from = @min(r.anchor, r.head); + const to = @max(r.anchor, r.head); + if (from == to) { + if (m < max_selections) { + out[m] = r; + m += 1; + } + continue; + } + var start = from; + while (start < to and m < max_selections) { + const eol = modal.lineEndOffset(text, modal.lineAtOffset(text, start)); + if (eol >= to) { + out[m] = .{ .anchor = start, .head = to }; + m += 1; + break; + } + out[m] = .{ .anchor = start, .head = eol }; + m += 1; + start = eol + 1; + } + } + if (m == 0) return; + return setRanges(t, text, out[0..m], &.{}, 0, true); // helix keeps primary 0 + } + if (kind == .trim) { + // helix trim_selections: whitespace off both ends; ranges that are + // empty or all whitespace are dropped entirely + var out: [max_selections]modal.Selection = undefined; + var m: usize = 0; + for (rs[0..n]) |r| { + var from = @min(r.anchor, r.head); + var to = @max(r.anchor, r.head); + while (from < to and std.ascii.isWhitespace(text[from])) from += 1; + while (to > from and std.ascii.isWhitespace(text[to - 1])) to -= 1; + if (from >= to) continue; + out[m] = if (r.anchor > r.head) .{ .anchor = to, .head = from } else .{ .anchor = from, .head = to }; + m += 1; + } + if (m == 0) { // helix: collapse_selection + keep_primary_selection + const c = modal.selectionCursor(text, rs[got.pri]); + return setRange(t, text, 0, .{ .anchor = c, .head = c }, false); + } + // helix: the first survivor that OVERLAPS the old primary, else the last + const pf = @min(rs[got.pri].anchor, rs[got.pri].head); + const pt = @max(rs[got.pri].anchor, rs[got.pri].head); + var pri = m - 1; + for (out[0..m], 0..) |r, i| { + const f = @min(r.anchor, r.head); + const to = @max(r.anchor, r.head); + if (f == pf or (to > pf and pt > f)) { + pri = i; + break; + } + } + return setRanges(t, text, out[0..m], &.{}, pri, expl); + } + const below = kind == .copy_below; + var out: [max_selections]modal.Selection = undefined; + var m: usize = 0; + var pri: usize = 0; + const nlines = modal.cursorLineCount(text); + for (rs[0..n], 0..) |r, ri| { + const is_pri = ri == got.pri; + // head-exclusive: back the leading end off onto its own cell + const hp = modal.positionAt(text, if (r.anchor < r.head) modal.prevGrapheme(text, r.head) else r.head); + const ap = modal.positionAt(text, if (r.anchor < r.head) r.anchor else modal.prevGrapheme(text, r.anchor)); + const height = @max(hp.row, ap.row) - @min(hp.row, ap.row) + 1; + if (m >= max_selections) break; + if (is_pri) pri = m; + out[m] = r; + m += 1; + var made: usize = 0; + var k: usize = 0; + while (made < cnt and m < max_selections) : (k += 1) { + const d = (k + 1) * height; + const arow = if (below) ap.row + d else ap.row -| d; + const hrow = if (below) hp.row + d else hp.row -| d; + if (arow >= nlines or hrow >= nlines) break; + const a2 = modal.offsetAt(text, .{ .row = arow, .col = ap.col }); + const h2 = modal.offsetAt(text, .{ .row = hrow, .col = hp.col }); + // a line too short to reach the column is skipped, not clamped + if (modal.positionAt(text, a2).col == ap.col and modal.positionAt(text, h2).col == hp.col) { + if (is_pri) pri = m; + out[m] = modal.moveSelectionCursor(text, .{ .anchor = a2, .head = a2 }, h2, true); + m += 1; + made += 1; + } + if (arow == 0 and hrow == 0) break; + } + } + setRanges(t, text, out[0..m], &.{}, pri, expl); +} + +/// a range's start CELL (document order key) — the smaller of its two ends +pub fn selStart(s: SelRange) struct { row: i32, col: i32 } { + if (s.arow < s.row or (s.arow == s.row and s.acol < s.col)) return .{ .row = s.arow, .col = s.acol }; + return .{ .row = s.row, .col = s.col }; +} + +pub fn maxLine(text: []const u8) usize { + const nl = modal.cursorLineCount(text); + return if (text.len == 0 or text[text.len - 1] == '\n') nl -| 2 else nl - 1; +} + +/// point-target motion: collapse there (extend in select mode) +pub fn pointMove(t: *Text, text: []const u8, range: modal.Selection, target: usize) void { + setRange(t, text, 0, modal.moveSelectionCursor(text, range, target, t.select), false); +} + +/// word motions select their traversed span (extend mode: head only) +pub fn wordMove(t: *Text, text: []const u8, range: modal.Selection, cnt: usize, target: modal.WordTarget) void { + const wr = modal.moveWord(text, range, cnt, target); + const res = if (t.select) modal.moveSelectionCursor(text, range, modal.selectionCursor(text, wr), true) else wr; + setRange(t, text, 0, res, false); +} + +/// f/t/F/T: anchor at the old cursor cell, head on the hit (not found: no move) +pub fn findMove(t: *Text, text: []const u8, range: modal.Selection, ch: u21, fwd: bool, till: bool, cnt: usize) void { + const cur = modal.selectionCursor(text, range); + const target = modal.findTarget(text, cur, ch, fwd, till, cnt) orelse return; + const res = if (t.select) + modal.moveSelectionCursor(text, range, target, true) + else + modal.moveSelectionCursor(text, .{ .anchor = cur, .head = cur }, target, true); + setRange(t, text, 0, res, false); +} + +/// j/k and friends: sticky goal column, clamped onto short lines' newline +pub fn verticalMove(t: *Text, text: []const u8, range: modal.Selection, down: bool, cnt: usize) void { + const cur = modal.selectionCursor(text, range); + const pos = File.textPosition(t, text, cur); + const goal: usize = if (t.sticky_col >= 0) + @intCast(t.sticky_col) + else + File.rawDisplayCol(File.textLine(t, text, pos.row), pos.col); + const last_row = File.textLineCount(t, text) - 1; + const nline = if (down) @min(pos.row + @max(1, cnt), last_row) else pos.row -| @max(1, cnt); + const target_col = File.rawAtDisplay(File.textLine(t, text, nline), goal); + const target = File.textOffset(t, text, .{ .row = nline, .col = target_col }); + // extend mode never walks onto the empty trailing line (helix) + if (t.select and target == text.len and text.len > 0 and text[text.len - 1] == '\n') return; + setRange(t, text, 0, modal.moveSelectionCursor(text, range, target, t.select), false); + t.sticky_col = @intCast(goal); +} + +pub fn visualMove( + t: *Text, + text: []const u8, + range: modal.Selection, + down: bool, + cnt: usize, + width: usize, +) void { + const cur = modal.selectionCursor(text, range); + const pos = File.textPosition(t, text, cur); + const last_row = File.textLineCount(t, text) - 1; + var row = pos.row; + var line = modal.lineSlice(text, row); + var vrow = File.visualRow(line, pos.col, width); + const goal: usize = if (t.sticky_col >= 0) + @intCast(t.sticky_col) + else + File.rawDisplayCol(line[vrow.start..vrow.end], pos.col -| vrow.start); + var steps = @max(1, cnt); + while (steps > 0) : (steps -= 1) { + if (down) { + if (vrow.end < line.len) { + vrow = File.visualRow(line, vrow.end, width); + continue; + } + if (row == last_row) break; + row += 1; + line = modal.lineSlice(text, row); + vrow = File.visualRow(line, 0, width); + } else { + if (vrow.start > 0) { + vrow = File.visualRow(line, vrow.start - 1, width); + continue; + } + if (row == 0) break; + row -= 1; + line = modal.lineSlice(text, row); + vrow = File.visualRow(line, line.len, width); + } + } + // The newline slot is a real cursor position, but the first byte of the + // NEXT visual row is not: landing there would read as two rows moved. + var target_col = vrow.start + File.rawAtDisplay(line[vrow.start..vrow.end], goal); + if (vrow.end < line.len and target_col >= vrow.end) + target_col = modal.graphemeStart(line, vrow.end - 1); + const target = File.textOffset(t, text, .{ .row = row, .col = target_col }); + // extend mode never walks onto the empty trailing line (helix) + if (t.select and target == text.len and text.len > 0 and text[text.len - 1] == '\n') return; + setRange(t, text, 0, modal.moveSelectionCursor(text, range, target, t.select), false); + t.sticky_col = @intCast(goal); +} + +/// Ctrl-d/u: scroll half a page AND move the cursor by the same rows +pub fn halfPageMove(t: *Text, text: []const u8, range: modal.Selection, down: bool) void { + const half: i32 = @max(1, @divTrunc(@as(i32, t.pane().rows), 2)); + t.pane().scrollBy(if (down) half else -half); + verticalMove(t, text, range, down, @intCast(half)); +} + +/// helix `scroll` without cursor sync (Ctrl-f/b, PgUp/PgDn, zj/zk): shift +/// the view, then snap a fallen-out cursor to the near scrolloff edge, col 0 +pub fn scrollViewMove(t: *Text, text: []const u8, range: modal.Selection, delta: i32) void { + const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, t.pane().rows) - 1, 2)); + t.pane().scrollBy(delta); + const top = t.pane().scroll(); + const last_row: i32 = @intCast(File.textLineCount(t, text) - 1); + const cur = modal.selectionCursor(text, range); + if (delta > 0) { + const snap: i32 = @max(0, @min(top + margin, last_row)); + const head = File.textLineStart(t, text, @intCast(snap)); + if (head <= cur) return; + const anchor = if (t.select) range.anchor else head; + setRange(t, text, 0, .{ .anchor = anchor, .head = head }, false); + } else { + const snap: i32 = @max(0, @min(top + @as(i32, t.pane().rows) - margin - 1, last_row)); + const head = File.textLineStart(t, text, @intCast(snap)); + if (head >= cur) return; + const anchor = if (t.select) range.anchor else head; + setRange(t, text, 0, .{ .anchor = anchor, .head = head }, false); + } +} + +/// gt/gc/gb: view-relative rows, col 0, scrolloff clamped (helix goto_window) +pub fn gotoWindow(t: *Text, text: []const u8, range: modal.Selection, which: enum { top, center, bottom }, cnt: usize) void { + const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, t.pane().rows) - 1, 2)); + const top = t.pane().scroll(); + const last_row: i32 = @intCast(File.textLineCount(t, text) - 1); + const last_vis: i32 = @min(@as(i32, t.pane().rows) - 1, last_row - top); + const n: i32 = @intCast(cnt - 1); + var vline: i32 = switch (which) { + .top => top + margin + n, + .center => top + @divTrunc(last_vis, 2), + .bottom => top + last_vis - (margin + n), + }; + vline = @max(vline, top + margin); + vline = @min(vline, top + last_vis - margin); + const row: i32 = std.math.clamp(vline, 0, last_row); + pointMove(t, text, range, File.textLineStart(t, text, @intCast(row))); +} + +/// helix Range::line_range — the inclusive line span a range covers +pub fn rangeLineSpan(text: []const u8, r: modal.Selection) struct { start: usize, end: usize } { + const from = @min(r.anchor, r.head); + const to = @max(r.anchor, r.head); + const to_adj = if (from == to) to else @max(modal.prevGrapheme(text, to), from); + return .{ .start = modal.lineAtOffset(text, from), .end = modal.lineAtOffset(text, to_adj) }; +} + +fn lineStartOrEof(text: []const u8, line: usize) usize { + if (line >= modal.cursorLineCount(text)) return text.len; + return modal.lineStartOffset(text, line); +} + +/// helix `x` extend_line_below: full lines incl. the newline, cursor ON +/// the last one's '\n'; an already-line-bounded selection grows downward +pub fn lineSelect(t: *Text, text: []const u8, range: modal.Selection, cnt: usize) void { + const span = rangeLineSpan(text, range); + const start = modal.lineStartOffset(text, span.start); + const end = lineStartOrEof(text, span.end + 1); + const full = @min(range.anchor, range.head) == start and @max(range.anchor, range.head) == end; + const head = lineStartOrEof(text, span.end + cnt + @intFromBool(full)); + setRange(t, text, 0, .{ .anchor = start, .head = head }, true); +} + +/// helix `X` extend_to_line_bounds (direction kept) +pub fn lineBoundsSelect(t: *Text, text: []const u8, range: modal.Selection) void { + const span = rangeLineSpan(text, range); + const start = modal.lineStartOffset(text, span.start); + const end = lineStartOrEof(text, span.end + 1); + const r: modal.Selection = if (range.head < range.anchor) + .{ .anchor = end, .head = start } + else + .{ .anchor = start, .head = end }; + setRange(t, text, 0, r, true); +} + +/// helix `Alt-x` shrink_to_line_bounds (single-line selections untouched) +pub fn shrinkSelToLineBounds(t: *Text, text: []const u8, range: modal.Selection) void { + const span = rangeLineSpan(text, range); + if (span.start == span.end) return; + const from = @min(range.anchor, range.head); + const to = @max(range.anchor, range.head); + var start = modal.lineStartOffset(text, span.start); + var end = lineStartOrEof(text, span.end + 1); + if (start != from) start = lineStartOrEof(text, span.start + 1); + if (end != to) end = modal.lineStartOffset(text, span.end); + const expl = (t.vsel.active and t.vsel.explicit) or t.msel.active; + const r: modal.Selection = if (range.head < range.anchor) + .{ .anchor = end, .head = start } + else + .{ .anchor = start, .head = end }; + setRange(t, text, 0, r, expl); +} + +/// pull the cursor back inside `text` after a rewrite; `row0` is the +/// absolute surface row of its first line (0 for a file) +pub fn clampCursor(t: *Text, text: []const u8, row0: i32) void { + const n = modal.lineCount(text); + const row: usize = @min(@as(usize, @intCast(@max(0, t.cur_row - row0))), if (n == 0) 0 else n - 1); + const llen = modal.lineSlice(text, row).len; + t.cur_row = @as(i32, @intCast(row)) + row0; + t.cur_col = @intCast(@min(@as(usize, @intCast(@max(0, t.cur_col))), llen)); + t.cur_pinned = true; + t.vsel.active = false; + t.msel.active = false; + t.pane().ensureCursorVisible(); +} diff --git a/src/body_layer.zig b/src/body_layer.zig index 6bac7018..71529326 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -132,7 +132,7 @@ test "compact context borders separate source gaps and preserve multiline header fn paintTerminalSelection(p: *Pardes, pane: *Pane, r: Rect, rows: []const Pane.PointerRow, bg: [3]u8, fg: ?[3]u8) void { const body = bodyText(p, p.scratch.allocator(), pane) catch return; - const raw = pane.mode == .tty; + const raw = pane.body.mode == .tty; const tx = r.x + config.GUTTER; const width = r.w -| config.GUTTER; const body_y = p.bodyTop(r); @@ -366,14 +366,14 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, sl, sel_btn[b], th.sel_fg); } // modal line selection (helix `x`): whole body rows, normal mode only - if ((pane.mode == .normal or modal_hover) and pane.msel.active) { - const hover_only = modal_hover and pane.mode != .normal; + if ((pane.body.mode == .normal or modal_hover) and pane.body.msel.active) { + const hover_only = modal_hover and pane.body.mode != .normal; const modal_bg = if (hover_only) colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)) else th.sel_bg; - const lo = @min(pane.msel.r0, pane.msel.r1); - const hi = @max(pane.msel.r0, pane.msel.r1); + const lo = @min(pane.body.msel.r0, pane.body.msel.r1); + const hi = @max(pane.body.msel.r0, pane.body.msel.r1); var row: u16 = BOX_H; // never paint the tag row while (row < body_bottom) : (row += 1) { const ar = pane.wrapAt(@as(i32, row) - @as(i32, BOX_H)).line; @@ -388,23 +388,23 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id } } const preview = normal.selRegexArmed(pane) != null; - const show_prim = (pane.mode == .normal and pane.vsel.active) or preview or - (modal_hover and pane.vsel.active); - const show_extra = pane.mode != .tty and pane.nsel > 0; + const show_prim = (pane.body.mode == .normal and pane.body.vsel.active) or preview or + (modal_hover and pane.body.vsel.active); + const show_extra = pane.body.mode != .tty and pane.body.nsel > 0; if (show_prim or show_extra) { const vpfx: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; var si: usize = 0; - while (si <= pane.nsel) : (si += 1) { - const primary = si == pane.nsel; + while (si <= pane.body.nsel) : (si += 1) { + const primary = si == pane.body.nsel; if (if (primary) !show_prim else !show_extra) continue; - const sr = if (primary) Pane.SelRange{ - .row = pane.cur_row, - .col = pane.cur_col, - .arow = if (pane.vsel.active) pane.vsel.row else pane.cur_row, - .acol = if (pane.vsel.active) pane.vsel.col else pane.cur_col, - } else pane.sels[si]; + const sr = if (primary) panes.Text.SelRange{ + .row = pane.body.cur_row, + .col = pane.body.cur_col, + .arow = if (pane.body.vsel.active) pane.body.vsel.row else pane.body.cur_row, + .acol = if (pane.body.vsel.active) pane.body.vsel.col else pane.body.cur_col, + } else pane.body.sels[si]; const bnd = edit.cellBounds(sr); - const hover_only = primary and modal_hover and pane.mode != .normal and !preview; + const hover_only = primary and modal_hover and pane.body.mode != .normal and !preview; const bg = if (hover_only) colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)) else if (primary) @@ -462,18 +462,18 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id // cursor: tracks the shell cursor until pinned by a click or a key // (the tag cursor above wins while the tag is focused) if (active and !pane.tag_edit) { - if (pane.mode != .tty) { + if (pane.body.mode != .tty) { const cur = panes.Terminal.gridCursor(pane); const goff = panes.Terminal.gridOffset(pane); - const crow = if (pane.cur_pinned) pane.cur_row else pane.surfRow(@as(i32, @intCast(cur.y)) + goff); - const ccol = if (pane.cur_pinned) pane.cur_col else @as(i32, @intCast(cur.x)); + const crow = if (pane.body.cur_pinned) pane.body.cur_row else pane.surfRow(@as(i32, @intCast(cur.y)) + goff); + const ccol = if (pane.body.cur_pinned) pane.body.cur_col else @as(i32, @intCast(cur.x)); const cwp = pane.wrapRow(crow, ccol); const prow = cwp.row + @as(i32, BOX_H); // Files store source-byte columns; the Surface stores display // cells, so account for every expanded tab before the cursor. const cx = if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayOffset(pane, crow, cwp.at, ccol) - else if (pane.cur_pinned) + else if (pane.body.cur_pinned) panes.File.lineDisplayOffset( modal.lineSlice(body, @intCast(@max(0, cwp.row))), @intCast(@max(0, cwp.at)), @@ -482,7 +482,7 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id else ccol; if (prow >= BOX_H and cx >= 0 and prow < body_bottom and cx < tw) - s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = body_y + @as(u16, @intCast(prow - BOX_H)), .bar = pane.mode == .insert }; + s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = body_y + @as(u16, @intCast(prow - BOX_H)), .bar = pane.body.mode == .insert }; } else if (panes.Terminal.visibleCursor(pane)) |cur| { if (cur.y + BOX_H < body_bottom and cur.x < tw) s.cursor = .{ .x = tx + cur.x, .y = body_y + cur.y }; diff --git a/src/colors.zig b/src/colors.zig index d6e1d535..741187c6 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -572,8 +572,8 @@ test "line numbers stay quiet without a current-line tag background" { const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); const pane = try p.setTestFile("first\nsecond\n"); - pane.cur_pinned = true; - pane.cur_row = 0; + pane.body.cur_pinned = true; + pane.body.cur_row = 0; var custom = themes[0]; custom.name = try gpa.dupe(u8, "quiet-gutter"); custom.lineno = .{ 70, 70, 70 }; @@ -598,7 +598,7 @@ test "line numbers stay quiet without a current-line tag background" { try std.testing.expectEqual(Color{ .rgb = custom.bg.? }, fallback.at(x, y).style.bg); try std.testing.expect(fallback.at(x, y).style.bold); // Moving the caret clears the previous cue; editing the tag parks it. - pane.cur_row = 1; + pane.body.cur_row = 1; const moved = try p.render(p.scratch.allocator()); try std.testing.expect(!moved.at(x, y).style.bold); try std.testing.expect(moved.at(x, y + 1).style.bold); diff --git a/src/config.zig b/src/config.zig index 4b47b188..38b87011 100644 --- a/src/config.zig +++ b/src/config.zig @@ -173,16 +173,16 @@ test "Space-k is unbound while Kill and other k chords remain available" { const p = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("first\nsecond\n"); - pane.cur_row = 1; + pane.body.cur_row = 1; while (p.nextEffect()) |_| {} p.update(.{ .key = .{ .cp = ' ' } }); try std.testing.expect(p.leader_on); p.update(.{ .key = .{ .cp = 'k' } }); try std.testing.expect(!p.leader_on and !p.quit); - try std.testing.expectEqual(@as(i32, 1), pane.cur_row); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); while (p.nextEffect()) |effect| try std.testing.expect(effect != .quit); p.update(.{ .key = .{ .cp = 'k' } }); - try std.testing.expectEqual(@as(i32, 0), pane.cur_row); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); try std.testing.expect(p.executeBuiltinLine(p.active, "Kill")); try std.testing.expect(p.quit); } diff --git a/src/detached/client.zig b/src/detached/client.zig index 6476d521..4468c961 100644 --- a/src/detached/client.zig +++ b/src/detached/client.zig @@ -868,9 +868,9 @@ test "detached selection pipe runs off the loop and returns through the attached try h.init(60, 16); defer h.deinit(); const pane = try h.core.setTestFile("one\ntwo\n"); - pane.cur_row = 0; - pane.cur_col = 2; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + pane.body.cur_row = 0; + pane.body.cur_col = 2; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; var client = try h.attach(60, 16); defer client.deinit(); _ = try h.pumpUntil(&client, .frame); diff --git a/src/detached/server.zig b/src/detached/server.zig index 2b9c9247..a3694c57 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -1251,8 +1251,8 @@ test "detached worker setup failure completes requests without changing document try std.testing.expect(s.core.lsp_wait == null); try std.testing.expect(s.lsp_task == null); - pane.cur_col = 2; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + pane.body.cur_col = 2; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; s.core.update(.{ .key = .{ .cp = '|' } }); s.core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); s.core.update(.{ .key = .{ .cp = pardes.Key.enter } }); diff --git a/src/dump.zig b/src/dump.zig index 46cf6001..2fb9ce80 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -740,7 +740,7 @@ fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previo const restored = try pardes.panes.Terminal.restore(p, src, revive); p.installPane(i, restored); try restored.setOwnedCwd(t.cwd); - if (std.mem.startsWith(u8, src.tag, "TTY ")) restored.mode = .tty; + if (std.mem.startsWith(u8, src.tag, "TTY ")) restored.body.mode = .tty; if (revive) p.emit(.{ .spawn = .{ .pane = @intCast(i), .cwd = .from(t.cwd) } }); break :terminal restored; }, @@ -773,7 +773,7 @@ fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previo errdefer gpa.destroy(history); const restored = try p.newDocPane(i); restored.file = .{ .path = path, .content = content, .history = history }; - restored.cur_pinned = true; + restored.body.cur_pinned = true; restored.cols = @max(1, src.cols); restored.rows = @max(1, src.rows); p.emit(.{ .watch = .{ .pane = @intCast(i), .on = true, .mode = .baseline_disk } }); diff --git a/src/edit.zig b/src/edit.zig index 04416b67..f1b381d6 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -14,6 +14,7 @@ const pdf_enabled = panes.Pdf.enabled; const lsp = @import("lsp/lsp.zig"); const platform = pardes.platform; const Pane = panes.Pane; +const Text = panes.Text; const TagHit = @import("tag_layer.zig").Hit; const BOX_H = pardes.BOX_H; const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; @@ -91,11 +92,11 @@ pub fn applyPaste(p: *Pardes, bytes: []const u8) void { if (normal.selRegexArmed(pane)) |a| normal.applySelRegex(p, pane, a.pat, a.split); return; } - if (pane.isTerminal() and pane.mode == .tty) return typeToTty(p, id, pane, bytes); + if (pane.isTerminal() and pane.body.mode == .tty) return typeToTty(p, id, pane, bytes); switch (if (req) |r| r.mode else .after) { - .after => pasteText(p, pane, bytes, false, 1), - .before => pasteText(p, pane, bytes, true, 1), - .replace => replaceWithText(p, pane, bytes), + .after => pasteText(p, &pane.body, bytes, false, 1), + .before => pasteText(p, &pane.body, bytes, true, 1), + .replace => replaceWithText(p, &pane.body, bytes), } } @@ -104,13 +105,13 @@ pub fn clipYank(p: *Pardes, pane: *Pane, main_only: bool) void { if (pv.selection_text.len > 0) setClipboard(p, pv.selection_text); return; }; - if (pane.nsel > 0 and !main_only) { - normal.replaySels(p, pane, .{ .normal = .{ .edit = .{ .kind = .yank, .count = 1 } } }); + if (pane.body.nsel > 0 and !main_only) { + normal.replaySels(p, &pane.body, .{ .normal = .{ .edit = .{ .kind = .yank, .count = 1 } } }); } else { - const others = pane.nsel; - pane.nsel = 0; - normalYank(p, pane); - pane.nsel = others; + const others = pane.body.nsel; + pane.body.nsel = 0; + normalYank(p, &pane.body); + pane.body.nsel = others; } p.emit(.{ .set_clipboard = {} }); } @@ -135,7 +136,7 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { if (pane.pointerSelection(gesture) != null) return; pane.clearPointerSelection(slot); // Refresh the source map before translating the rendered rectangle. - const raw = pane.isTerminal() and pane.mode == .tty; + const raw = pane.isTerminal() and pane.body.mode == .tty; const body = try body_layer.bodyText(p, p.scratch.allocator(), pane); const terminal_lines = if (pane.file == null and !raw) try panes.Terminal.cursorLines(p, pane) else &.{}; const first = @max(0, @min(gesture.r0, gesture.r1) - BOX_H); @@ -253,28 +254,28 @@ pub fn spanHas(r: i32, c: i32, ar: i32, ac: i32, br: i32, bc: i32) bool { pub fn currentSelText(p: *Pardes, pane: *Pane) ?[]const u8 { if (comptime pdf_enabled) if (p.native_images) if (pane.pdf) |pv| if (pv.selection != null and pv.selection_text.len > 0) return pv.selection_text; - if (pane.vsel.active) return vselText(p, pane); - if (!pane.msel.active) return null; - return yankRows(p, pane, @min(pane.msel.r0, pane.msel.r1), @max(pane.msel.r0, pane.msel.r1)); + if (pane.body.vsel.active) return vselText(p, &pane.body); + if (!pane.body.msel.active) return null; + return yankRows(p, &pane.body, @min(pane.body.msel.r0, pane.body.msel.r1), @max(pane.body.msel.r0, pane.body.msel.r1)); } -pub fn exitInsert(p: *Pardes, pane: *Pane) void { - pane.mode = .normal; - pane.msel.active = false; - pane.normal.clear(); - if (pane.append_at) |aa| { - pane.append_at = null; - const text = flatSurface(p, pane) catch return; - const gap = modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.cur_row)), .col = @intCast(@max(0, pane.cur_col)) }); +pub fn exitInsert(p: *Pardes, t: *Text) void { + t.mode = .normal; + t.msel.active = false; + t.normal.clear(); + if (t.append_at) |aa| { + t.append_at = null; + const text = flatSurface(p, t) catch return; + const gap = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) }); const a_off = modal.offsetAt(text, .{ .row = @intCast(@max(0, aa.row)), .col = @intCast(@max(0, aa.col)) }); const back = @max(a_off, modal.prevGrapheme(text, gap)); const bc = modal.positionAt(text, back); - pane.cur_row = @intCast(bc.row); - pane.cur_col = @intCast(bc.col); - pane.vsel = .{ .active = a_off != back, .row = aa.row, .col = aa.col, .explicit = false }; - pane.cur_pinned = true; - pane.ensureCursorVisible(); - for (pane.sels[0..pane.nsel]) |*s| { + t.cur_row = @intCast(bc.row); + t.cur_col = @intCast(bc.col); + t.vsel = .{ .active = a_off != back, .row = aa.row, .col = aa.col, .explicit = false }; + t.cur_pinned = true; + t.pane().ensureCursorVisible(); + for (t.sels[0..t.nsel]) |*s| { const sgap = modal.offsetAt(text, .{ .row = @intCast(@max(0, s.row)), .col = @intCast(@max(0, s.col)) }); const b2 = if (back == gap) sgap else modal.prevGrapheme(text, sgap); const bp = modal.positionAt(text, b2); @@ -286,7 +287,8 @@ pub fn exitInsert(p: *Pardes, pane: *Pane) void { } } -pub fn paneCursorLines(p: *Pardes, pane: *Pane) ![]const []const u8 { +pub fn paneCursorLines(p: *Pardes, t: *Text) ![]const []const u8 { + const pane = t.pane(); const arena = p.scratch.allocator(); if (pane.file) |*f| return panes.File.cursorLines(arena, pane, f); if (pane.hasPdf()) { @@ -296,10 +298,11 @@ pub fn paneCursorLines(p: *Pardes, pane: *Pane) ![]const []const u8 { return panes.Terminal.cursorLines(p, pane); } -pub fn paneByteAtDisplay(p: *Pardes, pane: *Pane, row: i32, from_raw: i32, display_col: i32) i32 { +pub fn paneByteAtDisplay(p: *Pardes, t: *Text, row: i32, from_raw: i32, display_col: i32) i32 { + const pane = t.pane(); if (pane.file != null) return panes.File.byteAtRowDisplay(pane, row, from_raw, display_col); - const lines = paneCursorLines(p, pane) catch return @max(0, from_raw + display_col); + const lines = paneCursorLines(p, t) catch return @max(0, from_raw + display_col); const local = row; if (local < 0 or @as(usize, @intCast(local)) >= lines.len) return @max(0, from_raw + display_col); @@ -312,14 +315,16 @@ pub fn paneByteAtDisplay(p: *Pardes, pane: *Pane, row: i32, from_raw: i32, displ /// Freeze the live terminal cursor into the modal coordinate space. The /// emulator reports screen cells; editing state stores UTF-8 byte offsets. -pub fn pinPaneCursor(p: *Pardes, pane: *Pane) void { - if (pane.cur_pinned) return; +pub fn pinPaneCursor(p: *Pardes, t: *Text) void { + const pane = t.pane(); + if (t.cur_pinned) return; pane.pinCursor(); if (pane.file == null and !pane.hasPdf()) - pane.cur_col = paneByteAtDisplay(p, pane, pane.cur_row, 0, pane.cur_col); + t.cur_col = paneByteAtDisplay(p, t, t.cur_row, 0, t.cur_col); } -pub fn flatSurface(p: *Pardes, pane: *Pane) ![]const u8 { +pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { + const pane = t.pane(); if (pane.file) |f| return f.content; if (pane.hasPdf()) { if (comptime pdf_enabled) return pane.pdf.?.ensureText(p.pdf_gpa); @@ -329,28 +334,31 @@ pub fn flatSurface(p: *Pardes, pane: *Pane) ![]const u8 { return panes.Terminal.flatSurface(p, pane, lines); } -pub fn paneWrapWidth(p: *const Pardes, pane: *const Pane) usize { +pub fn paneWrapWidth(p: *const Pardes, t: *Text) usize { + const pane = t.pane(); if (pane.file == null) return 0; return panes.File.wrapWidth(pane, p.settings.wrap); } /// Route shared edit operations to a file's content or a terminal overlay. -fn editText(p: *Pardes, pane: *Pane, lo: i32, hi: i32, col: i32) ?panes.EditText { +fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText { + const pane = t.pane(); if (pane.file) |f| return .{ .text = f.content, .row0 = 0 }; if (pane.image != null or pane.hasPdf()) return null; return panes.Terminal.editText(p, pane, lo, hi, col); } -fn editTextEol(p: *Pardes, pane: *Pane, b: Bounds) ?panes.EditText { - const eb = editText(p, pane, b.lo_row, b.hi_row, -1) orelse return null; +fn editTextEol(p: *Pardes, t: *Text, b: Bounds) ?panes.EditText { + const eb = editText(p, t, b.lo_row, b.hi_row, -1) orelse return null; const r: usize = @intCast(@max(0, b.hi_row - eb.row0)); if (r + 1 < modal.lineCount(eb.text)) return eb; if (b.hi_col < @as(i32, @intCast(modal.lineSlice(eb.text, r).len))) return eb; - return editText(p, pane, b.lo_row, b.hi_row + 1, -1); + return editText(p, t, b.lo_row, b.hi_row + 1, -1); } /// install a rewritten editable text (frees the old one) -fn setEditText(p: *Pardes, pane: *Pane, new: []u8) void { +fn setEditText(p: *Pardes, t: *Text, new: []u8) void { + const pane = t.pane(); if (pane.file) |*f| return panes.File.setContent(p, f, new); panes.Terminal.setEditText(p, pane, new); } @@ -359,73 +367,75 @@ pub const InsertAt = enum { at, append, line_start, line_end, open_below, open_a /// Files insert only inside existing rows and at grapheme boundaries. /// Terminal overlays can materialize virtual rows/columns, so keep those. -pub fn clampFileCursor(pane: *Pane) bool { +pub fn clampFileCursor(t: *Text) bool { + const pane = t.pane(); const file = if (pane.file) |*file| file else return false; - const old_row = pane.cur_row; - const old_col = pane.cur_col; + const old_row = t.cur_row; + const old_col = t.cur_col; const last = panes.File.nlines(pane.gpa, file) -| 1; - pane.cur_row = @intCast(@min(last, @as(usize, @intCast(@max(0, pane.cur_row))))); - const line = panes.File.sourceLine(pane, pane.cur_row); - pane.cur_col = @intCast(modal.graphemeStart(line, @min(line.len, @as(usize, @intCast(@max(0, pane.cur_col)))))); - return old_row != pane.cur_row or old_col != pane.cur_col; + t.cur_row = @intCast(@min(last, @as(usize, @intCast(@max(0, t.cur_row))))); + const line = panes.File.sourceLine(pane, t.cur_row); + t.cur_col = @intCast(modal.graphemeStart(line, @min(line.len, @as(usize, @intCast(@max(0, t.cur_col)))))); + return old_row != t.cur_row or old_col != t.cur_col; } -pub fn enterInsert(p: *Pardes, pane: *Pane, where: InsertAt, cnt: usize) void { +pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) void { + const pane = t.pane(); if (pane.hasPdf()) return; - pinPaneCursor(p, pane); - _ = clampFileCursor(pane); + pinPaneCursor(p, t); + _ = clampFileCursor(t); // snapshot once per insert session (WITH the pre-insert selection) so // `u` undoes the whole session and restores what was selected - pushUndo(p, pane); - pane.select = false; - pane.append_at = null; - pane.sticky_col = -1; - const text = flatSurface(p, pane) catch { - pane.mode = .insert; - pane.msel.active = false; - pane.vsel.active = false; - pane.normal.clear(); + pushUndo(p, t); + t.select = false; + t.append_at = null; + t.sticky_col = -1; + const text = flatSurface(p, t) catch { + t.mode = .insert; + t.msel.active = false; + t.vsel.active = false; + t.normal.clear(); return; }; - const cur = pane.toModalCursor(); - const line = panes.File.textLine(pane, text, cur.row); - const b: ?Bounds = if (pane.vsel.active) vselBounds(pane) else null; + const cur = t.toModalCursor(); + const line = panes.File.textLine(t, text, cur.row); + const b: ?Bounds = if (t.vsel.active) vselBounds(t) else null; switch (where) { .at => { if (b) |bb| { - pane.cur_row = bb.lo_row; - pane.cur_col = bb.lo_col; - pane.vsel = .{ .active = true, .row = bb.hi_row, .col = bb.hi_col, .explicit = false }; - pane.cur_pinned = true; + t.cur_row = bb.lo_row; + t.cur_col = bb.lo_col; + t.vsel = .{ .active = true, .row = bb.hi_row, .col = bb.hi_col, .explicit = false }; + t.cur_pinned = true; } }, .append => { - const lo_row = if (b) |bb| bb.lo_row else pane.cur_row; - const lo_col = if (b) |bb| bb.lo_col else pane.cur_col; - const hi_row = if (b) |bb| bb.hi_row else pane.cur_row; - const hi_col = if (b) |bb| bb.hi_col else pane.cur_col; - pane.append_at = .{ .row = lo_row, .col = lo_col }; + const lo_row = if (b) |bb| bb.lo_row else t.cur_row; + const lo_col = if (b) |bb| bb.lo_col else t.cur_col; + const hi_row = if (b) |bb| bb.hi_row else t.cur_row; + const hi_col = if (b) |bb| bb.hi_col else t.cur_col; + t.append_at = .{ .row = lo_row, .col = lo_col }; const gap = modal.nextGrapheme(text, modal.offsetAt(text, .{ .row = @intCast(@max(0, hi_row)), .col = @intCast(@max(0, hi_col)) })); const gc = modal.positionAt(text, gap); - pane.cur_row = @intCast(gc.row); - pane.cur_col = @intCast(gc.col); - pane.vsel = .{ .active = b != null, .row = lo_row, .col = lo_col, .explicit = false }; - pane.cur_pinned = true; + t.cur_row = @intCast(gc.row); + t.cur_col = @intCast(gc.col); + t.vsel = .{ .active = b != null, .row = lo_row, .col = lo_col, .explicit = false }; + t.cur_pinned = true; }, .line_start => { - pane.fromModalCursor(.{ .row = cur.row, .col = modal.firstNonWs(line) }); - pane.vsel.active = false; + t.fromModalCursor(.{ .row = cur.row, .col = modal.firstNonWs(line) }); + t.vsel.active = false; }, .line_end => { - pane.cur_col = @intCast(line.len); - pane.cur_pinned = true; - pane.vsel.active = false; + t.cur_col = @intCast(line.len); + t.cur_pinned = true; + t.vsel.active = false; }, .open_below, .open_above => { - pane.vsel.active = false; + t.vsel.active = false; const below = where == .open_below; - const abs: i32 = if (b) |bb| (if (below) bb.hi_row else bb.lo_row) else pane.cur_row; - const eb = editText(p, pane, abs, abs, -1) orelse return; + const abs: i32 = if (b) |bb| (if (below) bb.hi_row else bb.lo_row) else t.cur_row; + const eb = editText(p, t, abs, abs, -1) orelse return; const row: usize = @intCast(@max(0, abs - eb.row0)); const ind = modal.indentText(modal.lineSlice(eb.text, row)); const arena = p.scratch.allocator(); @@ -449,146 +459,147 @@ pub fn enterInsert(p: *Pardes, pane: *Pane, where: InsertAt, cnt: usize) void { else .{ .row = row, .col = 0 }; const new = modal.insertAt(p.gpa, eb.text, at, block) catch return; - setEditText(p, pane, new); - pane.cur_row = @as(i32, @intCast(if (below) row + 1 else row)) + eb.row0; - pane.cur_col = @intCast(ind.len); - pane.cur_pinned = true; + setEditText(p, t, new); + t.cur_row = @as(i32, @intCast(if (below) row + 1 else row)) + eb.row0; + t.cur_col = @intCast(ind.len); + t.cur_pinned = true; if (cnt > 1 and !p.multi_on) opened: { - const t2 = flatSurface(p, pane) catch break :opened; - var rs: [Pane.max_selections]modal.Selection = undefined; - const m = @min(cnt, Pane.max_selections); + const t2 = flatSurface(p, t) catch break :opened; + var rs: [Text.max_selections]modal.Selection = undefined; + const m = @min(cnt, Text.max_selections); for (0..m) |k| { - const o = modal.offsetAt(t2, .{ .row = @intCast(@max(0, pane.cur_row) + @as(i32, @intCast(k))), .col = ind.len }); + const o = modal.offsetAt(t2, .{ .row = @intCast(@max(0, t.cur_row) + @as(i32, @intCast(k))), .col = ind.len }); rs[k] = .{ .anchor = o, .head = o }; } - pane.setRanges(t2, rs[0..m], &.{}, 0, false); + t.setRanges(t2, rs[0..m], &.{}, 0, false); } }, } - pane.mode = .insert; - pane.msel.active = false; - pane.normal.clear(); + t.mode = .insert; + t.msel.active = false; + t.normal.clear(); pane.ensureCursorVisible(); } -pub fn handleInsert(p: *Pardes, pane: *Pane, key: Key) void { - if (pane.nsel == 0) return insertKey(p, pane, key); - normal.replaySels(p, pane, .{ .insert = key }); +pub fn handleInsert(p: *Pardes, t: *Text, key: Key) void { + if (t.nsel == 0) return insertKey(p, t, key); + normal.replaySels(p, t, .{ .insert = key }); } -pub fn insertKey(p: *Pardes, pane: *Pane, key: Key) void { +pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { + const pane = t.pane(); // helix aliases: normalize to the base key and re-dispatch - if (hit(key, config.insert_backspace_alias)) return insertKey(p, pane, .{ .cp = Key.backspace }); - if (hit(key, config.insert_enter_alias)) return insertKey(p, pane, .{ .cp = Key.enter }); - if (hit(key, config.insert_delete_alias)) return insertKey(p, pane, .{ .cp = Key.delete }); - pane.vsel.active = false; - if (!pane.cur_pinned) pinPaneCursor(p, pane); - _ = clampFileCursor(pane); + if (hit(key, config.insert_backspace_alias)) return insertKey(p, t, .{ .cp = Key.backspace }); + if (hit(key, config.insert_enter_alias)) return insertKey(p, t, .{ .cp = Key.enter }); + if (hit(key, config.insert_delete_alias)) return insertKey(p, t, .{ .cp = Key.delete }); + t.vsel.active = false; + if (!t.cur_pinned) pinPaneCursor(p, t); + _ = clampFileCursor(t); switch (key.cp) { Key.left, Key.right, Key.up, Key.down => { - const lines = paneCursorLines(p, pane) catch return; - const cur0 = pane.toModalCursor(); + const lines = paneCursorLines(p, t) catch return; + const cur0 = t.toModalCursor(); const nc = switch (key.cp) { Key.left => modal.charLeft(lines, cur0), Key.right => modal.charRight(lines, cur0), - Key.up => Pane.insertVerticalCursor(lines, cur0, false), - Key.down => Pane.insertVerticalCursor(lines, cur0, true), + Key.up => Text.insertVerticalCursor(lines, cur0, false), + Key.down => Text.insertVerticalCursor(lines, cur0, true), else => cur0, }; - pane.fromModalCursor(nc); + t.fromModalCursor(nc); pane.ensureCursorVisible(); return; }, Key.page_up, Key.page_down => { // helix binds insert pageup/pagedown to the same view // scroll + cursor snap as normal mode - const flat = flatSurface(p, pane) catch return; - const range = pane.primaryRange(flat, 0); + const flat = flatSurface(p, t) catch return; + const range = t.primaryRange(flat, 0); const step: i32 = @intCast(@max(1, pane.rows)); - pane.scrollViewMove(flat, range, if (key.cp == Key.page_down) step else -step); + t.scrollViewMove(flat, range, if (key.cp == Key.page_down) step else -step); return; }, Key.home => { - pane.cur_col = 0; - pane.cur_pinned = true; + t.cur_col = 0; + t.cur_pinned = true; pane.ensureCursorVisible(); return; }, Key.end => { // helix insert End: past the last char (goto_line_end_newline) - const text = flatSurface(p, pane) catch return; - const cur0 = pane.toModalCursor(); - pane.cur_col = @intCast(panes.File.textLine(pane, text, cur0.row).len); - pane.cur_pinned = true; + const text = flatSurface(p, t) catch return; + const cur0 = t.toModalCursor(); + t.cur_col = @intCast(panes.File.textLine(t, text, cur0.row).len); + t.cur_pinned = true; pane.ensureCursorVisible(); return; }, else => {}, } - const eb = editText(p, pane, pane.cur_row, pane.cur_row, pane.cur_col) orelse return; + const eb = editText(p, t, t.cur_row, t.cur_row, t.cur_col) orelse return; const text = eb.text; - const c = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) }; + const c = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - eb.row0)), .col = @intCast(@max(0, t.cur_col)) }; if (key.text.len > 0 and !key.ctrl and !key.alt) { const new = modal.insertAt(p.gpa, text, c, key.text) catch return; - setEditText(p, pane, new); + setEditText(p, t, new); for (key.text) |ch| { if (ch == '\n') { - pane.cur_row += 1; - pane.cur_col = 0; - } else pane.cur_col += 1; + t.cur_row += 1; + t.cur_col = 0; + } else t.cur_col += 1; } - pane.cur_pinned = true; + t.cur_pinned = true; pane.ensureCursorVisible(); return; } // helix insert-mode kills (word/line; deleteSpan is exclusive) if (hit(key, config.delete_word_backward)) { const e2 = if (c.row == 0 and c.col == 0) - (editText(p, pane, pane.cur_row - 1, pane.cur_row, 0) orelse return) + (editText(p, t, t.cur_row - 1, t.cur_row, 0) orelse return) else eb; - const c2 = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - e2.row0)), .col = c.col }; + const c2 = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - e2.row0)), .col = c.col }; const g = modal.offsetAt(e2.text, c2); if (g == 0) return; const wr = modal.moveWord(e2.text, .{ .anchor = g, .head = g }, 1, .prev_word_start); const from = @min(wr.anchor, wr.head); const fc = modal.positionAt(e2.text, from); const new = modal.deleteSpan(p.gpa, e2.text, fc, c2) catch return; - setEditText(p, pane, new); - pane.cur_row = @as(i32, @intCast(fc.row)) + e2.row0; - pane.cur_col = @intCast(fc.col); - pane.cur_pinned = true; + setEditText(p, t, new); + t.cur_row = @as(i32, @intCast(fc.row)) + e2.row0; + t.cur_col = @intCast(fc.col); + t.cur_pinned = true; pane.ensureCursorVisible(); return; } if (hit(key, config.delete_word_forward)) { const e2 = if (c.col >= modal.lineSlice(text, c.row).len and c.row + 1 >= modal.lineCount(text)) - (editText(p, pane, pane.cur_row, pane.cur_row + 1, pane.cur_col) orelse return) + (editText(p, t, t.cur_row, t.cur_row + 1, t.cur_col) orelse return) else eb; - const c2 = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - e2.row0)), .col = c.col }; + const c2 = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - e2.row0)), .col = c.col }; const g = modal.offsetAt(e2.text, c2); const wr = modal.moveWord(e2.text, .{ .anchor = g, .head = g }, 1, .next_word_end); const to = @max(wr.anchor, wr.head); if (to <= g) return; const new = modal.deleteSpan(p.gpa, e2.text, c2, modal.positionAt(e2.text, to)) catch return; - setEditText(p, pane, new); - pane.cur_pinned = true; + setEditText(p, t, new); + t.cur_pinned = true; return; } if (hit(key, config.kill_to_line_start)) { const new = modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = 0 }, c) catch return; - setEditText(p, pane, new); - pane.cur_col = 0; - pane.cur_pinned = true; + setEditText(p, t, new); + t.cur_col = 0; + t.cur_pinned = true; pane.ensureCursorVisible(); return; } if (hit(key, config.kill_to_line_end)) { const llen = modal.lineSlice(text, c.row).len; const new = modal.deleteSpan(p.gpa, text, c, .{ .row = c.row, .col = llen }) catch return; - setEditText(p, pane, new); - pane.cur_pinned = true; + setEditText(p, t, new); + t.cur_pinned = true; return; } switch (key.cp) { @@ -600,35 +611,35 @@ pub fn insertKey(p: *Pardes, pane: *Pane, key: Key) void { block[0] = '\n'; @memset(block[1..], ' '); const new = modal.insertAt(p.gpa, text, c, block) catch return; - setEditText(p, pane, new); - pane.cur_row += 1; - pane.cur_col = @intCast(indent); - pane.cur_pinned = true; + setEditText(p, t, new); + t.cur_row += 1; + t.cur_col = @intCast(indent); + t.cur_pinned = true; pane.ensureCursorVisible(); }, Key.backspace => { - if (pane.cur_col > 0) { + if (t.cur_col > 0) { const line = modal.lineSlice(text, c.row); const prev = modal.prevGrapheme(line, c.col); const new = modal.deleteChar(p.gpa, text, .{ .row = c.row, .col = prev }) catch return; - setEditText(p, pane, new); - pane.cur_col = @intCast(prev); - pane.cur_pinned = true; + setEditText(p, t, new); + t.cur_col = @intCast(prev); + t.cur_pinned = true; pane.ensureCursorVisible(); return; } // at col 0: eat the newline above (join up) — a terminal grows // its buffer over the row it is joining with - if (pane.cur_row <= 0) return; - const e2 = editText(p, pane, pane.cur_row - 1, pane.cur_row, 0) orelse return; - const row: usize = @intCast(@max(0, pane.cur_row - e2.row0)); + if (t.cur_row <= 0) return; + const e2 = editText(p, t, t.cur_row - 1, t.cur_row, 0) orelse return; + const row: usize = @intCast(@max(0, t.cur_row - e2.row0)); if (row == 0) return; const prevlen = modal.lineSlice(e2.text, row - 1).len; const new = modal.deleteSpan(p.gpa, e2.text, .{ .row = row - 1, .col = prevlen }, .{ .row = row, .col = 0 }) catch return; - setEditText(p, pane, new); - pane.cur_row -= 1; - pane.cur_col = @intCast(prevlen); - pane.cur_pinned = true; + setEditText(p, t, new); + t.cur_row -= 1; + t.cur_col = @intCast(prevlen); + t.cur_pinned = true; pane.ensureCursorVisible(); }, Key.delete => { @@ -637,15 +648,15 @@ pub fn insertKey(p: *Pardes, pane: *Pane, key: Key) void { const line = modal.lineSlice(text, c.row); if (c.col < line.len) { const new = modal.deleteChar(p.gpa, text, c) catch return; - setEditText(p, pane, new); + setEditText(p, t, new); } else { - const e2 = editText(p, pane, pane.cur_row, pane.cur_row + 1, pane.cur_col) orelse return; - const row: usize = @intCast(@max(0, pane.cur_row - e2.row0)); + const e2 = editText(p, t, t.cur_row, t.cur_row + 1, t.cur_col) orelse return; + const row: usize = @intCast(@max(0, t.cur_row - e2.row0)); if (row + 1 >= modal.lineCount(e2.text)) return; const new = modal.deleteSpan(p.gpa, e2.text, .{ .row = row, .col = c.col }, .{ .row = row + 1, .col = 0 }) catch return; - setEditText(p, pane, new); + setEditText(p, t, new); } - pane.cur_pinned = true; + t.cur_pinned = true; }, Key.tab => { const ln = modal.lineSlice(text, c.row); @@ -656,51 +667,51 @@ pub fn insertKey(p: *Pardes, pane: *Pane, key: Key) void { p.lspRequest(p.active, .completion, ""); if (p.lsp_seq != seq) return; } - insertTab(p, pane); + insertTab(p, t); }, else => {}, } } -pub fn insertTab(p: *Pardes, pane: *Pane) void { - const eb = editText(p, pane, pane.cur_row, pane.cur_row, pane.cur_col) orelse return; +pub fn insertTab(p: *Pardes, t: *Text) void { + const eb = editText(p, t, t.cur_row, t.cur_row, t.cur_col) orelse return; const c: modal.Cursor = .{ - .row = @intCast(@max(0, pane.cur_row - eb.row0)), - .col = @intCast(@max(0, pane.cur_col)), + .row = @intCast(@max(0, t.cur_row - eb.row0)), + .col = @intCast(@max(0, t.cur_col)), }; const pad = modal.INDENT_W - (c.col % modal.INDENT_W); const new = modal.insertAt(p.gpa, eb.text, c, " "[0..pad]) catch return; - setEditText(p, pane, new); - pane.cur_col += @intCast(pad); - pane.cur_pinned = true; - pane.ensureCursorVisible(); + setEditText(p, t, new); + t.cur_col += @intCast(pad); + t.cur_pinned = true; + t.pane().ensureCursorVisible(); } const Bounds = struct { lo_row: i32, lo_col: i32, hi_row: i32, hi_col: i32 }; /// a range's two cells, normalized to document order -pub fn cellBounds(s: Pane.SelRange) Bounds { +pub fn cellBounds(s: Text.SelRange) Bounds { if (s.row < s.arow or (s.row == s.arow and s.col < s.acol)) return .{ .lo_row = s.row, .lo_col = s.col, .hi_row = s.arow, .hi_col = s.acol }; return .{ .lo_row = s.arow, .lo_col = s.acol, .hi_row = s.row, .hi_col = s.col }; } /// the char selection [anchor, cursor] normalized to document order -fn vselBounds(pane: *Pane) Bounds { - return cellBounds(.{ .row = pane.cur_row, .col = pane.cur_col, .arow = pane.vsel.row, .acol = pane.vsel.col }); +fn vselBounds(t: *Text) Bounds { + return cellBounds(.{ .row = t.cur_row, .col = t.cur_col, .arow = t.vsel.row, .acol = t.vsel.col }); } -fn vselText(p: *Pardes, pane: *Pane) []const u8 { +fn vselText(p: *Pardes, t: *Text) []const u8 { const arena = p.scratch.allocator(); - const b = vselBounds(pane); - const text = flatSurface(p, pane) catch return ""; + const b = vselBounds(t); + const text = flatSurface(p, t) catch return ""; return modal.rangeText(arena, text, .{ .row = @intCast(@max(0, b.lo_row)), .col = @intCast(@max(0, b.lo_col)) }, .{ .row = @intCast(@max(0, b.hi_row)), .col = @intCast(@max(0, b.hi_col)) }) catch ""; } /// join surface rows [r0, r1] (absolute) with '\n'; scratch-owned -fn yankRows(p: *Pardes, pane: *Pane, r0: i32, r1: i32) []const u8 { +fn yankRows(p: *Pardes, t: *Text, r0: i32, r1: i32) []const u8 { const arena = p.scratch.allocator(); - const lines = paneCursorLines(p, pane) catch return ""; + const lines = paneCursorLines(p, t) catch return ""; const rows_count: usize = @intCast(@max(0, r1 - r0 + 1)); var total: usize = rows_count -| 1; var i = r0; @@ -725,54 +736,54 @@ fn yankRows(p: *Pardes, pane: *Pane, r0: i32, r1: i32) []const u8 { return out; } -pub fn normalDelete(p: *Pardes, pane: *Pane, yank: bool) void { - pane.select = false; // helix delete exits select mode - pane.sticky_col = -1; - if (pane.vsel.active) { - const b = vselBounds(pane); - if (yank) setYank(p, vselText(p, pane)); // read the range before the move - pushUndo(p, pane); - const eb = editTextEol(p, pane, b) orelse { - pane.vsel.active = false; +pub fn normalDelete(p: *Pardes, t: *Text, yank: bool) void { + t.select = false; // helix delete exits select mode + t.sticky_col = -1; + if (t.vsel.active) { + const b = vselBounds(t); + if (yank) setYank(p, vselText(p, t)); // read the range before the move + pushUndo(p, t); + const eb = editTextEol(p, t, b) orelse { + t.vsel.active = false; return; }; const d = modal.deleteRange(p.gpa, eb.text, .{ .row = @intCast(@max(0, b.lo_row - eb.row0)), .col = @intCast(@max(0, b.lo_col)) }, .{ .row = @intCast(@max(0, b.hi_row - eb.row0)), .col = @intCast(@max(0, b.hi_col)) }) catch { - pane.vsel.active = false; + t.vsel.active = false; return; }; - setEditText(p, pane, d.content); + setEditText(p, t, d.content); p.gpa.free(d.deleted); - pane.cur_row = b.lo_row; - pane.cur_col = b.lo_col; - pane.clampCursor(d.content, eb.row0); + t.cur_row = b.lo_row; + t.cur_col = b.lo_col; + t.clampCursor(d.content, eb.row0); return; } - if (pane.msel.active) { - const r0 = @min(pane.msel.r0, pane.msel.r1); - const r1 = @max(pane.msel.r0, pane.msel.r1); - pushUndo(p, pane); + if (t.msel.active) { + const r0 = @min(t.msel.r0, t.msel.r1); + const r1 = @max(t.msel.r0, t.msel.r1); + pushUndo(p, t); // linewise: a line's newline lives on the row below it - const eb = editText(p, pane, r0, r1 + 1, -1) orelse { - pane.msel.active = false; + const eb = editText(p, t, r0, r1 + 1, -1) orelse { + t.msel.active = false; return; }; const d = modal.deleteLines(p.gpa, eb.text, @intCast(@max(0, r0 - eb.row0)), @intCast(@max(0, r1 - eb.row0))) catch { - pane.msel.active = false; + t.msel.active = false; return; }; - setEditText(p, pane, d.content); + setEditText(p, t, d.content); if (yank) setYank(p, d.deleted); p.gpa.free(d.deleted); const n = modal.lineCount(d.content); - pane.cur_row = @as(i32, @intCast(@min(@as(usize, @intCast(@max(0, r0 - eb.row0))), if (n == 0) 0 else n - 1))) + eb.row0; - pane.cur_col = 0; - pane.msel.active = false; - pane.cur_pinned = true; - pane.ensureCursorVisible(); + t.cur_row = @as(i32, @intCast(@min(@as(usize, @intCast(@max(0, r0 - eb.row0))), if (n == 0) 0 else n - 1))) + eb.row0; + t.cur_col = 0; + t.msel.active = false; + t.cur_pinned = true; + t.pane().ensureCursorVisible(); } else { - pushUndo(p, pane); - const eb = editTextEol(p, pane, .{ .lo_row = pane.cur_row, .lo_col = pane.cur_col, .hi_row = pane.cur_row, .hi_col = pane.cur_col }) orelse return; - const c = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) }; + pushUndo(p, t); + const eb = editTextEol(p, t, .{ .lo_row = t.cur_row, .lo_col = t.cur_col, .hi_row = t.cur_row, .hi_col = t.cur_col }) orelse return; + const c = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - eb.row0)), .col = @intCast(@max(0, t.cur_col)) }; if (yank) { const arena = p.scratch.allocator(); setYank(p, modal.rangeText(arena, eb.text, c, c) catch return); @@ -780,38 +791,39 @@ pub fn normalDelete(p: *Pardes, pane: *Pane, yank: bool) void { // deleteRange (not deleteChar): the cursor may sit ON a '\n' // cell, where a delete joins the lines (helix 1-wide selection) const d = modal.deleteRange(p.gpa, eb.text, c, c) catch return; - setEditText(p, pane, d.content); + setEditText(p, t, d.content); p.gpa.free(d.deleted); const llen = modal.lineSlice(d.content, c.row).len; - pane.cur_col = @min(pane.cur_col, @as(i32, @intCast(llen))); + t.cur_col = @min(t.cur_col, @as(i32, @intCast(llen))); } } -pub fn normalYank(p: *Pardes, pane: *Pane) void { - pane.select = false; +pub fn normalYank(p: *Pardes, t: *Text) void { + const pane = t.pane(); + t.select = false; if (pane.rawPointerText(pane.sel[sel_slot])) |text| { setYank(p, text); return; } - if (pane.vsel.active) { - setYank(p, vselText(p, pane)); + if (t.vsel.active) { + setYank(p, vselText(p, t)); return; } - if (pane.msel.active) { - setYank(p, yankRows(p, pane, @min(pane.msel.r0, pane.msel.r1), @max(pane.msel.r0, pane.msel.r1))); + if (t.msel.active) { + setYank(p, yankRows(p, t, @min(t.msel.r0, t.msel.r1), @max(t.msel.r0, t.msel.r1))); } else { - const save = pane.vsel; - pane.vsel = .{ .active = true, .row = pane.cur_row, .col = pane.cur_col, .explicit = false }; - setYank(p, vselText(p, pane)); - pane.vsel = save; + const save = t.vsel; + t.vsel = .{ .active = true, .row = t.cur_row, .col = t.cur_col, .explicit = false }; + setYank(p, vselText(p, t)); + t.vsel = save; } } -pub fn pasteText(p: *Pardes, pane: *Pane, y0: []const u8, before: bool, count: usize) void { +pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usize) void { if (y0.len == 0) return; - pushUndo(p, pane); - pane.select = false; - pane.sticky_col = -1; + pushUndo(p, t); + t.select = false; + t.sticky_col = -1; const arena = p.scratch.allocator(); var y: []const u8 = y0; if (count > 1) { @@ -820,11 +832,11 @@ pub fn pasteText(p: *Pardes, pane: *Pane, y0: []const u8, before: bool, count: u for (0..count) |i| @memcpy(buf[i * y0.len ..][0..y0.len], y0); y = buf; } - const b: Bounds = if (pane.vsel.active) - vselBounds(pane) + const b: Bounds = if (t.vsel.active) + vselBounds(t) else - .{ .lo_row = pane.cur_row, .lo_col = pane.cur_col, .hi_row = pane.cur_row, .hi_col = pane.cur_col }; - const eb = editText(p, pane, b.lo_row, b.hi_row, -1) orelse return; + .{ .lo_row = t.cur_row, .lo_col = t.cur_col, .hi_row = t.cur_row, .hi_col = t.cur_col }; + const eb = editText(p, t, b.lo_row, b.hi_row, -1) orelse return; const row0 = eb.row0; if (y[y.len - 1] == '\n') { const block_text = y[0 .. y.len - 1]; @@ -834,17 +846,17 @@ pub fn pasteText(p: *Pardes, pane: *Pane, y0: []const u8, before: bool, count: u const row: usize = @intCast(@max(0, b.lo_row - row0)); const block = std.fmt.allocPrint(arena, "{s}\n", .{block_text}) catch return; out = modal.insertAt(p.gpa, eb.text, .{ .row = row, .col = 0 }, block) catch return; - pane.cur_row = @as(i32, @intCast(row + n - 1)) + row0; + t.cur_row = @as(i32, @intCast(row + n - 1)) + row0; } else { const row: usize = @intCast(@max(0, b.hi_row - row0)); out = modal.pasteLineBelow(p.gpa, eb.text, row, block_text) catch return; - pane.cur_row = @as(i32, @intCast(row + n)) + row0; + t.cur_row = @as(i32, @intCast(row + n)) + row0; } - setEditText(p, pane, out); - pane.vsel = .{ .active = true, .row = pane.cur_row - @as(i32, @intCast(n - 1)), .col = 0, .explicit = false }; + setEditText(p, t, out); + t.vsel = .{ .active = true, .row = t.cur_row - @as(i32, @intCast(n - 1)), .col = 0, .explicit = false }; // cursor ON the last pasted line's '\n' (helix) - const llen = modal.lineSlice(out, @intCast(@max(0, pane.cur_row - row0))).len; - pane.cur_col = @intCast(llen); + const llen = modal.lineSlice(out, @intCast(@max(0, t.cur_row - row0))).len; + t.cur_col = @intCast(llen); } else { const at: modal.Cursor = if (before) .{ .row = @intCast(@max(0, b.lo_row - row0)), .col = @intCast(@max(0, b.lo_col)) } @@ -857,34 +869,35 @@ pub fn pasteText(p: *Pardes, pane: *Pane, y0: []const u8, before: bool, count: u break :blk .{ .row = hrow, .col = gcol }; }; const out = modal.insertAt(p.gpa, eb.text, at, y) catch return; - setEditText(p, pane, out); - pane.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @as(i32, @intCast(at.row)) + row0, .col = @intCast(at.col), .explicit = false }; + setEditText(p, t, out); + t.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @as(i32, @intCast(at.row)) + row0, .col = @intCast(at.col), .explicit = false }; const end = modal.advanceBy(at, y); if (end.col > 0) { - pane.cur_row = @as(i32, @intCast(end.row)) + row0; - pane.cur_col = @intCast(modal.prevGrapheme(modal.lineSlice(out, end.row), end.col)); + t.cur_row = @as(i32, @intCast(end.row)) + row0; + t.cur_col = @intCast(modal.prevGrapheme(modal.lineSlice(out, end.row), end.col)); } else { - pane.cur_row = @as(i32, @intCast(end.row -| 1)) + row0; - pane.cur_col = @intCast(modal.lineSlice(out, end.row -| 1).len); + t.cur_row = @as(i32, @intCast(end.row -| 1)) + row0; + t.cur_col = @intCast(modal.lineSlice(out, end.row -| 1).len); } } - pane.msel.active = false; - pane.cur_pinned = true; - pane.ensureCursorVisible(); + t.msel.active = false; + t.cur_pinned = true; + t.pane().ensureCursorVisible(); } -pub fn normalChange(p: *Pardes, pane: *Pane) void { - pane.select = false; - pane.sticky_col = -1; - if (pane.vsel.active) { - const b = vselBounds(pane); - const eb = editTextEol(p, pane, b) orelse return; +pub fn normalChange(p: *Pardes, t: *Text) void { + const pane = t.pane(); + t.select = false; + t.sticky_col = -1; + if (t.vsel.active) { + const b = vselBounds(t); + const eb = editTextEol(p, t, b) orelse return; const hi_len = modal.lineSlice(eb.text, @intCast(@max(0, b.hi_row - eb.row0))).len; if (b.lo_col == 0 and @as(usize, @intCast(@max(0, b.hi_col))) >= hi_len) { - setYank(p, vselText(p, pane)); - pushUndo(p, pane); + setYank(p, vselText(p, t)); + pushUndo(p, t); const d = modal.deleteLines(p.gpa, eb.text, @intCast(@max(0, b.lo_row - eb.row0)), @intCast(@max(0, b.hi_row - eb.row0))) catch return; - setEditText(p, pane, d.content); + setEditText(p, t, d.content); p.gpa.free(d.deleted); const n = modal.lineCount(d.content); const row: usize = @min(@as(usize, @intCast(@max(0, b.lo_row - eb.row0))), if (n == 0) 0 else n - 1); @@ -892,37 +905,37 @@ pub fn normalChange(p: *Pardes, pane: *Pane) void { const arena = p.scratch.allocator(); const block = std.fmt.allocPrint(arena, "{s}\n", .{ind}) catch return; const new = modal.insertAt(p.gpa, d.content, .{ .row = row, .col = 0 }, block) catch return; - setEditText(p, pane, new); - pane.cur_row = @as(i32, @intCast(row)) + eb.row0; - pane.cur_col = @intCast(ind.len); - pane.vsel.active = false; - pane.msel.active = false; - pane.cur_pinned = true; - pane.mode = .insert; - pane.normal.clear(); + setEditText(p, t, new); + t.cur_row = @as(i32, @intCast(row)) + eb.row0; + t.cur_col = @intCast(ind.len); + t.vsel.active = false; + t.msel.active = false; + t.cur_pinned = true; + t.mode = .insert; + t.normal.clear(); pane.ensureCursorVisible(); return; } - setYank(p, vselText(p, pane)); - pushUndo(p, pane); + setYank(p, vselText(p, t)); + pushUndo(p, t); const d = modal.deleteRange(p.gpa, eb.text, .{ .row = @intCast(@max(0, b.lo_row - eb.row0)), .col = @intCast(@max(0, b.lo_col)) }, .{ .row = @intCast(@max(0, b.hi_row - eb.row0)), .col = @intCast(@max(0, b.hi_col)) }) catch { - pane.vsel.active = false; + t.vsel.active = false; return; }; - setEditText(p, pane, d.content); + setEditText(p, t, d.content); p.gpa.free(d.deleted); - pane.cur_row = b.lo_row; - pane.cur_col = b.lo_col; - pane.clampCursor(d.content, eb.row0); - pane.mode = .insert; - pane.normal.clear(); + t.cur_row = b.lo_row; + t.cur_col = b.lo_col; + t.clampCursor(d.content, eb.row0); + t.mode = .insert; + t.normal.clear(); return; } - if (pane.msel.active) { - const r0 = @min(pane.msel.r0, pane.msel.r1); - const r1 = @max(pane.msel.r0, pane.msel.r1); - pushUndo(p, pane); - const eb = editText(p, pane, r0, r1 + 1, -1) orelse return; + if (t.msel.active) { + const r0 = @min(t.msel.r0, t.msel.r1); + const r1 = @max(t.msel.r0, t.msel.r1); + pushUndo(p, t); + const eb = editText(p, t, r0, r1 + 1, -1) orelse return; const arena = p.scratch.allocator(); const lo: usize = @intCast(@max(0, r0 - eb.row0)); const hi: usize = @intCast(@max(0, r1 - eb.row0)); @@ -943,77 +956,77 @@ pub fn normalChange(p: *Pardes, pane: *Pane) void { var body: []u8 = eb.text; if (hi > lo) { const d = modal.deleteLines(p.gpa, body, lo + 1, hi) catch { - pane.msel.active = false; + t.msel.active = false; return; }; - setEditText(p, pane, d.content); + setEditText(p, t, d.content); p.gpa.free(d.deleted); body = d.content; } const cl = modal.clearLine(p.gpa, body, lo) catch { - pane.msel.active = false; + t.msel.active = false; return; }; - setEditText(p, pane, cl); - pane.cur_row = r0; - pane.cur_col = 0; - pane.msel.active = false; - pane.cur_pinned = true; - pane.mode = .insert; - pane.normal.clear(); + setEditText(p, t, cl); + t.cur_row = r0; + t.cur_col = 0; + t.msel.active = false; + t.cur_pinned = true; + t.mode = .insert; + t.normal.clear(); pane.ensureCursorVisible(); } else { - pushUndo(p, pane); - const eb = editTextEol(p, pane, .{ .lo_row = pane.cur_row, .lo_col = pane.cur_col, .hi_row = pane.cur_row, .hi_col = pane.cur_col }) orelse return; - const c = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) }; + pushUndo(p, t); + const eb = editTextEol(p, t, .{ .lo_row = t.cur_row, .lo_col = t.cur_col, .hi_row = t.cur_row, .hi_col = t.cur_col }) orelse return; + const c = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - eb.row0)), .col = @intCast(@max(0, t.cur_col)) }; const arena = p.scratch.allocator(); setYank(p, modal.rangeText(arena, eb.text, c, c) catch return); const d = modal.deleteRange(p.gpa, eb.text, c, c) catch return; - setEditText(p, pane, d.content); + setEditText(p, t, d.content); p.gpa.free(d.deleted); const llen = modal.lineSlice(d.content, c.row).len; - pane.cur_col = @min(pane.cur_col, @as(i32, @intCast(llen))); - pane.mode = .insert; - pane.normal.clear(); + t.cur_col = @min(t.cur_col, @as(i32, @intCast(llen))); + t.mode = .insert; + t.normal.clear(); } } -fn selRange(pane: *Pane, content: []const u8, row0: i32) modal.Range { - if (pane.vsel.active) { - const b = vselBounds(pane); +fn selRange(t: *Text, content: []const u8, row0: i32) modal.Range { + if (t.vsel.active) { + const b = vselBounds(t); return .{ .a = .{ .row = @intCast(@max(0, b.lo_row - row0)), .col = @intCast(@max(0, b.lo_col)) }, .b = .{ .row = @intCast(@max(0, b.hi_row - row0)), .col = @intCast(@max(0, b.hi_col)) }, }; } - if (pane.msel.active) { - const r0: usize = @intCast(@max(0, @min(pane.msel.r0, pane.msel.r1) - row0)); - const r1: usize = @intCast(@max(0, @max(pane.msel.r0, pane.msel.r1) - row0)); + if (t.msel.active) { + const r0: usize = @intCast(@max(0, @min(t.msel.r0, t.msel.r1) - row0)); + const r1: usize = @intCast(@max(0, @max(t.msel.r0, t.msel.r1) - row0)); const llen = modal.lineSlice(content, r1).len; return .{ .a = .{ .row = r0, .col = 0 }, .b = .{ .row = r1, .col = if (llen == 0) 0 else modal.prevGrapheme(modal.lineSlice(content, r1), llen) } }; } - const c = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row - row0)), .col = @intCast(@max(0, pane.cur_col)) }; + const c = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - row0)), .col = @intCast(@max(0, t.cur_col)) }; return .{ .a = c, .b = c }; } /// the rows an op's selection spans, absolute (what editText must cover) -fn selRows(pane: *Pane) Bounds { - if (pane.vsel.active) return vselBounds(pane); - if (pane.msel.active) return .{ - .lo_row = @min(pane.msel.r0, pane.msel.r1), +fn selRows(t: *Text) Bounds { + if (t.vsel.active) return vselBounds(t); + if (t.msel.active) return .{ + .lo_row = @min(t.msel.r0, t.msel.r1), .lo_col = 0, - .hi_row = @max(pane.msel.r0, pane.msel.r1), + .hi_row = @max(t.msel.r0, t.msel.r1), .hi_col = 0, }; - return .{ .lo_row = pane.cur_row, .lo_col = pane.cur_col, .hi_row = pane.cur_row, .hi_col = pane.cur_col }; + return .{ .lo_row = t.cur_row, .lo_col = t.cur_col, .hi_row = t.cur_row, .hi_col = t.cur_col }; } /// `r`: overwrite the selection (or the cursor char) with ch — /// newlines included (helix), so `xrz` joins the selected lines -pub fn normalReplaceChar(p: *Pardes, pane: *Pane, ch: u21) void { - pane.select = false; - const eb = editTextEol(p, pane, selRows(pane)) orelse return; - const before = pane.primaryRange(eb.text, eb.row0); +pub fn normalReplaceChar(p: *Pardes, t: *Text, ch: u21) void { + t.select = false; + const eb = editTextEol(p, t, selRows(t)) orelse return; + const before = t.primaryRange(eb.text, eb.row0); const lo = @min(before.anchor, before.head); const hi = @max(before.anchor, before.head); var graphemes: usize = 0; @@ -1021,59 +1034,59 @@ pub fn normalReplaceChar(p: *Pardes, pane: *Pane, ch: u21) void { while (at < hi) : (graphemes += 1) at = modal.nextGrapheme(eb.text, at); var encoded: [4]u8 = undefined; const encoded_len = std.unicode.utf8Encode(ch, &encoded) catch return; - const r = selRange(pane, eb.text, eb.row0); - pushUndo(p, pane); + const r = selRange(t, eb.text, eb.row0); + pushUndo(p, t); const new = modal.replaceChars(p.gpa, eb.text, r.a, r.b, ch) catch return; - setEditText(p, pane, new); + setEditText(p, t, new); const end = lo + graphemes * encoded_len; const mapped: modal.Selection = if (before.head < before.anchor) .{ .anchor = end, .head = lo } else .{ .anchor = lo, .head = end }; - pane.setRange(new, eb.row0, mapped, pane.vsel.explicit); + t.setRange(new, eb.row0, mapped, t.vsel.explicit); } /// `R`: replace the selection (or the cursor char) with the DEFAULT /// register. `SPC R` is the same verb over the system clipboard. -pub fn normalReplaceYank(p: *Pardes, pane: *Pane) void { - replaceWithText(p, pane, p.yank orelse return); +pub fn normalReplaceYank(p: *Pardes, t: *Text) void { + replaceWithText(p, t, p.yank orelse return); } /// The pasted text becomes the selection, head on its last char (which for /// a trailing-newline `y` is the '\n' cell of the last full line). -fn replaceWithText(p: *Pardes, pane: *Pane, y: []const u8) void { +fn replaceWithText(p: *Pardes, t: *Text, y: []const u8) void { if (y.len == 0) return; - pane.select = false; - const eb = editTextEol(p, pane, selRows(pane)) orelse return; - const r = selRange(pane, eb.text, eb.row0); - pushUndo(p, pane); + t.select = false; + const eb = editTextEol(p, t, selRows(t)) orelse return; + const r = selRange(t, eb.text, eb.row0); + pushUndo(p, t); const new = modal.replaceRange(p.gpa, eb.text, r.a, r.b, y) catch return; - setEditText(p, pane, new); - pane.msel.active = false; - pane.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @as(i32, @intCast(r.a.row)) + eb.row0, .col = @intCast(r.a.col), .explicit = false }; + setEditText(p, t, new); + t.msel.active = false; + t.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @as(i32, @intCast(r.a.row)) + eb.row0, .col = @intCast(r.a.col), .explicit = false }; const end = modal.advanceBy(r.a, y); if (end.col > 0) { - pane.cur_row = @as(i32, @intCast(end.row)) + eb.row0; - pane.cur_col = @intCast(modal.prevGrapheme(modal.lineSlice(new, end.row), end.col)); + t.cur_row = @as(i32, @intCast(end.row)) + eb.row0; + t.cur_col = @intCast(modal.prevGrapheme(modal.lineSlice(new, end.row), end.col)); } else { // the yank ended in '\n': the cursor lands ON that newline - pane.cur_row = @as(i32, @intCast(end.row -| 1)) + eb.row0; - pane.cur_col = @intCast(modal.lineSlice(new, end.row -| 1).len); + t.cur_row = @as(i32, @intCast(end.row -| 1)) + eb.row0; + t.cur_col = @intCast(modal.lineSlice(new, end.row -| 1).len); } - pane.cur_pinned = true; - pane.sticky_col = -1; - pane.ensureCursorVisible(); + t.cur_pinned = true; + t.sticky_col = -1; + t.pane().ensureCursorVisible(); } /// `~` / `` ` `` / ``Alt-` ``: case-map the selection (or the cursor char), /// keeping the selection (helix) -pub fn normalCase(p: *Pardes, pane: *Pane, op: modal.CaseOp) void { - pane.select = false; - const eb = editTextEol(p, pane, selRows(pane)) orelse return; - const r = selRange(pane, eb.text, eb.row0); - pushUndo(p, pane); +pub fn normalCase(p: *Pardes, t: *Text, op: modal.CaseOp) void { + t.select = false; + const eb = editTextEol(p, t, selRows(t)) orelse return; + const r = selRange(t, eb.text, eb.row0); + pushUndo(p, t); const new = modal.changeCase(p.gpa, eb.text, r.a, r.b, op) catch return; - setEditText(p, pane, new); + setEditText(p, t, new); } /// a change to apply to file content: delete [from, to), insert `ins` at @@ -1115,14 +1128,14 @@ fn applyChanges(p: *Pardes, text: []const u8, chs: []const TextChange) ![]u8 { return out; } -pub fn normalJoin(p: *Pardes, pane: *Pane) void { +pub fn normalJoin(p: *Pardes, t: *Text) void { // a join always eats the newline of its last line, so the buffer has // to reach one row PAST the selection - const sr = selRows(pane); - const eb = editText(p, pane, sr.lo_row, sr.hi_row + 1, -1) orelse return; + const sr = selRows(t); + const eb = editText(p, t, sr.lo_row, sr.hi_row + 1, -1) orelse return; const text = eb.text; - const range = pane.primaryRange(text, eb.row0); - const span = Pane.rangeLineSpan(text, range); + const range = t.primaryRange(text, eb.row0); + const span = Text.rangeLineSpan(text, range); const nlines = modal.cursorLineCount(text); var end = span.end; if (span.start == end) end = @min(end + 1, nlines - 1); @@ -1140,37 +1153,37 @@ pub fn normalJoin(p: *Pardes, pane: *Pane) void { chs_len += 1; } if (chs_len == 0) return; - pushUndo(p, pane); - const cur_off = modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) }); - const anc_off = if (pane.vsel.active) - modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.vsel.row - eb.row0)), .col = @intCast(@max(0, pane.vsel.col)) }) + pushUndo(p, t); + const cur_off = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.cur_row - eb.row0)), .col = @intCast(@max(0, t.cur_col)) }); + const anc_off = if (t.vsel.active) + modal.offsetAt(text, .{ .row = @intCast(@max(0, t.vsel.row - eb.row0)), .col = @intCast(@max(0, t.vsel.col)) }) else cur_off; const new = applyChanges(p, text, chs[0..chs_len]) catch return; const nc = mapThroughChanges(chs[0..chs_len], cur_off); const na = mapThroughChanges(chs[0..chs_len], anc_off); - setEditText(p, pane, new); + setEditText(p, t, new); const cc = modal.positionAt(new, nc); const ac = modal.positionAt(new, na); - pane.cur_row = @as(i32, @intCast(cc.row)) + eb.row0; - pane.cur_col = @intCast(cc.col); - if (pane.vsel.active) { - pane.vsel.row = @as(i32, @intCast(ac.row)) + eb.row0; - pane.vsel.col = @intCast(ac.col); + t.cur_row = @as(i32, @intCast(cc.row)) + eb.row0; + t.cur_col = @intCast(cc.col); + if (t.vsel.active) { + t.vsel.row = @as(i32, @intCast(ac.row)) + eb.row0; + t.vsel.col = @intCast(ac.col); } - pane.msel.active = false; - pane.cur_pinned = true; - pane.sticky_col = -1; - pane.ensureCursorVisible(); + t.msel.active = false; + t.cur_pinned = true; + t.sticky_col = -1; + t.pane().ensureCursorVisible(); } -pub fn normalIndent(p: *Pardes, pane: *Pane, cnt: usize, add: bool) void { - pane.select = false; - const sr = selRows(pane); - const eb = editText(p, pane, sr.lo_row, sr.hi_row, -1) orelse return; +pub fn normalIndent(p: *Pardes, t: *Text, cnt: usize, add: bool) void { + t.select = false; + const sr = selRows(t); + const eb = editText(p, t, sr.lo_row, sr.hi_row, -1) orelse return; const text = eb.text; - const range = pane.primaryRange(text, eb.row0); - const span = Pane.rangeLineSpan(text, range); + const range = t.primaryRange(text, eb.row0); + const span = Text.rangeLineSpan(text, range); const arena = p.scratch.allocator(); // one run of spaces, sliced per line: `>` never inserts more than this const pad = arena.alloc(u8, modal.INDENT_W * cnt) catch return; @@ -1208,45 +1221,45 @@ pub fn normalIndent(p: *Pardes, pane: *Pane, cnt: usize, add: bool) void { } } if (chs_len == 0) return; - pushUndo(p, pane); - const cur_off = modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.cur_row - eb.row0)), .col = @intCast(@max(0, pane.cur_col)) }); - const anc_off = if (pane.vsel.active) - modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.vsel.row - eb.row0)), .col = @intCast(@max(0, pane.vsel.col)) }) + pushUndo(p, t); + const cur_off = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.cur_row - eb.row0)), .col = @intCast(@max(0, t.cur_col)) }); + const anc_off = if (t.vsel.active) + modal.offsetAt(text, .{ .row = @intCast(@max(0, t.vsel.row - eb.row0)), .col = @intCast(@max(0, t.vsel.col)) }) else cur_off; const new = applyChanges(p, text, chs[0..chs_len]) catch return; const nc = mapThroughChanges(chs[0..chs_len], cur_off); const na = mapThroughChanges(chs[0..chs_len], anc_off); - setEditText(p, pane, new); + setEditText(p, t, new); const cc = modal.positionAt(new, nc); const ac = modal.positionAt(new, na); - pane.cur_row = @as(i32, @intCast(cc.row)) + eb.row0; - pane.cur_col = @intCast(cc.col); - if (pane.vsel.active) { - pane.vsel.row = @as(i32, @intCast(ac.row)) + eb.row0; - pane.vsel.col = @intCast(ac.col); + t.cur_row = @as(i32, @intCast(cc.row)) + eb.row0; + t.cur_col = @intCast(cc.col); + if (t.vsel.active) { + t.vsel.row = @as(i32, @intCast(ac.row)) + eb.row0; + t.vsel.col = @intCast(ac.col); } - pane.msel.active = false; - pane.cur_pinned = true; - pane.sticky_col = -1; - pane.ensureCursorVisible(); + t.msel.active = false; + t.cur_pinned = true; + t.sticky_col = -1; + t.pane().ensureCursorVisible(); } -pub fn normalToggleComment(p: *Pardes, pane: *Pane) void { - const expl = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active; - pane.select = false; // helix exit_select_mode +pub fn normalToggleComment(p: *Pardes, t: *Text) void { + const expl = (t.vsel.active and t.vsel.explicit) or t.msel.active; + t.select = false; // helix exit_select_mode // the buffer must cover every cursor's rows, not just the primary's - var b = selRows(pane); - for (pane.sels[0..pane.nsel]) |s| { + var b = selRows(t); + for (t.sels[0..t.nsel]) |s| { b.lo_row = @min(b.lo_row, @min(s.row, s.arow)); b.hi_row = @max(b.hi_row, @max(s.row, s.arow)); } - const surface = flatSurface(p, pane) catch return; - const last_row = @as(i32, @intCast(panes.File.textLineCount(pane, surface))) - 1; - const eb = editText(p, pane, b.lo_row, @min(b.hi_row + 1, last_row), -1) orelse return; + const surface = flatSurface(p, t) catch return; + const last_row = @as(i32, @intCast(panes.File.textLineCount(t, surface))) - 1; + const eb = editText(p, t, b.lo_row, @min(b.hi_row + 1, last_row), -1) orelse return; const text = eb.text; - var rs: [Pane.max_selections]modal.Selection = undefined; - const got = pane.ranges(text, eb.row0, &rs); + var rs: [Text.max_selections]modal.Selection = undefined; + const got = t.ranges(text, eb.row0, &rs); const nlines = modal.cursorLineCount(text); const arena = p.scratch.allocator(); // the lines the ranges cover, each ONE ONCE and in order (helix's @@ -1255,7 +1268,7 @@ pub fn normalToggleComment(p: *Pardes, pane: *Pane) void { var lines_len: usize = 0; var next: usize = 0; for (rs[0..got.n]) |r| { - const span = Pane.rangeLineSpan(text, r); + const span = Text.rangeLineSpan(text, r); var l = @max(span.start, next); const end = @min(span.end + 1, nlines); while (l < end) : (l += 1) { @@ -1264,7 +1277,7 @@ pub fn normalToggleComment(p: *Pardes, pane: *Pane) void { } next = @max(next, end); } - const ext = if (pane.file) |f| std.fs.path.extension(f.path) else ""; + const ext = if (t.pane().file) |f| std.fs.path.extension(f.path) else ""; var token: []const u8 = config.comment_token_default; lang: for (config.comment_tokens) |row| { for (row.exts) |e| if (std.ascii.eqlIgnoreCase(ext, e)) { @@ -1303,13 +1316,13 @@ pub fn normalToggleComment(p: *Pardes, pane: *Pane) void { .{ .from = at, .to = at, .ins = ins }; chs_len += 1; } - pushUndo(p, pane); + pushUndo(p, t); // one edit, and the WHOLE selection rides through it (helix maps the // selection with the transaction) - var cells: [Pane.max_selections]Pane.SelRange = undefined; + var cells: [Text.max_selections]Text.SelRange = undefined; const new = applyChanges(p, text, chs[0..chs_len]) catch return; for (rs[0..got.n], 0..) |r, i| { - const c = Pane.rangeCells(new, .{ + const c = Text.rangeCells(new, .{ .anchor = mapThroughChanges(chs[0..chs_len], r.anchor), .head = mapThroughChanges(chs[0..chs_len], r.head), }); @@ -1322,53 +1335,53 @@ pub fn normalToggleComment(p: *Pardes, pane: *Pane) void { .acol = @intCast(ac.col), }; } - setEditText(p, pane, new); - const t2 = flatSurface(p, pane) catch return; - for (cells[0..got.n], 0..) |s, i| rs[i] = Pane.cellRange(t2, s.arow, s.acol, s.row, s.col); - pane.setRanges(t2, rs[0..got.n], &.{}, got.pri, expl); + setEditText(p, t, new); + const t2 = flatSurface(p, t) catch return; + for (cells[0..got.n], 0..) |s, i| rs[i] = Text.cellRange(t2, s.arow, s.acol, s.row, s.col); + t.setRanges(t2, rs[0..got.n], &.{}, got.pri, expl); } -pub fn normalAdjustNumber(p: *Pardes, pane: *Pane, delta: i64) void { - const eb = editTextEol(p, pane, selRows(pane)) orelse return; - const r = selRange(pane, eb.text, eb.row0); +pub fn normalAdjustNumber(p: *Pardes, t: *Text, delta: i64) void { + const eb = editTextEol(p, t, selRows(t)) orelse return; + const r = selRange(t, eb.text, eb.row0); const arena = p.scratch.allocator(); const frag = modal.rangeText(arena, eb.text, r.a, r.b) catch return; const rep = (modal.incrementDecimal(arena, frag, delta) catch null) orelse return; - pushUndo(p, pane); - pane.select = false; + pushUndo(p, t); + t.select = false; const new = modal.replaceRange(p.gpa, eb.text, r.a, r.b, rep) catch return; - setEditText(p, pane, new); + setEditText(p, t, new); const start = modal.lineStartOffset(new, r.a.row) + r.a.col; const cc = modal.positionAt(new, modal.prevGrapheme(new, start + rep.len)); - pane.vsel = .{ .active = modal.nextGrapheme(rep, 0) < rep.len, .row = @as(i32, @intCast(r.a.row)) + eb.row0, .col = @intCast(r.a.col), .explicit = false }; - pane.msel.active = false; - pane.cur_row = @as(i32, @intCast(cc.row)) + eb.row0; - pane.cur_col = @intCast(cc.col); - pane.cur_pinned = true; - pane.sticky_col = -1; - pane.ensureCursorVisible(); + t.vsel = .{ .active = modal.nextGrapheme(rep, 0) < rep.len, .row = @as(i32, @intCast(r.a.row)) + eb.row0, .col = @intCast(r.a.col), .explicit = false }; + t.msel.active = false; + t.cur_row = @as(i32, @intCast(cc.row)) + eb.row0; + t.cur_col = @intCast(cc.col); + t.cur_pinned = true; + t.sticky_col = -1; + t.pane().ensureCursorVisible(); } /// `]Space` / `[Space`: add blank lines below/above, the cursor staying /// on its text line (the selection rides along) -pub fn addNewline(p: *Pardes, pane: *Pane, below: bool, cnt: usize) void { - const eb = editText(p, pane, pane.cur_row, pane.cur_row, -1) orelse return; - pushUndo(p, pane); - const row: usize = @intCast(@max(0, pane.cur_row - eb.row0)); +pub fn addNewline(p: *Pardes, t: *Text, below: bool, cnt: usize) void { + const eb = editText(p, t, t.cur_row, t.cur_row, -1) orelse return; + pushUndo(p, t); + const row: usize = @intCast(@max(0, t.cur_row - eb.row0)); const arena = p.scratch.allocator(); const nl = arena.alloc(u8, cnt) catch return; @memset(nl, '\n'); const llen = modal.lineSlice(eb.text, row).len; const new = modal.insertAt(p.gpa, eb.text, .{ .row = row, .col = if (below) llen else 0 }, nl) catch return; - setEditText(p, pane, new); + setEditText(p, t, new); if (!below) { - pane.cur_row += @intCast(cnt); // the line moved down; stay on it - if (pane.vsel.active and pane.vsel.row >= @as(i32, @intCast(row))) pane.vsel.row += @intCast(cnt); - } else if (pane.vsel.active and pane.vsel.row > @as(i32, @intCast(row))) { - pane.vsel.row += @intCast(cnt); + t.cur_row += @intCast(cnt); // the line moved down; stay on it + if (t.vsel.active and t.vsel.row >= @as(i32, @intCast(row))) t.vsel.row += @intCast(cnt); + } else if (t.vsel.active and t.vsel.row > @as(i32, @intCast(row))) { + t.vsel.row += @intCast(cnt); } - pane.cur_pinned = true; - pane.ensureCursorVisible(); + t.cur_pinned = true; + t.pane().ensureCursorVisible(); } /// pair mapping for m-mode: either bracket names the pair; anything else @@ -1383,20 +1396,20 @@ fn pairFor(ch: u21) ?struct { o: u8, c: u8 } { }; } -pub fn textobjectSelect(p: *Pardes, pane: *Pane, text: []const u8, obj: u21, around: bool) void { - const range = pane.primaryRange(text, 0); +pub fn textobjectSelect(p: *Pardes, t: *Text, text: []const u8, obj: u21, around: bool) void { + const range = t.primaryRange(text, 0); switch (obj) { 'w', 'W' => { const r = modal.selectWord(text, range, around, obj == 'W'); - return pane.setRange(text, 0, r, false); + return t.setRange(text, 0, r, false); }, 'p' => { const r = modal.selectParagraph(text, range, around, 1); - return pane.setRange(text, 0, r, false); + return t.setRange(text, 0, r, false); }, else => {}, } - const lines = paneCursorLines(p, pane) catch return; + const lines = paneCursorLines(p, t) catch return; const cur = modal.positionAt(text, modal.selectionCursor(text, range)); const pair: ?modal.Range = switch (obj) { '\'', '"', '`' => modal.enclosingQuote(lines, cur, @intCast(obj)), @@ -1415,102 +1428,105 @@ pub fn textobjectSelect(p: *Pardes, pane: *Pane, text: []const u8, obj: u21, aro a = modal.nextGrapheme(text, a); head = modal.prevGrapheme(text, head); } - pane.setRange(text, 0, .{ .anchor = a, .head = head }, false); + t.setRange(text, 0, .{ .anchor = a, .head = head }, false); } /// `ms`: wrap the selection (or the cursor char) in a pair; the wrap /// including the pair becomes the selection -pub fn surroundAdd(p: *Pardes, pane: *Pane, ch: u21) void { +pub fn surroundAdd(p: *Pardes, t: *Text, ch: u21) void { const pr = pairFor(ch) orelse return; - pane.select = false; - const eb = editTextEol(p, pane, selRows(pane)) orelse return; - const r = selRange(pane, eb.text, eb.row0); - pushUndo(p, pane); + t.select = false; + const eb = editTextEol(p, t, selRows(t)) orelse return; + const r = selRange(t, eb.text, eb.row0); + pushUndo(p, t); const close_col = modal.nextGrapheme(modal.lineSlice(eb.text, r.b.row), r.b.col); var new = modal.insertAt(p.gpa, eb.text, .{ .row = r.b.row, .col = close_col }, &[1]u8{pr.c}) catch return; - setEditText(p, pane, new); + setEditText(p, t, new); new = modal.insertAt(p.gpa, new, .{ .row = r.a.row, .col = r.a.col }, &[1]u8{pr.o}) catch return; - setEditText(p, pane, new); - pane.msel.active = false; - pane.vsel = .{ .active = true, .row = @as(i32, @intCast(r.a.row)) + eb.row0, .col = @intCast(r.a.col), .explicit = false }; - pane.cur_row = @as(i32, @intCast(r.b.row)) + eb.row0; - pane.cur_col = @intCast(close_col + @as(usize, if (r.a.row == r.b.row) 1 else 0)); - pane.cur_pinned = true; - pane.sticky_col = -1; - pane.ensureCursorVisible(); + setEditText(p, t, new); + t.msel.active = false; + t.vsel = .{ .active = true, .row = @as(i32, @intCast(r.a.row)) + eb.row0, .col = @intCast(r.a.col), .explicit = false }; + t.cur_row = @as(i32, @intCast(r.b.row)) + eb.row0; + t.cur_col = @intCast(close_col + @as(usize, if (r.a.row == r.b.row) 1 else 0)); + t.cur_pinned = true; + t.sticky_col = -1; + t.pane().ensureCursorVisible(); } /// `md`: delete the enclosing pair's chars; the cursor maps through -pub fn surroundDelete(p: *Pardes, pane: *Pane, ch: u21) void { +pub fn surroundDelete(p: *Pardes, t: *Text, ch: u21) void { const pr = pairFor(ch) orelse return; - const lines = paneCursorLines(p, pane) catch return; - const cur = pane.toModalCursor(); + const lines = paneCursorLines(p, t) catch return; + const cur = t.toModalCursor(); const r = (if (pr.o == pr.c) modal.enclosingQuote(lines, cur, pr.o) else modal.enclosingPair(lines, cur, pr.o, pr.c)) orelse return; const lo: i32 = @intCast(@min(r.a.row, cur.row)); const hi: i32 = @intCast(@max(r.b.row, cur.row)); - const eb = editText(p, pane, lo, hi, -1) orelse return; + const eb = editText(p, t, lo, hi, -1) orelse return; const text = eb.text; const drow = -eb.row0; // surface row -> buffer row const ra: modal.Cursor = .{ .row = @intCast(@as(i32, @intCast(r.a.row)) + drow), .col = r.a.col }; const rb: modal.Cursor = .{ .row = @intCast(@as(i32, @intCast(r.b.row)) + drow), .col = r.b.col }; - pushUndo(p, pane); + pushUndo(p, t); const a_off = modal.offsetAt(text, ra); const b_off = modal.offsetAt(text, rb); const cur_off = modal.offsetAt(text, .{ .row = @intCast(@as(i32, @intCast(cur.row)) + drow), .col = cur.col }); // the close first, so the open's position stays valid var new = modal.deleteChar(p.gpa, text, rb) catch return; - setEditText(p, pane, new); + setEditText(p, t, new); new = modal.deleteChar(p.gpa, new, ra) catch return; - setEditText(p, pane, new); + setEditText(p, t, new); var nc = cur_off; if (nc > b_off) nc -= 1; if (nc > a_off) nc -= 1; const cc = modal.positionAt(new, nc); - pane.cur_row = @as(i32, @intCast(cc.row)) + eb.row0; - pane.cur_col = @intCast(cc.col); - pane.vsel.active = false; - pane.msel.active = false; - pane.cur_pinned = true; - pane.ensureCursorVisible(); + t.cur_row = @as(i32, @intCast(cc.row)) + eb.row0; + t.cur_col = @intCast(cc.col); + t.vsel.active = false; + t.msel.active = false; + t.cur_pinned = true; + t.pane().ensureCursorVisible(); } /// `mr`: swap the enclosing pair's chars for 's -pub fn surroundReplace(p: *Pardes, pane: *Pane, from: u21, to: u21) void { +pub fn surroundReplace(p: *Pardes, t: *Text, from: u21, to: u21) void { const fp = pairFor(from) orelse return; const tp = pairFor(to) orelse return; - const lines = paneCursorLines(p, pane) catch return; - const cur = pane.toModalCursor(); + const lines = paneCursorLines(p, t) catch return; + const cur = t.toModalCursor(); const r = (if (fp.o == fp.c) modal.enclosingQuote(lines, cur, fp.o) else modal.enclosingPair(lines, cur, fp.o, fp.c)) orelse return; - const eb = editText(p, pane, @as(i32, @intCast(r.a.row)), @as(i32, @intCast(r.b.row)), -1) orelse return; + const eb = editText(p, t, @as(i32, @intCast(r.a.row)), @as(i32, @intCast(r.b.row)), -1) orelse return; const drow = -eb.row0; // surface row -> buffer row const ar: usize = @intCast(@as(i32, @intCast(r.a.row)) + drow); const br: usize = @intCast(@as(i32, @intCast(r.b.row)) + drow); - pushUndo(p, pane); + pushUndo(p, t); const out = p.gpa.dupe(u8, eb.text) catch return; out[modal.lineStartOffset(out, ar) + r.a.col] = tp.o; out[modal.lineStartOffset(out, br) + r.b.col] = tp.c; - setEditText(p, pane, out); + setEditText(p, t, out); } -pub fn pushUndo(p: *Pardes, pane: *Pane) void { +pub fn pushUndo(p: *Pardes, t: *Text) void { + const pane = t.pane(); // one keystroke, one undo step — even when it edited at ten cursors. if (p.multi_on and !p.multi_first) return; if (pane.file != null) return panes.File.pushUndo(p, pane); panes.Terminal.pushUndo(p, pane); } -pub fn doUndo(p: *Pardes, pane: *Pane) void { +pub fn doUndo(p: *Pardes, t: *Text) void { + const pane = t.pane(); if (pane.file != null) return panes.File.undo(p, pane); panes.Terminal.undo(p, pane); } -pub fn doRedo(p: *Pardes, pane: *Pane) void { +pub fn doRedo(p: *Pardes, t: *Text) void { + const pane = t.pane(); if (pane.file != null) return panes.File.redo(p, pane); panes.Terminal.redo(p, pane); } @@ -1564,14 +1580,14 @@ test "insert newline adds one indent level after a closing call" { defer p.deinit(); while (p.nextEffect()) |_| {} const pane = try p.setTestFile(" callback({})\n"); - pane.mode = .insert; - pane.cur_col = 16; + pane.body.mode = .insert; + pane.body.cur_col = 16; p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expectEqualSlices(u8, " callback({})\n \n", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 1), pane.cur_row); - try std.testing.expectEqual(@as(i32, 8), pane.cur_col); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, 8), pane.body.cur_col); } test "insert and normal modes edit complete Unicode graphemes" { @@ -1580,41 +1596,41 @@ test "insert and normal modes edit complete Unicode graphemes" { defer p.deinit(); const pane = try p.setTestFile("a" ++ "e\u{301}" ++ "👩🏽\u{200d}🚀" ++ "界" ++ "z"); - pane.mode = .insert; - pane.cur_col = 22; // on z, after the CJK grapheme - insertKey(p, pane, .{ .cp = Key.left }); - try std.testing.expectEqual(@as(i32, 19), pane.cur_col); - insertKey(p, pane, .{ .cp = Key.left }); - try std.testing.expectEqual(@as(i32, 4), pane.cur_col); - insertKey(p, pane, .{ .cp = Key.right }); - try std.testing.expectEqual(@as(i32, 19), pane.cur_col); - insertKey(p, pane, .{ .cp = Key.backspace }); + pane.body.mode = .insert; + pane.body.cur_col = 22; // on z, after the CJK grapheme + insertKey(p, &pane.body, .{ .cp = Key.left }); + try std.testing.expectEqual(@as(i32, 19), pane.body.cur_col); + insertKey(p, &pane.body, .{ .cp = Key.left }); + try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col); + insertKey(p, &pane.body, .{ .cp = Key.right }); + try std.testing.expectEqual(@as(i32, 19), pane.body.cur_col); + insertKey(p, &pane.body, .{ .cp = Key.backspace }); try std.testing.expectEqualStrings("ae\u{301}界z", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 4), pane.cur_col); + try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col); - pane.mode = .normal; - pane.cur_col = 1; - normalDelete(p, pane, false); + pane.body.mode = .normal; + pane.body.cur_col = 1; + normalDelete(p, &pane.body, false); try std.testing.expectEqualStrings("a界z", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 1), pane.cur_col); - normalReplaceChar(p, pane, 'λ'); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); + normalReplaceChar(p, &pane.body, 'λ'); try std.testing.expectEqualStrings("aλz", pane.file.?.content); panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "界a")); - pane.cur_col = 3; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; - normalReplaceChar(p, pane, 'λ'); + pane.body.cur_col = 3; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + normalReplaceChar(p, &pane.body, 'λ'); try std.testing.expectEqualStrings("λλ", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 2), pane.cur_col); - try std.testing.expectEqual(@as(i32, 0), pane.vsel.col); + try std.testing.expectEqual(@as(i32, 2), pane.body.cur_col); + try std.testing.expectEqual(@as(i32, 0), pane.body.vsel.col); panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "界a")); - pane.cur_col = 0; - pane.vsel = .{ .active = true, .row = 0, .col = 3, .explicit = true }; - normalReplaceChar(p, pane, 'λ'); + pane.body.cur_col = 0; + pane.body.vsel = .{ .active = true, .row = 0, .col = 3, .explicit = true }; + normalReplaceChar(p, &pane.body, 'λ'); try std.testing.expectEqualStrings("λλ", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 0), pane.cur_col); - try std.testing.expectEqual(@as(i32, 2), pane.vsel.col); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_col); + try std.testing.expectEqual(@as(i32, 2), pane.body.vsel.col); } test "flat text replacement preserves a terminal fragment origin and direction" { @@ -1622,23 +1638,23 @@ test "flat text replacement preserves a terminal fragment origin and direction" defer p.deinit(); p.update(.{ .output = .{ .pane = 0, .bytes = "first\r\nsecond\r\nthird\r\n界a\r\n" } }); const pane = p.panes[0].?; - pane.mode = .normal; - pane.cur_pinned = true; - pane.cur_row = 3; - pane.cur_col = 0; - pane.vsel = .{ .active = true, .row = 3, .col = 3, .explicit = true }; - normalReplaceChar(p, pane, 'λ'); + pane.body.mode = .normal; + pane.body.cur_pinned = true; + pane.body.cur_row = 3; + pane.body.cur_col = 0; + pane.body.vsel = .{ .active = true, .row = 3, .col = 3, .explicit = true }; + normalReplaceChar(p, &pane.body, 'λ'); try std.testing.expectEqual(@as(i32, 3), pane.ovl.?.row); try std.testing.expectEqualStrings("λλ", pane.ovl.?.text); - try std.testing.expectEqual(@as(i32, 3), pane.cur_row); - try std.testing.expectEqual(@as(i32, 0), pane.cur_col); - try std.testing.expectEqual(@as(i32, 3), pane.vsel.row); - try std.testing.expectEqual(@as(i32, 2), pane.vsel.col); - try std.testing.expect(pane.vsel.active and pane.vsel.explicit); - const lines = try paneCursorLines(p, pane); + try std.testing.expectEqual(@as(i32, 3), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_col); + try std.testing.expectEqual(@as(i32, 3), pane.body.vsel.row); + try std.testing.expectEqual(@as(i32, 2), pane.body.vsel.col); + try std.testing.expect(pane.body.vsel.active and pane.body.vsel.explicit); + const lines = try paneCursorLines(p, &pane.body); try std.testing.expectEqualStrings("first", lines[0]); try std.testing.expectEqualStrings("λλ", lines[3]); - const flat = try flatSurface(p, pane); + const flat = try flatSurface(p, &pane.body); try std.testing.expect(std.mem.startsWith(u8, flat, "first\nsecond\nthird\nλλ\n")); } diff --git a/src/exec.zig b/src/exec.zig index 75d07441..0a9d6f31 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -38,13 +38,13 @@ pub fn takesCommandLine(p: *const Pardes, id: usize) bool { } pub fn chordEachSel(p: *Pardes, pane: *Pane, cmd: Builtin) bool { - if (pane.nsel == 0) return false; - const text = edit.flatSurface(p, pane) catch return false; - var ranges: [Pane.max_selections]modal.Selection = undefined; - const got = pane.ranges(text, 0, &ranges); + if (pane.body.nsel == 0) return false; + const text = edit.flatSurface(p, &pane.body) catch return false; + var ranges: [panes.Text.max_selections]modal.Selection = undefined; + const got = pane.body.ranges(text, 0, &ranges); if (got.n < 2) return false; - var texts: [Pane.max_selections][]u8 = undefined; + var texts: [panes.Text.max_selections][]u8 = undefined; var made: usize = 0; defer for (texts[0..made]) |t| p.gpa.free(t); for (ranges[0..got.n]) |range| { @@ -59,10 +59,10 @@ pub fn chordEachSel(p: *Pardes, pane: *Pane, cmd: Builtin) bool { const id = p.active; const serial = pane.serial; - pane.vsel.active = false; - pane.msel.active = false; - pane.select = false; - pane.nsel = 0; // the chord consumed them, exactly as it consumes one + pane.body.vsel.active = false; + pane.body.msel.active = false; + pane.body.select = false; + pane.body.nsel = 0; // the chord consumed them, exactly as it consumes one var primary_active: ?usize = null; for (texts[0..made], 0..) |txt, i| { @@ -96,7 +96,7 @@ pub const PointerOperand = struct { pub fn pointerOperand(p: *Pardes, pane: *Pane, clicked: Pane.Sel) PointerOperand { const visible = clicked.r0 - @as(i32, BOX_H); const wrapped = pane.wrapAt(visible); - const raw = pane.isTerminal() and pane.mode == .tty and clicked.r0 >= BOX_H; + const raw = pane.isTerminal() and pane.body.mode == .tty and clicked.r0 >= BOX_H; const row = if (raw) panes.Terminal.gridOffset(pane) + visible else wrapped.line; const raw_line = if (raw) modal.lineSlice(body_layer.bodyText(p, p.scratch.allocator(), pane) catch "", @intCast(@max(0, visible))) else ""; const col = if (raw) @@ -104,7 +104,7 @@ pub fn pointerOperand(p: *Pardes, pane: *Pane, clicked: Pane.Sel) PointerOperand else if (clicked.r0 >= BOX_H) edit.paneByteAtDisplay( p, - pane, + &pane.body, wrapped.line, wrapped.at, clicked.c0 - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0), @@ -143,14 +143,14 @@ pub fn pointerOperand(p: *Pardes, pane: *Pane, clicked: Pane.Sel) PointerOperand result.preview = kept; return result; } - if (pane.vsel.active and pane.vsel.explicit and - edit.spanHas(row, col, pane.vsel.row, pane.vsel.col, pane.cur_row, pane.cur_col)) + if (pane.body.vsel.active and pane.body.vsel.explicit and + edit.spanHas(row, col, pane.body.vsel.row, pane.body.vsel.col, pane.body.cur_row, pane.body.cur_col)) { result.text = edit.currentSelText(p, pane); return result; } - if (pane.msel.active and row >= @min(pane.msel.r0, pane.msel.r1) and - row <= @max(pane.msel.r0, pane.msel.r1)) + if (pane.body.msel.active and row >= @min(pane.body.msel.r0, pane.body.msel.r1) and + row <= @max(pane.body.msel.r0, pane.body.msel.r1)) { result.text = edit.currentSelText(p, pane); return result; @@ -202,7 +202,7 @@ pub fn heldSelection(p: *Pardes, first: usize) ?[]const u8 { }; if (t.sel[sel_slot].state == .done) { if (edit.selectionText(p, t, t.sel[sel_slot]) catch null) |tx| return tx; - } else if ((t.vsel.active and t.vsel.explicit) or t.msel.active) { + } else if ((t.body.vsel.active and t.body.vsel.explicit) or t.body.msel.active) { if (edit.currentSelText(p, t)) |tx| return tx; } } @@ -302,7 +302,7 @@ fn spawnTtyWithMount(p: *Pardes, from: usize, v9fs: bool) void { const nt = p.newShell(free, Pardes.paneDir(src)) catch return; nt.greet = !v9fs; nt.v9fs_on_spawn = v9fs; - nt.mode = .tty; + nt.body.mode = .tty; const parent = layout.splitParent(p, from); const f = layout.findPane(p, parent).?; layout.insert(p, f.col, f.idx + 1, free); @@ -558,8 +558,8 @@ test "the acme chords act once per selection, not once on the primary" { .{ .anchor = 0, .head = 6 }, .{ .anchor = 7, .head = 13 }, }; - pane.setRanges(pane.file.?.content, &ranges, &.{}, 0, true); - try std.testing.expectEqual(@as(u8, 1), pane.nsel); + pane.body.setRanges(pane.file.?.content, &ranges, &.{}, 0, true); + try std.testing.expectEqual(@as(u8, 1), pane.body.nsel); const before = p.ncol; p.update(.{ .key = .{ .cp = Key.tab } }); // config.exec_key: Exec @@ -567,5 +567,5 @@ test "the acme chords act once per selection, not once on the primary" { // other cursor, so one keystroke over two cursors made one column. try std.testing.expectEqual(before + 2, p.ncol); // ...and the chord consumed the selection exactly as it does with one. - try std.testing.expectEqual(@as(u8, 0), p.panes[0].?.nsel); + try std.testing.expectEqual(@as(u8, 0), p.panes[0].?.body.nsel); } diff --git a/src/gui/gui.zig b/src/gui/gui.zig index a11b22c7..97bbc816 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1399,7 +1399,7 @@ test "GUI completion failure survives backlog and leaves the document unchanged" const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); const pane = try core.setTestFile("abc"); - pane.cur_col = 1; + pane.body.cur_col = 1; core.lspRequest(core.active, .completion, ""); const id = core.lsp_wait.?.id; var workers: LspWorkers = .{}; @@ -1426,7 +1426,7 @@ test "GUI completion failure survives backlog and leaves the document unchanged" shell.drainQueue(); try std.testing.expect(core.lsp_wait == null); try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 1), pane.cur_col); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); try std.testing.expect(shell.saw_event); } @@ -1611,7 +1611,7 @@ test "GUI LSP worker limit rejects before allocation and recovers after owned wo const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); const pane = try core.setTestFile("abc"); - pane.cur_col = 1; + pane.body.cur_col = 1; var workers: LspWorkers = .{}; var gate: std.Io.Event = .unset; var threads: [LspWorkers.capacity]?std.Thread = @splat(null); @@ -1650,7 +1650,7 @@ test "GUI LSP worker limit rejects before allocation and recovers after owned wo }); try std.testing.expect(core.lsp_wait == null); try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 1), pane.cur_col); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "WorkersBusy") != null); try std.testing.expectEqual(@as(usize, 0), failing.alloc_index); try std.testing.expect(!failing.has_induced_failure); @@ -1762,8 +1762,8 @@ test "GUI worker setup failures finish matching LSP and pipe requests" { try std.testing.expect(core.lsp_wait == null); try std.testing.expectEqualStrings("abc", pane.file.?.content); - pane.cur_col = 2; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + pane.body.cur_col = 2; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; core.update(.{ .key = .{ .cp = '|' } }); core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); core.update(.{ .key = .{ .cp = pardes.Key.enter } }); @@ -3870,7 +3870,7 @@ const Shell = struct { s.closePty(e.pane); if (e.failure) |err| { if (s.core.panes[e.pane]) |pane| { - pane.mode = .normal; + pane.body.mode = .normal; s.core.reportError(e.pane, "terminal reader", err); } } else s.core.update(.{ .eof = .{ .pane = e.pane } }); diff --git a/src/host_io.zig b/src/host_io.zig index d0b9de71..959ce3bd 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -322,7 +322,7 @@ pub const Lsp = struct { const path = try gpa.dupe(u8, "/file.zig"); gpa.free(pane.file.?.path); pane.file.?.path = path; - pane.cur_col = 6; + pane.body.cur_col = 6; const revision = pane.file.?.revision; const undo_len = pane.file.?.history.undo_len; var failing = std.testing.FailingAllocator.init(gpa, .{}); diff --git a/src/layout.zig b/src/layout.zig index 3d8932a8..49da0207 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -704,7 +704,7 @@ pub fn focusDir(p: *Pardes, from: usize, dir: enum { left, right, up, down }) vo if (best) |b| { p.active = b; // a count typed before the hop was meant for the pane you left - p.panes[b].?.normal.clear(); + p.panes[b].?.body.normal.clear(); } } diff --git a/src/look.zig b/src/look.zig index 1534d332..efc3f312 100644 --- a/src/look.zig +++ b/src/look.zig @@ -482,15 +482,15 @@ pub fn expandedSel(p: *Pardes, pane: *Pane, at: Pane.Sel) ?Pane.Sel { /// the word under the modal cursor as a pane-local selection (paneText /// coords: row 0 is the tag; file panes carry the line-number prefix) pub fn cursorWordSel(p: *Pardes, pane: *Pane) Pane.Sel { - const w = pane.wrapRow(pane.cur_row, pane.cur_col); + const w = pane.wrapRow(pane.body.cur_row, pane.body.cur_col); const vrow = w.row + @as(i32, BOX_H); const vcol = if (pane.file != null) - panes.File.displayOffset(pane, pane.cur_row, w.at, pane.cur_col) + @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayOffset(pane, pane.body.cur_row, w.at, pane.body.cur_col) + @as(i32, panes.File.gutterWidth(pane)) else blk: { - const lines = edit.paneCursorLines(p, pane) catch break :blk pane.cur_col; - const local = pane.cur_row; - if (local < 0 or @as(usize, @intCast(local)) >= lines.len) break :blk pane.cur_col; - break :blk panes.File.lineDisplayOffset(lines[@intCast(local)], @intCast(@max(0, w.at)), @intCast(@max(0, pane.cur_col))); + const lines = edit.paneCursorLines(p, &pane.body) catch break :blk pane.body.cur_col; + const local = pane.body.cur_row; + if (local < 0 or @as(usize, @intCast(local)) >= lines.len) break :blk pane.body.cur_col; + break :blk panes.File.lineDisplayOffset(lines[@intCast(local)], @intCast(@max(0, w.at)), @intCast(@max(0, pane.body.cur_col))); }; return .{ .state = .done, .c0 = vcol, .c1 = vcol, .r0 = vrow, .r1 = vrow }; } @@ -526,9 +526,9 @@ fn lookFirstHit(p: *Pardes, id: usize) void { if (p.active != rid) return; // walked out of the list; leave it there const txt = edit.currentSelText(p, rp) orelse return; // spent, exactly as the look chord spends it (handleKey) - rp.vsel.active = false; - rp.msel.active = false; - rp.select = false; + rp.body.vsel.active = false; + rp.body.msel.active = false; + rp.body.select = false; exec.runBuiltin(p, config.look_cmd, rid, "", txt); } @@ -587,7 +587,7 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start anchor = found.anchor; } } else { - const lines = try edit.paneCursorLines(p, pane); + const lines = try edit.paneCursorLines(p, &pane.body); // a real file names itself; a terminal or an output buffer has no path const has_path = if (pane.file) |f| f.output == null else false; var idbuf: [16]u8 = undefined; @@ -597,8 +597,8 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start std.fs.path.basename(pane.file.?.path) else std.fmt.bufPrint(&idbuf, config.pane_addr ++ "{d}", .{id}) catch return error.PathTooLong; - const cl: usize = @intCast(@max(0, pane.cur_row)); - const cc: usize = @intCast(@max(0, pane.cur_col)); + const cl: usize = @intCast(@max(0, pane.body.cur_row)); + const cc: usize = @intCast(@max(0, pane.body.cur_col)); for (lines, 0..) |ln, i| { const at = std.ascii.indexOfIgnoreCase(ln, pat) orelse continue; const row = try std.fmt.allocPrint(arena, "{s}:{d}:{d}{c}{d} {s}\n", .{ @@ -656,11 +656,11 @@ pub fn jumpResult(p: *Pardes, id: usize, row: usize) bool { if (ln.len == 0) return false; const r: i32 = @intCast(row); pane.search_row = row; - rp.msel = .{ .active = true, .r0 = r, .r1 = r }; - rp.vsel.active = false; - rp.nsel = 0; - rp.cur_row = r; - rp.cur_pinned = true; + rp.body.msel = .{ .active = true, .r0 = r, .r1 = r }; + rp.body.vsel.active = false; + rp.body.nsel = 0; + rp.body.cur_row = r; + rp.body.cur_pinned = true; const off = rp.scroll(); const last = off + @as(i32, rp.rows) - 1; if (r < off) rp.scrollBy(r - off) else if (r > last) rp.scrollBy(r - last); @@ -676,14 +676,14 @@ pub fn jumpResult(p: *Pardes, id: usize, row: usize) bool { null; }; if (span) |selected| { - rp.cur_col = @intCast(selected.start); + rp.body.cur_col = @intCast(selected.start); rp.look_at = .{ .row = r, .col0 = @intCast(selected.start), .col1 = @intCast(selected.end - 1), }; } else { - rp.cur_col = 0; + rp.body.cur_col = 0; rp.look_at = null; } if (tr.commands) { @@ -692,7 +692,7 @@ pub fn jumpResult(p: *Pardes, id: usize, row: usize) bool { lookAt(p, rid, ln[selected.start..selected.end]); // This is the newly visited result, not a selection carried into // the destination. Look cleared the previous source selection. - rp.msel = .{ .active = true, .r0 = r, .r1 = r }; + rp.body.msel = .{ .active = true, .r0 = r, .r1 = r }; } armLookWalk(p, rid); return true; @@ -705,9 +705,9 @@ fn lookEdge(delta: i32) LookFrom { } fn lookStand(pane: *Pane) LookFrom { - if (pane.look_at) |s| if (s.row == pane.cur_row and s.col0 == pane.cur_col) + if (pane.look_at) |s| if (s.row == pane.body.cur_row and s.col0 == pane.body.cur_col) return .{ .row = s.row, .col = s.col0, .strict = true }; - return .{ .row = pane.cur_row, .col = pane.cur_col }; + return .{ .row = pane.body.cur_row, .col = pane.body.cur_col }; } fn lookWalkPanes(p: *Pardes, out: *[MAX_PANES]usize) []const usize { @@ -759,7 +759,7 @@ fn wholeRowSpan(ln: []const u8) ?Span { } fn lookSpanIn(p: *Pardes, pane: *Pane, from: LookFrom, delta: i32, budget: *usize) ?Pane.LookSpot { - const lines = edit.paneCursorLines(p, pane) catch return null; + const lines = edit.paneCursorLines(p, &pane.body) catch return null; const nrows: i32 = @intCast(lines.len); if (nrows == 0) return null; const grain: panes.Output.Grain = if (pane.file) |*f| panes.Output.grain(f.output) else .word; @@ -835,13 +835,13 @@ pub fn lookWalk(p: *Pardes, delta: i32) void { } fn landLookSpot(p: *Pardes, id: usize, pane: *Pane, spot: Pane.LookSpot) void { - edit.pinPaneCursor(p, pane); // fresh out of tty mode the cursor still tracks the shell - pane.vsel = .{ .active = true, .row = spot.row, .col = spot.col1, .explicit = true }; - pane.msel.active = false; - pane.nsel = 0; - pane.cur_row = spot.row; - pane.cur_col = spot.col0; - pane.cur_pinned = true; + edit.pinPaneCursor(p, &pane.body); // fresh out of tty mode the cursor still tracks the shell + pane.body.vsel = .{ .active = true, .row = spot.row, .col = spot.col1, .explicit = true }; + pane.body.msel.active = false; + pane.body.nsel = 0; + pane.body.cur_row = spot.row; + pane.body.cur_col = spot.col0; + pane.body.cur_pinned = true; pane.look_at = spot; p.look_walk_owner = pane.serial; p.active = id; @@ -944,7 +944,7 @@ pub fn focusPaneLine(p: *Pardes, id: usize, at: Spot, landing: enum { center, ke if (id >= MAX_PANES) return; const pane = p.panes[id] orelse return; p.active = id; - pane.normal.clear(); + pane.body.normal.clear(); if (pane.hasPdf()) { if (landing == .keep) return; if (comptime pdf_enabled) { @@ -964,21 +964,21 @@ pub fn focusPaneLine(p: *Pardes, id: usize, at: Spot, landing: enum { center, ke } } } - pane.cur_row = @intCast(at.line - 1); - pane.cur_col = if (at.col > 0) @intCast(at.col - 1) else 0; - pane.cur_pinned = true; + pane.body.cur_row = @intCast(at.line - 1); + pane.body.cur_col = if (at.col > 0) @intCast(at.col - 1) else 0; + pane.body.cur_pinned = true; if (at.end_line != 0) return selectSpan(p, pane, at); pane.ensureCursorVisible(); } fn selectSpan(p: *Pardes, pane: *Pane, at: Spot) void { - const text = edit.flatSurface(p, pane) catch return; + const text = edit.flatSurface(p, &pane.body) catch return; // saturating, not `- 1`: `f.zig:0-5` is a legal thing to type and a // 1-based zero is the same nothing an absent number is const acol: i32 = @intCast(at.col -| 1); const ecol: i32 = if (at.end_col > 0) @intCast(at.end_col - 1) else std.math.maxInt(i32); - const r = Pane.cellRange(text, @intCast(at.line -| 1), acol, @intCast(at.end_line -| 1), ecol); - pane.setRange(text, 0, r, true); + const r = panes.Text.cellRange(text, @intCast(at.line -| 1), acol, @intCast(at.end_line -| 1), ecol); + pane.body.setRange(text, 0, r, true); } fn openPaneTarget(p: *const Pardes, path: []const u8, at: Spot) ?Target { @@ -1006,13 +1006,13 @@ fn focusPaneByPath(p: *Pardes, path: []const u8, at: Spot) bool { /// Navigation starts a new selection at the destination. pub fn clearNavigationSelection(p: *Pardes, pane: *Pane) void { - pane.vsel = .{}; - pane.msel = .{}; - pane.nsel = 0; - pane.select = false; - pane.normal.clear(); - pane.append_at = null; - pane.sticky_col = -1; + pane.body.vsel = .{}; + pane.body.msel = .{}; + pane.body.nsel = 0; + pane.body.select = false; + pane.body.normal.clear(); + pane.body.append_at = null; + pane.body.sticky_col = -1; for (0..pane.sel.len) |slot| pane.clearPointerSelection(slot); pane.sel = @splat(.{}); if (comptime pdf_enabled) if (pane.pdf) |*state| { @@ -1150,7 +1150,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand: []const u8) void { const found = resolveLookTarget(p, id, txt, &realbuf); switch (found) { .none => { - const bmode = if (pane.tag_edit) pane.tag_mode else pane.mode; + const bmode = if (pane.tag_edit) pane.tag_mode else pane.body.mode; if (pane.image != null or bmode == .tty) return; runSearch(p, id, trimmed, .text, .cursor) catch |err| { p.reportError(id, "search", err); @@ -1203,7 +1203,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand: []const u8) void { const free = p.freeSlot() orelse return p.reportError(id, "look", error.NoPaneSlots); const nt = panes.File.open(p, free, target.path, target.at.line) catch |err| return p.reportError(id, "look", err); - if (target.at.col > 0) nt.cur_col = @intCast(target.at.col - 1); + if (target.at.col > 0) nt.body.cur_col = @intCast(target.at.col - 1); exec.placeDoc(p, id, free, nt); layout.compute(p); nt.file.?.scroll -|= @max(1, p.rects[free].h -| BOX_H) / 2; @@ -1249,7 +1249,7 @@ test "Look hover waits without mutating the pane and input cancels it" { const selections_before = pane.sel; const active_before = p.active; - const cursor_before = .{ pane.cur_row, pane.cur_col }; + const cursor_before = .{ pane.body.cur_row, pane.body.cur_col }; const jumps_before = .{ p.njumps, p.jcur, p.n_look_src }; const effects_before = p.effects_len; @@ -1276,7 +1276,7 @@ test "Look hover waits without mutating the pane and input cancels it" { // Resolving and displaying the operand is observational only. try std.testing.expect(std.meta.eql(selections_before, pane.sel)); try std.testing.expectEqual(active_before, p.active); - try std.testing.expectEqual(cursor_before, .{ pane.cur_row, pane.cur_col }); + try std.testing.expectEqual(cursor_before, .{ pane.body.cur_row, pane.body.cur_col }); try std.testing.expectEqual(jumps_before, .{ p.njumps, p.jcur, p.n_look_src }); try std.testing.expectEqual(effects_before, p.effects_len); @@ -1436,8 +1436,8 @@ test "Look copies its operand before releasing pointer selection storage" { }; p.drag = .{ .select = .{ .id = 0, .button = config.select_button } }; lookAt(p, 0, operand); - try std.testing.expectEqual(@as(i32, 2), pane.cur_row); - try std.testing.expectEqual(@as(i32, 1), pane.cur_col); + try std.testing.expectEqual(@as(i32, 2), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); try std.testing.expect(pane.pointer_selections[0] == null); try std.testing.expectEqual(.none, pane.sel[0].state); try std.testing.expectEqual(.none, p.drag); @@ -1448,10 +1448,10 @@ test "Look ignores missing and out of bounds pane addresses" { defer p.deinit(); const pane = try p.setTestFile("alpha\nbravo\n"); for ([_][]const u8{ config.pane_addr ++ "15:2", config.pane_addr ++ "999999:2" }) |operand| { - pane.setRange(pane.file.?.content, 0, .{ .anchor = 0, .head = 3 }, true); + pane.body.setRange(pane.file.?.content, 0, .{ .anchor = 0, .head = 3 }, true); lookAt(p, 0, operand); try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expectEqual(@as(i32, 0), pane.cur_row); - try std.testing.expect(!pane.vsel.active); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); + try std.testing.expect(!pane.body.vsel.active); } } diff --git a/src/macos.zig b/src/macos.zig index ccbb5dd5..c9c83a2d 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -338,8 +338,8 @@ test "mac worker setup failures finish matching LSP and pipe requests" { try std.testing.expect(core.lsp_wait == null); try std.testing.expectEqualStrings("abc", pane.file.?.content); - pane.cur_col = 2; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + pane.body.cur_col = 2; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; core.update(.{ .key = .{ .cp = '|' } }); core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); core.update(.{ .key = .{ .cp = pardes.Key.enter } }); @@ -1465,8 +1465,8 @@ test "mac Restore keeps host state and rejects callbacks from the old core" { try std.testing.expect(st.core.lsp_wait == null); const pane = st.core.panes[0].?; - pane.cur_col = 4; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + pane.body.cur_col = 4; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; st.core.update(.{ .key = .{ .cp = '|' } }); st.core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); st.core.update(.{ .key = .{ .cp = pardes.Key.enter } }); diff --git a/src/mouse.zig b/src/mouse.zig index 2a00bded..a840c8fc 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -378,7 +378,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { // next cursor move or left wheel pulls it back } else if (pane.file != null and !p.settings.wrap) { // wrapped there is nothing off to the right to reach - const line = panes.File.sourceLine(pane, pane.cur_row); + const line = panes.File.sourceLine(pane, pane.body.cur_row); const visual = panes.File.rawDisplayCol(line, @intCast(@max(0, pane.hscroll))); const next: usize = if (m.button == .wheel_right) visual +| @as(usize, @intCast(config.wheel_cols)) @@ -682,7 +682,7 @@ fn gestureRange(p: *Pardes, id: usize, text: []const u8, on_tag: bool, operand: const top = @min(sel.r0, sel.r1) - @as(i32, BOX_H); if (top < 0) break :lead null; const w = pane.wrapAt(top); - const col = edit.paneByteAtDisplay(p, pane, w.line, w.at, @min(sel.c0, sel.c1) - panes.File.gutterWidth(pane)); + const col = edit.paneByteAtDisplay(p, &pane.body, w.line, w.at, @min(sel.c0, sel.c1) - panes.File.gutterWidth(pane)); break :lead .{ .row = @intCast(@max(0, w.line)), .col = @intCast(@max(0, col)), @@ -720,22 +720,22 @@ fn mirrorTtySelection(p: *Pardes, pane: *Pane) void { const body = body_layer.bodyText(p, p.scratch.allocator(), pane) catch return; const line = modal.lineSlice(body, @intCast(@max(0, endpoint.row - panes.Terminal.gridOffset(pane)))); const byte = if (gesture.c1 >= gesture.c0) modal.prevGrapheme(line, @min(endpoint.hi, line.len)) else endpoint.lo; - pane.cur_row = pane.surfRow(endpoint.row); + pane.body.cur_row = pane.surfRow(endpoint.row); var shown = std.mem.trimEnd(u8, line[@min(endpoint.prompt_bytes, line.len)..], " \t"); if (pane.ovl) |overlay| { - const relative = pane.cur_row - overlay.row; + const relative = pane.body.cur_row - overlay.row; if (relative >= 0 and relative < modal.lineCount(overlay.text)) shown = modal.lineSlice(overlay.text, @intCast(relative)); } - pane.cur_col = @intCast(modal.graphemeStart(shown, @min(shown.len, byte -| endpoint.prompt_bytes))); - pane.cur_pinned = true; - pane.msel.active = false; - pane.vsel.active = false; - pane.nsel = 0; - pane.select = false; - pane.append_at = null; - pane.sticky_col = -1; - pane.normal.clear(); + pane.body.cur_col = @intCast(modal.graphemeStart(shown, @min(shown.len, byte -| endpoint.prompt_bytes))); + pane.body.cur_pinned = true; + pane.body.msel.active = false; + pane.body.vsel.active = false; + pane.body.nsel = 0; + pane.body.select = false; + pane.body.append_at = null; + pane.body.sticky_col = -1; + pane.body.normal.clear(); edit.setYank(p, text); } @@ -813,27 +813,27 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { const dragged = sl.c0 != sl.c1 or sl.r0 != sl.r1; if (!dragged) pane.sel[sel_slot].state = .none; if (dragged) edit.capturePointerSelection(p, pane, sel_slot) catch {}; - if (dragged and pane.mode == .tty) mirrorTtySelection(p, pane); + if (dragged and pane.body.mode == .tty) mirrorTtySelection(p, pane); const body_vis = sl.r1 - @as(i32, BOX_H); - if (body_vis >= 0 and pane.mode != .tty) { + if (body_vis >= 0 and pane.body.mode != .tty) { const w = pane.wrapAt(body_vis); - pane.cur_row = w.line; - pane.cur_col = edit.paneByteAtDisplay( + pane.body.cur_row = w.line; + pane.body.cur_col = edit.paneByteAtDisplay( p, - pane, + &pane.body, w.line, w.at, sl.c1 - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0), ); - pane.cur_pinned = true; - if (edit.clampFileCursor(pane)) pane.ensureCursorVisible(); - pane.msel.active = false; - pane.normal.clear(); - pane.vsel.active = false; - pane.nsel = 0; // a click says WHERE the one cursor is - pane.select = false; - pane.append_at = null; - pane.sticky_col = -1; + pane.body.cur_pinned = true; + if (edit.clampFileCursor(&pane.body)) pane.ensureCursorVisible(); + pane.body.msel.active = false; + pane.body.normal.clear(); + pane.body.vsel.active = false; + pane.body.nsel = 0; // a click says WHERE the one cursor is + pane.body.select = false; + pane.body.append_at = null; + pane.body.sticky_col = -1; if (s.ctrl) p.lspRequest(s.id, .definition, ""); } } else { @@ -842,7 +842,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { // this file -- a sticky context header's number included, // since the row map holds each header's own source line. if (s.button == config.look_button and clk.r0 >= BOX_H and clk.r0 == clk.r1 and - clk.c0 == clk.c1 and clk.c0 >= 0 and pane.mode != .tty) + clk.c0 == clk.c1 and clk.c0 >= 0 and pane.body.mode != .tty) if (pane.file) |f| if (f.output == null and clk.c0 < panes.File.gutterWidth(pane)) { const line = pane.wrapAt(clk.r0 - BOX_H).line; if (line >= 0) { @@ -858,10 +858,10 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { pane.sel[b] = expanded else if (operand.text == null) pane.sel[b].state = .none; - if (s.button == config.look_button and clk.r0 >= BOX_H and pane.mode != .tty) { - pane.cur_row = operand.row; - pane.cur_col = operand.col; - if (edit.clampFileCursor(pane)) pane.ensureCursorVisible(); + if (s.button == config.look_button and clk.r0 >= BOX_H and pane.body.mode != .tty) { + pane.body.cur_row = operand.row; + pane.body.cur_col = operand.col; + if (edit.clampFileCursor(&pane.body)) pane.ensureCursorVisible(); } const txt = operand.text; const cmd = if (s.button == config.look_button) config.look_cmd else config.exec_cmd; @@ -909,7 +909,7 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { if (cut and pv.selection_text.len > 0) edit.setYank(p, pv.selection_text); return; }; - if (pane.mode == .tty) { + if (pane.body.mode == .tty) { if (!s.chorded) { s.chorded = true; pane.sel[sel_slot].state = .none; // drop the sweep highlight @@ -944,44 +944,44 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { const w1 = pane.wrapAt(@max(0, sl.r1 - @as(i32, BOX_H))); const row0 = w0.line; const row1 = w1.line; - const col0 = edit.paneByteAtDisplay(p, pane, w0.line, w0.at, sl.c0 - pfx); - const col1 = edit.paneByteAtDisplay(p, pane, w1.line, w1.at, sl.c1 - pfx); - pane.cur_row = row1; - pane.cur_col = col1; - pane.cur_pinned = true; - pane.msel.active = false; - pane.normal.clear(); - if (!pane.isTerminal()) pane.mode = .normal; - pane.vsel = .{ .active = row0 != row1 or col0 != col1, .row = row0, .col = col0, .explicit = false }; - pane.nsel = 0; + const col0 = edit.paneByteAtDisplay(p, &pane.body, w0.line, w0.at, sl.c0 - pfx); + const col1 = edit.paneByteAtDisplay(p, &pane.body, w1.line, w1.at, sl.c1 - pfx); + pane.body.cur_row = row1; + pane.body.cur_col = col1; + pane.body.cur_pinned = true; + pane.body.msel.active = false; + pane.body.normal.clear(); + if (!pane.isTerminal()) pane.body.mode = .normal; + pane.body.vsel = .{ .active = row0 != row1 or col0 != col1, .row = row0, .col = col0, .explicit = false }; + pane.body.nsel = 0; } if (cut) { - if (pane.vsel.active) edit.normalDelete(p, pane, true); - } else if (pane.vsel.active) { - edit.normalReplaceYank(p, pane); + if (pane.body.vsel.active) edit.normalDelete(p, &pane.body, true); + } else if (pane.body.vsel.active) { + edit.normalReplaceYank(p, &pane.body); } else if (pane.file) |*f| { // bare cursor: splice the register in literally (no linewise // magic) so a paste right after a cut restores the text exactly const y = p.yank orelse return; if (y.len == 0) return; - const at = modal.Cursor{ .row = @intCast(@max(0, pane.cur_row)), .col = @intCast(@max(0, pane.cur_col)) }; - edit.pushUndo(p, pane); + const at = modal.Cursor{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)) }; + edit.pushUndo(p, &pane.body); const new = modal.insertAt(p.gpa, f.content, at, y) catch return; panes.File.setContent(p, f, new); - pane.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @intCast(at.row), .col = @intCast(at.col), .explicit = false }; + pane.body.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @intCast(at.row), .col = @intCast(at.col), .explicit = false }; const end = modal.advanceBy(at, y); if (end.col > 0) { - pane.cur_row = @intCast(end.row); - pane.cur_col = @intCast(modal.prevGrapheme(modal.lineSlice(f.content, end.row), end.col)); + pane.body.cur_row = @intCast(end.row); + pane.body.cur_col = @intCast(modal.prevGrapheme(modal.lineSlice(f.content, end.row), end.col)); } else { // the register ended in '\n': the cursor lands ON that newline - pane.cur_row = @intCast(end.row -| 1); - pane.cur_col = @intCast(modal.lineSlice(f.content, end.row -| 1).len); + pane.body.cur_row = @intCast(end.row -| 1); + pane.body.cur_col = @intCast(modal.lineSlice(f.content, end.row -| 1).len); } - pane.cur_pinned = true; - pane.sticky_col = -1; + pane.body.cur_pinned = true; + pane.body.sticky_col = -1; pane.ensureCursorVisible(); - } else edit.pasteText(p, pane, p.yank orelse return, true, 1); + } else edit.pasteText(p, &pane.body, p.yank orelse return, true, 1); } test "plain left click clears explicit modal selection" { @@ -989,10 +989,10 @@ test "plain left click clears explicit modal selection" { const p = try Pardes.init(gpa, .{ .cols = 40, .rows = 10 }); defer p.deinit(); const pane = try p.setTestFile("abcdef\n"); - pane.cur_row = 0; - pane.cur_col = 5; - pane.vsel = .{ .active = true, .row = 0, .col = 1, .explicit = true }; - pane.msel = .{ .active = true, .r0 = 0, .r1 = 0 }; + pane.body.cur_row = 0; + pane.body.cur_col = 5; + pane.body.vsel = .{ .active = true, .row = 0, .col = 1, .explicit = true }; + pane.body.msel = .{ .active = true, .r0 = 0, .r1 = 0 }; var frame = std.heap.ArenaAllocator.init(gpa); defer frame.deinit(); @@ -1003,9 +1003,9 @@ test "plain left click clears explicit modal selection" { p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = click_x, .row = body_y } }); p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = click_x, .row = body_y } }); - try std.testing.expectEqual(@as(i32, 3), pane.cur_col); - try std.testing.expect(!pane.vsel.active); - try std.testing.expect(!pane.msel.active); + try std.testing.expectEqual(@as(i32, 3), pane.body.cur_col); + try std.testing.expect(!pane.body.vsel.active); + try std.testing.expect(!pane.body.msel.active); try std.testing.expectEqual(.none, pane.sel[@intFromEnum(config.select_button)].state); } @@ -1412,7 +1412,7 @@ test "mouse thumb buttons navigate once and clear selection gestures" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12 }); defer p.deinit(); const pane = try p.setTestFile("alpha beta\ngamma delta\nepsilon zeta\n"); - pane.setRange(pane.file.?.content, 0, .{ .anchor = 1, .head = 5 }, true); + pane.body.setRange(pane.file.?.content, 0, .{ .anchor = 1, .head = 5 }, true); p.njumps = 3; p.jcur = 2; for (0..3) |i| p.jumps[i] = .{ .pane = 0, .serial = pane.serial, .line = @intCast(i + 1), .col = 1 }; @@ -1425,6 +1425,6 @@ test "mouse thumb buttons navigate once and clear selection gestures" { p.update(.{ .mouse = .{ .button = .forward, .kind = .press, .col = 0, .row = 0 } }); p.update(.{ .mouse = .{ .button = .forward, .kind = .release, .col = 0, .row = 0 } }); try std.testing.expectEqual(@as(usize, 2), p.jcur); - try std.testing.expect(!pane.vsel.active); + try std.testing.expect(!pane.body.vsel.active); try std.testing.expectEqual(.none, p.drag); } diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 645b1c33..484b08c9 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -297,9 +297,9 @@ test "the pane ctl takes get, lock and unlock, and nothing that a file of its ow defer p.deinit(); const ctl_node = Node.of(serialOf(p), .ctl); for ([_][]const u8{ - "menu", "nomenu", "dump echo hi", "font Go Mono", "lock x", "bogus", "DEL", - "name x.txt", "put", "del", "delete", "Look x", "Exec Save", "clean", - "dirty", "cleartag", "dot=addr", "addr=dot", "show", "mark", "nomark", + "menu", "nomenu", "dump echo hi", "font Go Mono", "lock x", "bogus", "DEL", + "name x.txt", "put", "del", "delete", "Look x", "Exec Save", "clean", + "dirty", "cleartag", "dot=addr", "addr=dot", "show", "mark", "nomark", "scroll", "limit=addr", "get x", "look /tmp", "exec Del", }) |bad| try testing.expectEqual(E.INVAL, wr(p, ctl_node, bad).errno()); try testing.expect(p.paneBySerial(serialOf(p)) != null); @@ -447,27 +447,27 @@ test "look opens spaced paths and locations without editing the source pane" { const look_node = Node.of(source.serial, .look); const revision = source.file.?.revision; const undo_len = source.file.?.history.undo_len; - source.cur_col = 3; + source.body.cur_col = 3; var clicked: [4200]u8 = undefined; try testing.expectEqual(Status.ok, wr(p, look_node, try std.fmt.bufPrint(&clicked, "{s}:2:3\n", .{path})).reply.status); const opened = p.panes[p.active].?; try testing.expect(opened != source); try testing.expectEqualStrings(path, opened.file.?.path); try testing.expectEqualStrings("first\nsecond\nthird\n", opened.file.?.content); - try testing.expectEqual(@as(i32, 1), opened.cur_row); - try testing.expectEqual(@as(i32, 2), opened.cur_col); + try testing.expectEqual(@as(i32, 1), opened.body.cur_row); + try testing.expectEqual(@as(i32, 2), opened.body.cur_col); try testing.expectEqualStrings("source stays intact\n", source.file.?.content); try testing.expectEqual(revision, source.file.?.revision); try testing.expectEqual(undo_len, source.file.?.history.undo_len); - try testing.expectEqual(@as(i32, 3), source.cur_col); + try testing.expectEqual(@as(i32, 3), source.body.cur_col); var expected: [16]u8 = undefined; try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{opened.serial}), rd(p, root_look, 0, 4096).bytes); p.active = 0; try testing.expectEqual(Status.ok, wr(p, root_look, try std.fmt.bufPrint(&clicked, "{s}:3:2\n", .{path})).reply.status); try testing.expect(p.panes[p.active].? == opened); - try testing.expectEqual(@as(i32, 2), opened.cur_row); - try testing.expectEqual(@as(i32, 1), opened.cur_col); + try testing.expectEqual(@as(i32, 2), opened.body.cur_row); + try testing.expectEqual(@as(i32, 1), opened.body.cur_col); try testing.expectEqualStrings(try std.fmt.bufPrint(&expected, "{d}\n", .{opened.serial}), rd(p, root_look, 0, 4096).bytes); } diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 76854dbc..7e9cf7e7 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -124,9 +124,9 @@ fn cellOf(row: i32, col: i32) modal.Cursor { pub fn dotOf(pane: *Pane) State.Range { const text = bodyOf(pane); - const head = modal.offsetAt(text, cellOf(pane.cur_row, pane.cur_col)); - if (!pane.vsel.active) return .{ .q0 = clip(head), .q1 = clip(head) }; - const anchor = modal.offsetAt(text, cellOf(pane.vsel.row, pane.vsel.col)); + const head = modal.offsetAt(text, cellOf(pane.body.cur_row, pane.body.cur_col)); + if (!pane.body.vsel.active) return .{ .q0 = clip(head), .q1 = clip(head) }; + const anchor = modal.offsetAt(text, cellOf(pane.body.vsel.row, pane.body.vsel.col)); var hi = @max(head, anchor); if (hi < text.len) hi = modal.nextGrapheme(text, hi); return .{ .q0 = clip(@min(head, anchor)), .q1 = clip(hi) }; @@ -137,23 +137,23 @@ pub fn setDot(pane: *Pane, r: State.Range) void { const q0 = @min(@as(usize, r.q0), text.len); const q1 = @max(q0, @min(@as(usize, r.q1), text.len)); const a = modal.positionAt(text, q0); - pane.vsel = .{ .active = q1 > q0, .row = @intCast(a.row), .col = @intCast(a.col), .explicit = true }; + pane.body.vsel = .{ .active = q1 > q0, .row = @intCast(a.row), .col = @intCast(a.col), .explicit = true }; const h = modal.positionAt(text, if (q1 > q0) modal.prevGrapheme(text, q1) else q0); - pane.cur_row = @intCast(h.row); - pane.cur_col = @intCast(h.col); - pane.cur_pinned = true; - pane.sticky_col = -1; - pane.msel.active = false; + pane.body.cur_row = @intCast(h.row); + pane.body.cur_col = @intCast(h.col); + pane.body.cur_pinned = true; + pane.body.sticky_col = -1; + pane.body.msel.active = false; pane.ensureCursorVisible(); } pub fn showOffset(pane: *Pane, off: usize) void { const text = bodyOf(pane); const c = modal.positionAt(text, @min(off, text.len)); - pane.cur_row = @intCast(c.row); - pane.cur_col = @intCast(c.col); - pane.cur_pinned = true; - pane.sticky_col = -1; + pane.body.cur_row = @intCast(c.row); + pane.body.cur_col = @intCast(c.col); + pane.body.cur_pinned = true; + pane.body.sticky_col = -1; pane.ensureCursorVisible(); } diff --git a/src/normal.zig b/src/normal.zig index 6647dcca..192fd933 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -12,6 +12,7 @@ const edit = @import("edit.zig"); const config = @import("config.zig"); const pdf_enabled = panes.Pdf.enabled; const Pane = panes.Pane; +const Text = panes.Text; const Key = pardes.Key; const hit = pardes.hit; const sel_slot = pardes.sel_slot; @@ -66,11 +67,11 @@ pub fn multiOnce(p: *Pardes) bool { } fn startSelRegex(p: *Pardes, pane: *Pane, split: bool) void { - const text = edit.flatSurface(p, pane) catch return; - const got = pane.ranges(text, 0, &pane.sel_snap); + const text = edit.flatSurface(p, &pane.body) catch return; + const got = pane.body.ranges(text, 0, &pane.sel_snap); pane.nsel_snap = @intCast(got.n); pane.sel_snap_pri = @intCast(got.pri); - pane.sel_snap_expl = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active; + pane.sel_snap_expl = (pane.body.vsel.active and pane.body.vsel.explicit) or pane.body.msel.active; p.startPrompt(pane, .{ .search = if (split) config.split_marker else config.select_marker }); } @@ -89,9 +90,9 @@ pub fn selRegexArmed(pane: *Pane) ?struct { pat: []const u8, split: bool } { } pub fn applySelRegex(p: *Pardes, pane: *Pane, pat: []const u8, split: bool) void { - const text = edit.flatSurface(p, pane) catch return; + const text = edit.flatSurface(p, &pane.body) catch return; const snap = pane.sel_snap[0..pane.nsel_snap]; - var out: [Pane.max_selections]modal.Selection = undefined; + var out: [Text.max_selections]modal.Selection = undefined; var m: usize = 0; if (pat.len > 0) if (mvzr.compile(pat)) |re| { var hay_all = text; @@ -109,7 +110,7 @@ pub fn applySelRegex(p: *Pardes, pane: *Pane, pat: []const u8, split: bool) void const hay = hay_all[from..to]; var at: usize = 0; var piece = from; // split: where the next piece begins - while (at < hay.len and m < Pane.max_selections) { + while (at < hay.len and m < Text.max_selections) { const hit_at = re.matchPos(at, hay) orelse break; if (split) { out[m] = .{ .anchor = piece, .head = from + hit_at.start }; @@ -122,7 +123,7 @@ pub fn applySelRegex(p: *Pardes, pane: *Pane, pat: []const u8, split: bool) void // an empty match would otherwise never advance at = if (hit_at.end > hit_at.start) hit_at.end else hit_at.end + 1; } - if (split and piece < to and m < Pane.max_selections) { + if (split and piece < to and m < Text.max_selections) { out[m] = .{ .anchor = piece, .head = to }; m += 1; } @@ -135,37 +136,37 @@ pub fn applySelRegex(p: *Pardes, pane: *Pane, pat: []const u8, split: bool) void r.anchor = @min(r.anchor, text.len); r.head = @min(r.head, text.len); } - return pane.setRanges(text, snap, &.{}, pane.sel_snap_pri, pane.sel_snap_expl); + return pane.body.setRanges(text, snap, &.{}, pane.sel_snap_pri, pane.sel_snap_expl); } - pane.setRanges(text, out[0..m], &.{}, 0, true); // helix keeps primary 0 (its own TODO) + pane.body.setRanges(text, out[0..m], &.{}, 0, true); // helix keeps primary 0 (its own TODO) } const KeyState = struct { - mode: Pane.Mode, + mode: Text.Mode, select: bool, normal: modal.Normal.State, find_op: u8, find_ch: u21, - append_at: @FieldType(Pane, "append_at"), + append_at: @FieldType(Text, "append_at"), - fn of(pane: *Pane) KeyState { + fn of(t: *Text) KeyState { return .{ - .mode = pane.mode, - .select = pane.select, - .normal = pane.normal, - .find_op = pane.find_op, - .find_ch = pane.find_ch, - .append_at = pane.append_at, + .mode = t.mode, + .select = t.select, + .normal = t.normal, + .find_op = t.find_op, + .find_ch = t.find_ch, + .append_at = t.append_at, }; } - fn into(s: KeyState, pane: *Pane) void { - pane.mode = s.mode; - pane.select = s.select; - pane.normal = s.normal; - pane.find_op = s.find_op; - pane.find_ch = s.find_ch; - pane.append_at = s.append_at; + fn into(s: KeyState, t: *Text) void { + t.mode = s.mode; + t.select = s.select; + t.normal = s.normal; + t.find_op = s.find_op; + t.find_ch = s.find_ch; + t.append_at = s.append_at; } }; @@ -175,25 +176,25 @@ const Replay = union(enum) { insert: Key, }; -pub fn replaySels(p: *Pardes, pane: *Pane, what: Replay) void { +pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { const id = p.active; - const serial = pane.serial; - // the whole selection in pane coordinates, document order. pane.sels + const serial = t.pane().serial; + // the whole selection in text coordinates, document order. t.sels // is already ordered, so this only slots the primary into place. - var list: [Pane.max_selections]Pane.SelRange = undefined; + var list: [Text.max_selections]Text.SelRange = undefined; var n: usize = 0; var pri: usize = 0; - const prim: Pane.SelRange = .{ - .row = pane.cur_row, - .col = pane.cur_col, - .arow = if (pane.vsel.active) pane.vsel.row else pane.cur_row, - .acol = if (pane.vsel.active) pane.vsel.col else pane.cur_col, - .sticky = pane.sticky_col, + const prim: Text.SelRange = .{ + .row = t.cur_row, + .col = t.cur_col, + .arow = if (t.vsel.active) t.vsel.row else t.cur_row, + .acol = if (t.vsel.active) t.vsel.col else t.cur_col, + .sticky = t.sticky_col, }; - const pr = Pane.selStart(prim); + const pr = Text.selStart(prim); var placed = false; - for (pane.sels[0..pane.nsel]) |s| { - const sr = Pane.selStart(s); + for (t.sels[0..t.nsel]) |s| { + const sr = Text.selStart(s); if (!placed and (pr.row < sr.row or (pr.row == sr.row and pr.col <= sr.col))) { pri = n; list[n] = prim; @@ -209,13 +210,13 @@ pub fn replaySels(p: *Pardes, pane: *Pane, what: Replay) void { n += 1; } - const saved = KeyState.of(pane); - const explicit = pane.vsel.explicit; + const saved = KeyState.of(t); + const explicit = t.vsel.explicit; var after = saved; var after_expl = explicit; // each pass's result: cursor and anchor cells as distances from the // end of the surface text, plus the range's own j/k goal column - var res: [Pane.max_selections]struct { cur: usize, anc: usize, sticky: i32 } = undefined; + var res: [Text.max_selections]struct { cur: usize, anc: usize, sticky: i32 } = undefined; p.multi_on = true; p.multi_stop = false; var passes: usize = 0; @@ -224,98 +225,99 @@ pub fn replaySels(p: *Pardes, pane: *Pane, what: Replay) void { i -= 1; p.multi_first = passes == 0; passes += 1; - saved.into(pane); - pane.nsel = 0; // the handler underneath sees ONE selection - pane.cur_row = list[i].row; - pane.cur_col = list[i].col; - pane.vsel = .{ - .active = list[i].arow != list[i].row or list[i].acol != list[i].col or pane.select, + saved.into(t); + t.nsel = 0; // the handler underneath sees ONE selection + t.cur_row = list[i].row; + t.cur_col = list[i].col; + t.vsel = .{ + .active = list[i].arow != list[i].row or list[i].acol != list[i].col or t.select, .row = list[i].arow, .col = list[i].acol, .explicit = explicit, }; - pane.msel.active = false; - pane.sticky_col = list[i].sticky; + t.msel.active = false; + t.sticky_col = list[i].sticky; switch (what) { - .normal => |normal_action| executeNormalAction(p, pane, normal_action), - .insert => |insert_key| edit.insertKey(p, pane, insert_key), + .normal => |normal_action| executeNormalAction(p, t, normal_action), + .insert => |insert_key| edit.insertKey(p, t, insert_key), } if (p.multi_stop) break; if (i == pri) { - after = KeyState.of(pane); - after_expl = pane.vsel.explicit; + after = KeyState.of(t); + after_expl = t.vsel.explicit; } - const text = edit.flatSurface(p, pane) catch { + const text = edit.flatSurface(p, t) catch { p.multi_stop = true; break; }; - const co = modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.cur_row)), .col = @intCast(@max(0, pane.cur_col)) }); - const ao = if (pane.vsel.active) - modal.offsetAt(text, .{ .row = @intCast(@max(0, pane.vsel.row)), .col = @intCast(@max(0, pane.vsel.col)) }) + const co = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) }); + const ao = if (t.vsel.active) + modal.offsetAt(text, .{ .row = @intCast(@max(0, t.vsel.row)), .col = @intCast(@max(0, t.vsel.col)) }) else co; - res[i] = .{ .cur = text.len - @min(co, text.len), .anc = text.len - @min(ao, text.len), .sticky = pane.sticky_col }; + res[i] = .{ .cur = text.len - @min(co, text.len), .anc = text.len - @min(ao, text.len), .sticky = t.sticky_col }; } p.multi_on = false; p.multi_first = false; if (p.multi_stop) { p.multi_stop = false; const pn = p.panes[id] orelse return; - if (pn.serial == serial) pn.nsel = 0; + if (pn.serial == serial) pn.body.nsel = 0; return; } - const text = edit.flatSurface(p, pane) catch return; - var rs: [Pane.max_selections]modal.Selection = undefined; - var st: [Pane.max_selections]i32 = undefined; + const text = edit.flatSurface(p, t) catch return; + var rs: [Text.max_selections]modal.Selection = undefined; + var st: [Text.max_selections]i32 = undefined; for (res[0..n], 0..) |r, k| { - rs[k] = Pane.cellOffRange(text, text.len - @min(r.anc, text.len), text.len - @min(r.cur, text.len)); + rs[k] = Text.cellOffRange(text, text.len - @min(r.anc, text.len), text.len - @min(r.cur, text.len)); st[k] = r.sticky; } - pane.setRanges(text, rs[0..n], st[0..n], pri, after_expl); - after.into(pane); - pane.ensureCursorVisible(); // the view follows the PRIMARY, not the last pass + t.setRanges(text, rs[0..n], st[0..n], pri, after_expl); + after.into(t); + t.pane().ensureCursorVisible(); // the view follows the PRIMARY, not the last pass } -pub fn handleNormal(p: *Pardes, pane: *Pane, key: Key) void { - const parsed = modal.Normal.parse(&pane.normal, normalInput(key)); +pub fn handleNormal(p: *Pardes, t: *Text, key: Key) void { + const parsed = modal.Normal.parse(&t.normal, normalInput(key)); const semantic = switch (parsed) { .pending, .ignored, .unbound => return, .action => |value| value, }; - if (pane.nsel == 0 or semantic.scope() == .once) - return executeNormalAction(p, pane, semantic); - replaySels(p, pane, .{ .normal = semantic }); + if (t.nsel == 0 or semantic.scope() == .once) + return executeNormalAction(p, t, semantic); + replaySels(p, t, .{ .normal = semantic }); } -fn executeNormalAction(p: *Pardes, pane: *Pane, semantic: modal.Normal.Action) void { +fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void { + const pane = t.pane(); const raw_selection = pane.rawPointerText(pane.sel[sel_slot]) != null; - const before = .{ pane.cur_row, pane.cur_col, pane.vsel, pane.msel, pane.select, pane.nsel, pane.mode }; - defer if (raw_selection and !std.meta.eql(before, .{ pane.cur_row, pane.cur_col, pane.vsel, pane.msel, pane.select, pane.nsel, pane.mode })) { + const before = .{ t.cur_row, t.cur_col, t.vsel, t.msel, t.select, t.nsel, t.mode }; + defer if (raw_selection and !std.meta.eql(before, .{ t.cur_row, t.cur_col, t.vsel, t.msel, t.select, t.nsel, t.mode })) { pane.clearPointerSelection(sel_slot); pane.sel[sel_slot].state = .none; }; - if (raw_selection and semantic == .edit and semantic.edit.kind == .yank) return edit.normalYank(p, pane); - edit.pinPaneCursor(p, pane); - const text = edit.flatSurface(p, pane) catch return; - const range = pane.primaryRange(text, 0); + if (raw_selection and semantic == .edit and semantic.edit.kind == .yank) return edit.normalYank(p, t); + edit.pinPaneCursor(p, t); + const text = edit.flatSurface(p, t) catch return; + const range = t.primaryRange(text, 0); const cur = modal.selectionCursor(text, range); switch (semantic) { .escape => { - pane.select = false; + t.select = false; return exec.runBuiltin(p, .Last, p.active, "", null); }, .goto => |go| switch (go.target) { .file_start => { - const line = if (go.explicit_count) @min(@as(usize, go.count) - 1, Pane.maxLine(text)) else 0; - return pane.pointMove(text, range, modal.lineStartOffset(text, line)); + const line = if (go.explicit_count) @min(@as(usize, go.count) - 1, Text.maxLine(text)) else 0; + return t.pointMove(text, range, modal.lineStartOffset(text, line)); }, - .last_line => return pane.pointMove(text, range, modal.lineStartOffset(text, Pane.maxLine(text))), - .line_start => return pane.pointMove(text, range, modal.lineStartOffset(text, modal.lineAtOffset(text, cur))), + .last_line => return t.pointMove(text, range, modal.lineStartOffset(text, Text.maxLine(text))), + .line_start => return t.pointMove(text, range, modal.lineStartOffset(text, modal.lineAtOffset(text, cur))), .line_end => { const line = modal.lineAtOffset(text, cur); const ls = modal.lineStartOffset(text, line); - return pane.pointMove(text, range, @max(ls, modal.prevGrapheme(text, modal.lineEndOffset(text, line)))); + return t.pointMove(text, range, @max(ls, modal.prevGrapheme(text, modal.lineEndOffset(text, line)))); }, .first_nonws => { const line = modal.lineAtOffset(text, cur); @@ -323,35 +325,35 @@ fn executeNormalAction(p: *Pardes, pane: *Pane, semantic: modal.Normal.Action) v const slice = text[ls..modal.lineEndOffset(text, line)]; const nw = modal.firstNonWs(slice); if (nw == slice.len) return; - return pane.pointMove(text, range, ls + nw); + return t.pointMove(text, range, ls + nw); }, - .line_down => return pane.visualMove(text, range, true, go.count, edit.paneWrapWidth(p, pane)), - .line_up => return pane.visualMove(text, range, false, go.count, edit.paneWrapWidth(p, pane)), + .line_down => return t.visualMove(text, range, true, go.count, edit.paneWrapWidth(p, t)), + .line_up => return t.visualMove(text, range, false, go.count, edit.paneWrapWidth(p, t)), .column => { const line = modal.lineAtOffset(text, cur); const ls = modal.lineStartOffset(text, line); const slice = text[ls..modal.lineEndOffset(text, line)]; - return pane.pointMove(text, range, ls + modal.graphemeAtColumn(slice, @as(usize, go.count) - 1)); + return t.pointMove(text, range, ls + modal.graphemeAtColumn(slice, @as(usize, go.count) - 1)); }, - .view_top => return pane.gotoWindow(text, range, .top, go.count), - .view_center => return pane.gotoWindow(text, range, .center, go.count), - .view_bottom => return pane.gotoWindow(text, range, .bottom, go.count), + .view_top => return t.gotoWindow(text, range, .top, go.count), + .view_center => return t.gotoWindow(text, range, .center, go.count), + .view_bottom => return t.gotoWindow(text, range, .bottom, go.count), }, .view => |view| switch (view) { .top => { - pane.scrollBy(pane.cur_row - pane.scroll()); + pane.scrollBy(t.cur_row - pane.scroll()); pane.ensureCursorVisible(); }, .center => { - pane.scrollBy(pane.cur_row - (pane.scroll() + @divTrunc(@as(i32, pane.rows), 2) - 1)); + pane.scrollBy(t.cur_row - (pane.scroll() + @divTrunc(@as(i32, pane.rows), 2) - 1)); pane.ensureCursorVisible(); }, .bottom => { - pane.scrollBy(pane.cur_row - (pane.scroll() + @as(i32, pane.rows) - 1)); + pane.scrollBy(t.cur_row - (pane.scroll() + @as(i32, pane.rows) - 1)); pane.ensureCursorVisible(); }, - .scroll_down => return pane.scrollViewMove(text, range, 1), - .scroll_up => return pane.scrollViewMove(text, range, -1), + .scroll_down => return t.scrollViewMove(text, range, 1), + .scroll_up => return t.scrollViewMove(text, range, -1), }, .find => |find| { const op: u8 = switch (find.kind) { @@ -360,9 +362,9 @@ fn executeNormalAction(p: *Pardes, pane: *Pane, semantic: modal.Normal.Action) v .till_forward => @intCast(config.till_char_fwd), .till_backward => @intCast(config.till_char_back), }; - pane.find_op = op; - pane.find_ch = find.char; - return pane.findMove( + t.find_op = op; + t.find_ch = find.char; + return t.findMove( text, range, find.char, @@ -371,21 +373,21 @@ fn executeNormalAction(p: *Pardes, pane: *Pane, semantic: modal.Normal.Action) v find.count, ); }, - .replace_char => |char| return edit.normalReplaceChar(p, pane, char), + .replace_char => |char| return edit.normalReplaceChar(p, t, char), .match_bracket => { - const lines = edit.paneCursorLines(p, pane) catch return; + const lines = edit.paneCursorLines(p, t) catch return; const mc = modal.matchBracket(lines, modal.positionAt(text, cur)) orelse return; - return pane.pointMove(text, range, modal.offsetAt(text, mc)); + return t.pointMove(text, range, modal.offsetAt(text, mc)); }, - .textobject => |object| return edit.textobjectSelect(p, pane, text, object.char, object.around), - .surround_add => |char| return edit.surroundAdd(p, pane, char), - .surround_delete => |char| return edit.surroundDelete(p, pane, char), - .surround_replace => |replace| return edit.surroundReplace(p, pane, replace.from, replace.to), + .textobject => |object| return edit.textobjectSelect(p, t, text, object.char, object.around), + .surround_add => |char| return edit.surroundAdd(p, t, char), + .surround_delete => |char| return edit.surroundDelete(p, t, char), + .surround_replace => |replace| return edit.surroundReplace(p, t, replace.from, replace.to), .paragraph => |paragraph| { - const r2 = modal.moveParagraph(text, range, paragraph.count, paragraph.direction == .forward, pane.select); - return pane.setRange(text, 0, r2, false); + const r2 = modal.moveParagraph(text, range, paragraph.count, paragraph.direction == .forward, t.select); + return t.setRange(text, 0, r2, false); }, - .add_newline => |newline| return edit.addNewline(p, pane, newline.direction == .forward, newline.count), + .add_newline => |newline| return edit.addNewline(p, t, newline.direction == .forward, newline.count), .diagnostic => |diagnostic| { const fwd = diagnostic.direction == .forward; if (!diagnostic.endpoint) { @@ -409,46 +411,46 @@ fn executeNormalAction(p: *Pardes, pane: *Pane, semantic: modal.Normal.Action) v .left => { var target = cur; for (0..move.count) |_| target = modal.prevGrapheme(text, target); - return pane.pointMove(text, range, target); + return t.pointMove(text, range, target); }, .right => { var target = cur; for (0..move.count) |_| target = modal.nextGrapheme(text, target); - return pane.pointMove(text, range, target); + return t.pointMove(text, range, target); }, - .down => return pane.verticalMove(text, range, true, move.count), - .up => return pane.verticalMove(text, range, false, move.count), - .next_word_start => return pane.wordMove(text, range, move.count, .next_word_start), - .prev_word_start => return pane.wordMove(text, range, move.count, .prev_word_start), - .next_word_end => return pane.wordMove(text, range, move.count, .next_word_end), - .next_long_word_start => return pane.wordMove(text, range, move.count, .next_long_word_start), - .prev_long_word_start => return pane.wordMove(text, range, move.count, .prev_long_word_start), - .next_long_word_end => return pane.wordMove(text, range, move.count, .next_long_word_end), + .down => return t.verticalMove(text, range, true, move.count), + .up => return t.verticalMove(text, range, false, move.count), + .next_word_start => return t.wordMove(text, range, move.count, .next_word_start), + .prev_word_start => return t.wordMove(text, range, move.count, .prev_word_start), + .next_word_end => return t.wordMove(text, range, move.count, .next_word_end), + .next_long_word_start => return t.wordMove(text, range, move.count, .next_long_word_start), + .prev_long_word_start => return t.wordMove(text, range, move.count, .prev_long_word_start), + .next_long_word_end => return t.wordMove(text, range, move.count, .next_long_word_end), }, .repeat_find => |count| { - if (pane.find_op == 0) return; - const fwd = pane.find_op == config.find_char_fwd or pane.find_op == config.till_char_fwd; - const till = pane.find_op == config.till_char_fwd or pane.find_op == config.till_char_back; + if (t.find_op == 0) return; + const fwd = t.find_op == config.find_char_fwd or t.find_op == config.till_char_fwd; + const till = t.find_op == config.till_char_fwd or t.find_op == config.till_char_back; var repeated = range; var moved = false; for (0..count) |_| { const cc = modal.selectionCursor(text, repeated); - const target = modal.findTarget(text, cc, pane.find_ch, fwd, till, 1) orelse break; - repeated = if (pane.select) + const target = modal.findTarget(text, cc, t.find_ch, fwd, till, 1) orelse break; + repeated = if (t.select) modal.moveSelectionCursor(text, repeated, target, true) else modal.moveSelectionCursor(text, .{ .anchor = cc, .head = cc }, target, true); moved = true; } if (!moved) return; - return pane.setRange(text, 0, repeated, false); + return t.setRange(text, 0, repeated, false); }, .line => |line_kind| switch (line_kind) { - .start => return pane.pointMove(text, range, modal.lineStartOffset(text, modal.lineAtOffset(text, cur))), + .start => return t.pointMove(text, range, modal.lineStartOffset(text, modal.lineAtOffset(text, cur))), .end => { const line = modal.lineAtOffset(text, cur); const ls = modal.lineStartOffset(text, line); - return pane.pointMove(text, range, @max(ls, modal.prevGrapheme(text, modal.lineEndOffset(text, line)))); + return t.pointMove(text, range, @max(ls, modal.prevGrapheme(text, modal.lineEndOffset(text, line)))); }, .first_nonws => { const line = modal.lineAtOffset(text, cur); @@ -456,21 +458,21 @@ fn executeNormalAction(p: *Pardes, pane: *Pane, semantic: modal.Normal.Action) v const slice = text[ls..modal.lineEndOffset(text, line)]; const nw = modal.firstNonWs(slice); if (nw == slice.len) return; - return pane.pointMove(text, range, ls + nw); + return t.pointMove(text, range, ls + nw); }, }, .goto_line => |go| { if (!go.explicit) return; - const line = @min(@as(usize, go.count) - 1, Pane.maxLine(text)); - return pane.pointMove(text, range, modal.lineStartOffset(text, line)); + const line = @min(@as(usize, go.count) - 1, Text.maxLine(text)); + return t.pointMove(text, range, modal.lineStartOffset(text, line)); }, .page => |page| switch (page.kind) { // Counts were parsed historically but these four text view // actions intentionally move exactly one viewport unit. - .half_down => return pane.halfPageMove(text, range, true), - .half_up => return pane.halfPageMove(text, range, false), - .down => return pane.scrollViewMove(text, range, @as(i32, pane.rows)), - .up => return pane.scrollViewMove(text, range, -@as(i32, pane.rows)), + .half_down => return t.halfPageMove(text, range, true), + .half_up => return t.halfPageMove(text, range, false), + .down => return t.scrollViewMove(text, range, @as(i32, pane.rows)), + .up => return t.scrollViewMove(text, range, -@as(i32, pane.rows)), }, .insert => |insert| { const where: edit.InsertAt = switch (insert.kind) { @@ -481,59 +483,59 @@ fn executeNormalAction(p: *Pardes, pane: *Pane, semantic: modal.Normal.Action) v .open_below => .open_below, .open_above => .open_above, }; - return edit.enterInsert(p, pane, where, insert.count); + return edit.enterInsert(p, t, where, insert.count); }, .select => |select| switch (select.kind) { .mode => { - if (pane.select) { - pane.select = false; + if (t.select) { + t.select = false; } else { - pane.select = true; - if (pane.msel.active) { - pane.setRange(text, 0, range, true); - } else if (!pane.vsel.active) { - pane.vsel = .{ .active = true, .row = pane.cur_row, .col = pane.cur_col, .explicit = true }; + t.select = true; + if (t.msel.active) { + t.setRange(text, 0, range, true); + } else if (!t.vsel.active) { + t.vsel = .{ .active = true, .row = t.cur_row, .col = t.cur_col, .explicit = true }; } else { - pane.vsel.explicit = true; + t.vsel.explicit = true; } } - pane.cur_pinned = true; + t.cur_pinned = true; }, - .line => return pane.lineSelect(text, range, select.count), - .line_bounds => return pane.lineBoundsSelect(text, range), - .shrink_to_line_bounds => return pane.shrinkSelToLineBounds(text, range), - .collapse => return pane.setRange(text, 0, .{ .anchor = cur, .head = cur }, false), + .line => return t.lineSelect(text, range, select.count), + .line_bounds => return t.lineBoundsSelect(text, range), + .shrink_to_line_bounds => return t.shrinkSelToLineBounds(text, range), + .collapse => return t.setRange(text, 0, .{ .anchor = cur, .head = cur }, false), .flip => { - const explicit = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active; - return pane.setRange(text, 0, .{ .anchor = range.head, .head = range.anchor }, explicit); + const explicit = (t.vsel.active and t.vsel.explicit) or t.msel.active; + return t.setRange(text, 0, .{ .anchor = range.head, .head = range.anchor }, explicit); }, - .all => return pane.setRange(text, 0, .{ .anchor = 0, .head = text.len }, false), + .all => return t.setRange(text, 0, .{ .anchor = 0, .head = text.len }, false), }, .multi => |multi| { if (multi.kind == .keep_primary) { - pane.nsel = 0; + t.nsel = 0; return; } - return pane.multiSelAction(text, multi.kind, multi.count); + return t.multiSelAction(text, multi.kind, multi.count); }, .select_regex => |split| return startSelRegex(p, pane, split), .edit => |op| switch (op.kind) { - .delete => return edit.normalDelete(p, pane, true), - .delete_noyank => return edit.normalDelete(p, pane, false), - .change => return edit.normalChange(p, pane), - .yank => return edit.normalYank(p, pane), - .replace_with_yank => return edit.normalReplaceYank(p, pane), - .paste_after => return edit.pasteText(p, pane, p.yank orelse return, false, op.count), - .paste_before => return edit.pasteText(p, pane, p.yank orelse return, true, op.count), - .switch_case => return edit.normalCase(p, pane, .toggle), - .lowercase => return edit.normalCase(p, pane, .lower), - .uppercase => return edit.normalCase(p, pane, .upper), - .join_lines => return edit.normalJoin(p, pane), - .indent => return edit.normalIndent(p, pane, op.count, true), - .unindent => return edit.normalIndent(p, pane, op.count, false), - .comment_toggle => return edit.normalToggleComment(p, pane), - .undo => return edit.doUndo(p, pane), - .redo => return edit.doRedo(p, pane), + .delete => return edit.normalDelete(p, t, true), + .delete_noyank => return edit.normalDelete(p, t, false), + .change => return edit.normalChange(p, t), + .yank => return edit.normalYank(p, t), + .replace_with_yank => return edit.normalReplaceYank(p, t), + .paste_after => return edit.pasteText(p, t, p.yank orelse return, false, op.count), + .paste_before => return edit.pasteText(p, t, p.yank orelse return, true, op.count), + .switch_case => return edit.normalCase(p, t, .toggle), + .lowercase => return edit.normalCase(p, t, .lower), + .uppercase => return edit.normalCase(p, t, .upper), + .join_lines => return edit.normalJoin(p, t), + .indent => return edit.normalIndent(p, t, op.count, true), + .unindent => return edit.normalIndent(p, t, op.count, false), + .comment_toggle => return edit.normalToggleComment(p, t), + .undo => return edit.doUndo(p, t), + .redo => return edit.doRedo(p, t), }, .lsp => |request| return p.lspRequest(p.active, switch (request) { .definition => .definition, @@ -543,14 +545,14 @@ fn executeNormalAction(p: *Pardes, pane: *Pane, semantic: modal.Normal.Action) v .references => .references, .format => .format, }, ""), - .adjust_number => |delta| return edit.normalAdjustNumber(p, pane, delta), + .adjust_number => |delta| return edit.normalAdjustNumber(p, t, delta), .leader => { p.leader_on = true; p.leader_n = 0; }, .command_line => { p.enterTagEdit(pane, -1); - if (pane.tag_edit) pane.mode = .normal; + if (pane.tag_edit) t.mode = .normal; }, .pipe_selection => |how| return p.startPrompt(pane, .{ .pipe = how }), .search => return p.startPrompt(pane, .{ .search = config.search_marker }), @@ -565,15 +567,15 @@ pub fn handlePdfNormal(p: *Pardes, pane: *Pane, key: Key) void { if (comptime !pdf_enabled) return; if (pane.pdf == null) return; if (hit(key, config.leave_pane)) { - pane.normal.clear(); - pane.select = false; + pane.body.normal.clear(); + pane.body.select = false; return exec.runBuiltin(p, .Last, p.active, "", null); } - if (pane.normal.prefix == .none and isPrefix(key, 'f')) { - pane.normal.clear(); + if (pane.body.normal.prefix == .none and isPrefix(key, 'f')) { + pane.body.normal.clear(); return exec.runBuiltin(p, .PdfSections, p.active, "", null); } - const parsed = modal.Normal.parse(&pane.normal, normalInput(key)); + const parsed = modal.Normal.parse(&pane.body.normal, normalInput(key)); switch (parsed) { .pending, .ignored, .unbound => {}, .action => |semantic| { @@ -595,7 +597,7 @@ pub fn handlePdfNormal(p: *Pardes, pane: *Pane, key: Key) void { }, .command_line => { p.enterTagEdit(pane, -1); - if (pane.tag_edit) pane.mode = .normal; + if (pane.tag_edit) pane.body.mode = .normal; }, .search => p.startPrompt(pane, .{ .search = config.search_marker }), .search_forward => look.lookWalk(p, 1), @@ -618,57 +620,57 @@ test "gj/gk step the wrapped rows a body draws while j/k keep the file's lines" // gj holds the column INSIDE the row and lands on the next break; the line // is one line the whole way down, which is the whole point. - pane.cur_row = 0; - pane.cur_col = 3; - pane.sticky_col = -1; + pane.body.cur_row = 0; + pane.body.cur_col = 3; + pane.body.sticky_col = -1; p.update(.{ .key = .{ .cp = 'g' } }); p.update(.{ .key = .{ .cp = 'j' } }); - try std.testing.expectEqual(@as(i32, 0), pane.cur_row); - try std.testing.expectEqual(@as(i32, @intCast(width + 3)), pane.cur_col); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, @intCast(width + 3)), pane.body.cur_col); p.update(.{ .key = .{ .cp = 'g' } }); p.update(.{ .key = .{ .cp = 'j' } }); - try std.testing.expectEqual(@as(i32, @intCast(width * 2 + 3)), pane.cur_col); + try std.testing.expectEqual(@as(i32, @intCast(width * 2 + 3)), pane.body.cur_col); p.update(.{ .key = .{ .cp = 'g' } }); p.update(.{ .key = .{ .cp = 'k' } }); - try std.testing.expectEqual(@as(i32, @intCast(width + 3)), pane.cur_col); + try std.testing.expectEqual(@as(i32, @intCast(width + 3)), pane.body.cur_col); // A count is counted in rows, not lines. p.update(.{ .key = .{ .cp = '2' } }); p.update(.{ .key = .{ .cp = 'g' } }); p.update(.{ .key = .{ .cp = 'j' } }); - try std.testing.expectEqual(@as(i32, 0), pane.cur_row); - try std.testing.expectEqual(@as(i32, @intCast(width * 3 + 3)), pane.cur_col); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, @intCast(width * 3 + 3)), pane.body.cur_col); // Plain j/k are untouched: one FILE line each, whatever the body drew. - pane.cur_col = 3; - pane.sticky_col = -1; + pane.body.cur_col = 3; + pane.body.sticky_col = -1; p.update(.{ .key = .{ .cp = 'j' } }); - try std.testing.expectEqual(@as(i32, 1), pane.cur_row); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); p.update(.{ .key = .{ .cp = 'k' } }); - try std.testing.expectEqual(@as(i32, 0), pane.cur_row); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); // The last row of a line steps into the next line's first row, and the // first row steps back onto the previous line's LAST row. - pane.cur_row = 0; - pane.cur_col = @intCast(long.len - 1); - pane.sticky_col = -1; + pane.body.cur_row = 0; + pane.body.cur_col = @intCast(long.len - 1); + pane.body.sticky_col = -1; p.update(.{ .key = .{ .cp = 'g' } }); p.update(.{ .key = .{ .cp = 'j' } }); - try std.testing.expectEqual(@as(i32, 1), pane.cur_row); - pane.cur_col = 0; - pane.sticky_col = -1; + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); + pane.body.cur_col = 0; + pane.body.sticky_col = -1; p.update(.{ .key = .{ .cp = 'g' } }); p.update(.{ .key = .{ .cp = 'k' } }); - try std.testing.expectEqual(@as(i32, 0), pane.cur_row); - try std.testing.expect(pane.cur_col >= @as(i32, @intCast(long.len - long.len % width))); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); + try std.testing.expect(pane.body.cur_col >= @as(i32, @intCast(long.len - long.len % width))); // Wrap OFF: a line is one visual row, so gj/gk ARE j/k again. p.settings.wrap = false; - pane.cur_row = 0; - pane.cur_col = 3; - pane.sticky_col = -1; + pane.body.cur_row = 0; + pane.body.cur_col = 3; + pane.body.sticky_col = -1; p.update(.{ .key = .{ .cp = 'g' } }); p.update(.{ .key = .{ .cp = 'j' } }); - try std.testing.expectEqual(@as(i32, 1), pane.cur_row); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); } test "flat text movement and selection replay need no scratch rows" { @@ -685,39 +687,39 @@ test "flat text movement and selection replay need no scratch rows" { p.scratch.deinit(); p.scratch = .init(denied.allocator()); - pane.cur_row = 4094; - handleNormal(p, pane, .{ .cp = 'l' }); - try std.testing.expectEqual(@as(i32, 1), pane.cur_col); - handleNormal(p, pane, .{ .cp = 'j' }); - try std.testing.expectEqual(@as(i32, 4095), pane.cur_row); - try std.testing.expectEqual(@as(i32, 1), pane.cur_col); - handleNormal(p, pane, .{ .cp = 'h' }); - try std.testing.expectEqual(@as(i32, 0), pane.cur_col); - executeNormalAction(p, pane, .{ .textobject = .{ .char = 'w', .around = false } }); - try std.testing.expectEqual(@as(i32, 2), pane.cur_col); - try std.testing.expectEqual(@as(i32, 0), pane.vsel.col); + pane.body.cur_row = 4094; + handleNormal(p, &pane.body, .{ .cp = 'l' }); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); + handleNormal(p, &pane.body, .{ .cp = 'j' }); + try std.testing.expectEqual(@as(i32, 4095), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); + handleNormal(p, &pane.body, .{ .cp = 'h' }); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_col); + executeNormalAction(p, &pane.body, .{ .textobject = .{ .char = 'w', .around = false } }); + try std.testing.expectEqual(@as(i32, 2), pane.body.cur_col); + try std.testing.expectEqual(@as(i32, 0), pane.body.vsel.col); - pane.vsel.active = false; - pane.cur_row = 1024; - pane.cur_col = 0; - pane.nsel = 1; - pane.sels[0] = .{ .row = 3072, .col = 0, .arow = 3072, .acol = 0 }; - handleNormal(p, pane, .{ .cp = 'l' }); - handleNormal(p, pane, .{ .cp = 'j' }); - try std.testing.expectEqual(@as(u8, 1), pane.nsel); - try std.testing.expectEqual(@as(i32, 1025), pane.cur_row); - try std.testing.expectEqual(@as(i32, 1), pane.cur_col); - try std.testing.expectEqual(@as(i32, 3073), pane.sels[0].row); - try std.testing.expectEqual(@as(i32, 1), pane.sels[0].col); + pane.body.vsel.active = false; + pane.body.cur_row = 1024; + pane.body.cur_col = 0; + pane.body.nsel = 1; + pane.body.sels[0] = .{ .row = 3072, .col = 0, .arow = 3072, .acol = 0 }; + handleNormal(p, &pane.body, .{ .cp = 'l' }); + handleNormal(p, &pane.body, .{ .cp = 'j' }); + try std.testing.expectEqual(@as(u8, 1), pane.body.nsel); + try std.testing.expectEqual(@as(i32, 1025), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); + try std.testing.expectEqual(@as(i32, 3073), pane.body.sels[0].row); + try std.testing.expectEqual(@as(i32, 1), pane.body.sels[0].col); try std.testing.expect(!denied.has_induced_failure); try std.testing.expectEqual(@as(usize, 0), p.scratch.queryCapacity()); - pane.nsel = 0; - pane.cur_col = 4; - executeNormalAction(p, pane, .match_bracket); + pane.body.nsel = 0; + pane.body.cur_col = 4; + executeNormalAction(p, &pane.body, .match_bracket); try std.testing.expect(denied.has_induced_failure); - try std.testing.expectEqual(@as(i32, 4), pane.cur_col); + try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col); denied.fail_index = std.math.maxInt(usize); - executeNormalAction(p, pane, .match_bracket); - try std.testing.expectEqual(@as(i32, 8), pane.cur_col); + executeNormalAction(p, &pane.body, .match_bracket); + try std.testing.expectEqual(@as(i32, 8), pane.body.cur_col); } diff --git a/src/panes.zig b/src/panes.zig index 9bf2d92f..e6634583 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -24,8 +24,6 @@ const Key = pardes.Key; pub const EditText = struct { text: []u8, row0: i32 }; pub const Pane = struct { - pub const Mode = enum { normal, insert, tty }; - /// One mouse selection (block-shaped), per button. c/r are text-area relative; /// r counts from the tag row (body starts at BOX_H). pub const Sel = struct { @@ -53,39 +51,12 @@ pub const Pane = struct { rows: []PointerRow, raw_text: ?[]u8 = null, }; - - /// A modal line selection (helix `x`): whole rows [r0, r1], absolute. - pub const LineSel = struct { - active: bool = false, - r0: i32 = 0, - r1: i32 = 0, - }; - - pub const CharSel = struct { - active: bool = false, - row: i32 = 0, - col: i32 = 0, - explicit: bool = false, - }; - pub const LookSpot = struct { row: i32, col0: i32, col1: i32, }; - pub const max_selections = 64; - - pub const SelRange = struct { - row: i32, - col: i32, - arow: i32, - acol: i32, - /// this range's own j/k goal column (helix Range::old_visual_position); - /// the PRIMARY's copy is Pane.sticky_col - sticky: i32 = -1, - }; - const PdfSlot = if (Pdf.enabled) ?Pdf.State else void; pub const Prompt = union(enum) { @@ -108,7 +79,9 @@ pub const Pane = struct { /// dies with it, as acme keeps the same on its Window /// (editors/acme/dat.h:226-266). fs: pardes.ctlfs.pane.State = .{}, - mode: Mode = .normal, + /// The body: what the pane shows and edits, its cursor, selections, + /// mode and edit-buffer undo. + body: Text = .{}, vweight: f32 = 1, /// A folded pane keeps its expansion weight, but occupies only its tag row. collapsed: bool = false, @@ -121,26 +94,13 @@ pub const Pane = struct { file: ?File.State = null, image: ?Image.State = null, pdf: PdfSlot = if (Pdf.enabled) null else {}, - msel: LineSel = .{}, - vsel: CharSel = .{}, - sels: [max_selections - 1]SelRange = undefined, - nsel: u8 = 0, - select: bool = false, - /// sticky goal column for j/k runs (helix old_visual_position): any - /// non-vertical range write resets it to -1. - sticky_col: i32 = -1, - append_at: ?struct { row: i32, col: i32 } = null, - normal: modal.Normal.State = .{}, - /// last f/F/t/T motion, for Alt-. repeat - find_op: u8 = 0, - find_ch: u21 = 0, /// Tag-tail input state. The tag text is presentation; this tag carries /// which operation owns it and the tail offset restored on submit/cancel. prompt: Prompt = .none, search_pane: ?usize = null, search_row: ?usize = null, look_at: ?LookSpot = null, - sel_snap: [max_selections]modal.Selection = undefined, + sel_snap: [Text.max_selections]modal.Selection = undefined, nsel_snap: u8 = 0, sel_snap_pri: u8 = 0, sel_snap_expl: bool = false, @@ -153,7 +113,7 @@ pub const Pane = struct { tag_sel: bool = false, /// the body mode a tag edit hijacked (tags are always insert); terminals /// restore it on exit so clicking the tag never changes the pane's mode - tag_mode: Mode = .normal, + tag_mode: Text.Mode = .normal, tag_col: u16 = 0, tag_saved_col: ?u16 = null, tag_anchor: u16 = 0, @@ -163,14 +123,7 @@ pub const Pane = struct { tag_name_len: ?u16 = null, /// Display columns hidden to reveal the tag caret; tag addresses stay whole. tag_scroll: u16 = 0, - ed_undo: [Terminal.history_max]Terminal.Snapshot = undefined, - ed_undo_len: usize = 0, - ed_redo: [Terminal.history_max]Terminal.Snapshot = undefined, - ed_redo_len: usize = 0, cwd: Cwd = .none, - cur_pinned: bool = false, - cur_row: i32 = 0, - cur_col: i32 = 0, hscroll: i32 = 0, // Visible rows map to source lines and raw/display column origins. wrap_line: [limits.wrap_rows]i32 = undefined, @@ -512,7 +465,7 @@ pub const Pane = struct { // already, so only treat an ancestor as pinned in the matching view. if (pane.context_rows < pane.wrap_n and pane.wrap_line[pane.context_rows] == off) { for (pane.wrap_line[0..pane.context_rows]) |row| { - if (row == pane.cur_row) { + if (row == pane.body.cur_row) { in_context = true; break; } @@ -528,10 +481,10 @@ pub const Pane = struct { margin = @min(margin, @divTrunc(@max(0, lines_shown), 2)); } if (!in_context) { - if (pane.cur_row < off + margin) { - pane.scrollBy(pane.cur_row - margin - off); - } else if (pane.cur_row > last - margin) { - var to = pane.cur_row + margin; + if (pane.body.cur_row < off + margin) { + pane.scrollBy(pane.body.cur_row - margin - off); + } else if (pane.body.cur_row > last - margin) { + var to = pane.body.cur_row + margin; if (pane.file) |*f| to = @min(to, @as(i32, @intCast(File.nlines(pane.gpa, f) -| 1))); if (comptime Pdf.enabled) { if (pane.pdf) |pv| @@ -544,8 +497,8 @@ pub const Pane = struct { if (pane.body_wrapped) return; const w: i32 = @max(1, @as(i32, pane.cols) - @as(i32, File.gutterWidth(pane))); const hmargin: i32 = @min(config.scroll_off, @divTrunc(w - 1, 2)); - const line = modal.lineSlice(f.content, @intCast(@max(0, pane.cur_row))); - const raw_cur: usize = @intCast(@max(0, pane.cur_col)); + const line = modal.lineSlice(f.content, @intCast(@max(0, pane.body.cur_row))); + const raw_cur: usize = @intCast(@max(0, pane.body.cur_col)); const raw_scroll: usize = @intCast(@max(0, pane.hscroll)); const cur = @as(i32, @intCast(File.rawDisplayCol(line, raw_cur))); const visual_scroll = @as(i32, @intCast(File.rawDisplayCol(line, raw_scroll))); @@ -559,16 +512,16 @@ pub const Pane = struct { } pub fn pinCursor(pane: *Pane) void { - if (pane.cur_pinned) return; + if (pane.body.cur_pinned) return; if (pane.file != null or hasPdf(pane)) { - pane.cur_row = pane.scroll(); - pane.cur_col = 0; + pane.body.cur_row = pane.scroll(); + pane.body.cur_col = 0; } else { const cur = Terminal.gridCursor(pane); - pane.cur_row = pane.surfRow(@as(i32, cur.y) + Terminal.gridOffset(pane)); - pane.cur_col = @intCast(cur.x); + pane.body.cur_row = pane.surfRow(@as(i32, cur.y) + Terminal.gridOffset(pane)); + pane.body.cur_col = @intCast(cur.x); } - pane.cur_pinned = true; + pane.body.cur_pinned = true; } pub fn hasPdf(pane: *const Pane) bool { @@ -581,545 +534,10 @@ pub const Pane = struct { else false; } - - pub fn toModalCursor(pane: *Pane) modal.Cursor { - return .{ .row = @intCast(@max(0, pane.cur_row)), .col = @intCast(@max(0, pane.cur_col)) }; - } - - pub fn fromModalCursor(pane: *Pane, c: modal.Cursor) void { - pane.cur_row = @as(i32, @intCast(c.row)); - pane.cur_col = @intCast(c.col); - pane.cur_pinned = true; - } - - pub fn insertVerticalCursor(lines: []const []const u8, c: modal.Cursor, down: bool) modal.Cursor { - if (lines.len == 0) return c; - const row = if (down) @min(c.row + 1, lines.len - 1) else c.row -| 1; - const target = lines[row]; - if (target.len == 0) return .{ .row = row, .col = 0 }; - const source = if (c.row < lines.len) lines[c.row] else ""; - const goal = File.rawDisplayCol(source, c.col); - const mapped = File.rawAtDisplay(target, goal); - const last = modal.prevGrapheme(target, target.len); - return .{ .row = row, .col = modal.graphemeStart(target, @min(mapped, last)) }; - } - - pub fn primaryRange(pane: *Pane, text: []const u8, row0: i32) modal.Selection { - const c = File.textOffset(pane, text, .{ .row = @intCast(@max(0, pane.cur_row - row0)), .col = @intCast(@max(0, pane.cur_col)) }); - if (pane.msel.active) { - // legacy line selection (file-search results highlight): linewise - const r0: usize = @intCast(@max(0, @min(pane.msel.r0, pane.msel.r1) - row0)); - const r1: usize = @intCast(@max(0, @max(pane.msel.r0, pane.msel.r1) - row0)); - const s = modal.lineStartOffset(text, r0); - const e = if (r1 + 1 >= modal.cursorLineCount(text)) text.len else modal.lineStartOffset(text, r1 + 1); - return .{ .anchor = s, .head = @max(e, modal.nextGrapheme(text, c)) }; - } - if (pane.vsel.active) return cellRange(text, pane.vsel.row - row0, pane.vsel.col, pane.cur_row - row0, pane.cur_col); - return .{ .anchor = c, .head = modal.nextGrapheme(text, c) }; - } - - pub fn cellRange(text: []const u8, arow: i32, acol: i32, hrow: i32, hcol: i32) modal.Selection { - const a = modal.offsetAt(text, .{ .row = @intCast(@max(0, arow)), .col = @intCast(@max(0, acol)) }); - const c = modal.offsetAt(text, .{ .row = @intCast(@max(0, hrow)), .col = @intCast(@max(0, hcol)) }); - return cellOffRange(text, a, c); - } - - /// the same, from the two cells' gap offsets - pub fn cellOffRange(text: []const u8, a: usize, c: usize) modal.Selection { - if (a <= c) return .{ .anchor = a, .head = modal.nextGrapheme(text, c) }; - return .{ .anchor = modal.nextGrapheme(text, a), .head = c }; - } - - pub fn rangeCells(text: []const u8, r: modal.Selection) struct { cur: usize, anc: usize } { - if (r.head > r.anchor) return .{ .cur = modal.prevGrapheme(text, r.head), .anc = r.anchor }; - if (r.head < r.anchor) return .{ .cur = r.head, .anc = modal.prevGrapheme(text, r.anchor) }; - return .{ .cur = r.head, .anc = r.head }; - } - - pub fn setRange(pane: *Pane, text: []const u8, row0: i32, r0: modal.Selection, explicit: bool) void { - var r = r0; - if (r.anchor == r.head) r.head = modal.nextGrapheme(text, r.head); // min_width_1 - const off = rangeCells(text, r); - const cc = File.textPosition(pane, text, off.cur); - // a bare block cursor has both cells on the same offset — the common - // case by far — and this conversion is not free even indexed - const ac = if (off.anc == off.cur) cc else File.textPosition(pane, text, off.anc); - pane.cur_row = @as(i32, @intCast(cc.row)) + row0; - pane.cur_col = @intCast(cc.col); - pane.vsel = .{ - .active = off.anc != off.cur or pane.select, - .row = @as(i32, @intCast(ac.row)) + row0, - .col = @intCast(ac.col), - .explicit = explicit or pane.select, - }; - pane.msel.active = false; - pane.nsel = 0; // writing ONE range means the selection IS that range - pane.cur_pinned = true; - pane.sticky_col = -1; - pane.normal.clear(); - pane.ensureCursorVisible(); - } - - pub fn ranges(pane: *Pane, text: []const u8, row0: i32, out: *[max_selections]modal.Selection) struct { n: usize, pri: usize } { - const pr = primaryRange(pane, text, row0); - var n: usize = 0; - var pri: usize = 0; - var placed = false; - for (pane.sels[0..pane.nsel]) |s| { - const r = cellRange(text, s.arow - row0, s.acol, s.row - row0, s.col); - if (!placed and @min(pr.anchor, pr.head) <= @min(r.anchor, r.head)) { - pri = n; - out[n] = pr; - n += 1; - placed = true; - } - out[n] = r; - n += 1; - } - if (!placed) { - pri = n; - out[n] = pr; - n += 1; - } - return .{ .n = n, .pri = pri }; - } - - pub fn setRanges(pane: *Pane, text: []const u8, in: []const modal.Selection, sticky: []const i32, pri0: usize, explicit: bool) void { - if (in.len == 0) return; // helix asserts non-empty; here it just means "no change" - var r: [max_selections]modal.Selection = undefined; - var st: [max_selections]i32 = undefined; - var n: usize = @min(in.len, max_selections); - var pri: usize = @min(pri0, n - 1); - for (in[0..n], 0..) |x, i| { - r[i] = x; - if (r[i].anchor == r[i].head) r[i].head = modal.nextGrapheme(text, r[i].head); - st[i] = if (i < sticky.len) sticky[i] else -1; - } - // insertion sort by start — n is tiny and usually already ordered - var i: usize = 1; - while (i < n) : (i += 1) { - var j = i; - while (j > 0 and @min(r[j].anchor, r[j].head) < @min(r[j - 1].anchor, r[j - 1].head)) : (j -= 1) { - std.mem.swap(modal.Selection, &r[j], &r[j - 1]); - std.mem.swap(i32, &st[j], &st[j - 1]); - if (pri == j) pri = j - 1 else if (pri == j - 1) pri = j; - } - } - var k: usize = 0; - i = 1; - while (i < n) : (i += 1) { - const a = r[k]; - const b = r[i]; - const af = @min(a.anchor, a.head); - const at = @max(a.anchor, a.head); - const bf = @min(b.anchor, b.head); - const bt = @max(b.anchor, b.head); - if (af == bf or (at > bf and bt > af)) { - r[k] = if (a.anchor > a.head and b.anchor > b.head) - .{ .anchor = @max(a.anchor, b.anchor), .head = @min(a.head, b.head) } - else - .{ .anchor = @min(af, bf), .head = @max(at, bt) }; - if (pri == i) pri = k; - if (st[k] < 0) st[k] = st[i]; - continue; - } - k += 1; - r[k] = b; - st[k] = st[i]; - if (pri == i) pri = k; - } - n = k + 1; - setRange(pane, text, 0, r[pri], explicit); - pane.sticky_col = st[pri]; - var w: usize = 0; - for (r[0..n], 0..) |x, idx| { - if (idx == pri) continue; - const c = rangeCells(text, x); - const cc = modal.positionAt(text, c.cur); - const ac = modal.positionAt(text, c.anc); - pane.sels[w] = .{ - .row = @as(i32, @intCast(cc.row)), - .col = @intCast(cc.col), - .arow = @as(i32, @intCast(ac.row)), - .acol = @intCast(ac.col), - .sticky = st[idx], - }; - w += 1; - } - pane.nsel = @intCast(w); - } - - pub fn multiSelAction(pane: *Pane, text: []const u8, kind: modal.Normal.Multi, cnt: usize) void { - var rs: [max_selections]modal.Selection = undefined; - const got = ranges(pane, text, 0, &rs); - const n = got.n; - const expl = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active; - if (kind == .remove_primary) { - if (n < 2) return; // helix: "no selections remaining" - var out: [max_selections]modal.Selection = undefined; - var m: usize = 0; - for (rs[0..n], 0..) |r, i| { - if (i == got.pri) continue; - out[m] = r; - m += 1; - } - // helix Selection::remove: the NEXT range takes over, or the - // previous one when the primary was last - return setRanges(pane, text, out[0..m], &.{}, @min(got.pri, m - 1), expl); - } - if (kind == .rotate_forward or kind == .rotate_backward) { - const step = cnt % n; - const pri = if (kind == .rotate_forward) (got.pri + step) % n else (got.pri + (n - step)) % n; - return setRanges(pane, text, rs[0..n], &.{}, pri, expl); - } - if (kind == .merge) { - // helix merge_selections: first.merge(last) — the ranges are - // sorted, so that is simply the whole span - const lo = @min(rs[0].anchor, rs[0].head); - const hi = @max(rs[n - 1].anchor, rs[n - 1].head); - const rev = rs[0].anchor > rs[0].head and rs[n - 1].anchor > rs[n - 1].head; - const one: modal.Selection = if (rev) .{ .anchor = hi, .head = lo } else .{ .anchor = lo, .head = hi }; - return setRanges(pane, text, &.{one}, &.{}, 0, expl); - } - if (kind == .merge_consecutive) { - var out: [max_selections]modal.Selection = undefined; - var m: usize = 0; - var pri: usize = 0; - for (rs[0..n], 0..) |r, i| { - if (m > 0 and @min(r.anchor, r.head) == @max(out[m - 1].anchor, out[m - 1].head)) { - const lo = @min(@min(out[m - 1].anchor, out[m - 1].head), @min(r.anchor, r.head)); - const hi = @max(@max(out[m - 1].anchor, out[m - 1].head), @max(r.anchor, r.head)); - out[m - 1] = .{ .anchor = lo, .head = hi }; - if (i == got.pri) pri = m - 1; - continue; - } - if (i == got.pri) pri = m; - out[m] = r; - m += 1; - } - return setRanges(pane, text, out[0..m], &.{}, pri, expl); - } - if (kind == .split_newline) { - // helix selection::split_on_newline — one range per line the - // selection covers, the newlines themselves left out - var out: [max_selections]modal.Selection = undefined; - var m: usize = 0; - for (rs[0..n]) |r| { - const from = @min(r.anchor, r.head); - const to = @max(r.anchor, r.head); - if (from == to) { - if (m < max_selections) { - out[m] = r; - m += 1; - } - continue; - } - var start = from; - while (start < to and m < max_selections) { - const eol = modal.lineEndOffset(text, modal.lineAtOffset(text, start)); - if (eol >= to) { - out[m] = .{ .anchor = start, .head = to }; - m += 1; - break; - } - out[m] = .{ .anchor = start, .head = eol }; - m += 1; - start = eol + 1; - } - } - if (m == 0) return; - return setRanges(pane, text, out[0..m], &.{}, 0, true); // helix keeps primary 0 - } - if (kind == .trim) { - // helix trim_selections: whitespace off both ends; ranges that are - // empty or all whitespace are dropped entirely - var out: [max_selections]modal.Selection = undefined; - var m: usize = 0; - for (rs[0..n]) |r| { - var from = @min(r.anchor, r.head); - var to = @max(r.anchor, r.head); - while (from < to and std.ascii.isWhitespace(text[from])) from += 1; - while (to > from and std.ascii.isWhitespace(text[to - 1])) to -= 1; - if (from >= to) continue; - out[m] = if (r.anchor > r.head) .{ .anchor = to, .head = from } else .{ .anchor = from, .head = to }; - m += 1; - } - if (m == 0) { // helix: collapse_selection + keep_primary_selection - const c = modal.selectionCursor(text, rs[got.pri]); - return setRange(pane, text, 0, .{ .anchor = c, .head = c }, false); - } - // helix: the first survivor that OVERLAPS the old primary, else the last - const pf = @min(rs[got.pri].anchor, rs[got.pri].head); - const pt = @max(rs[got.pri].anchor, rs[got.pri].head); - var pri = m - 1; - for (out[0..m], 0..) |r, i| { - const f = @min(r.anchor, r.head); - const t = @max(r.anchor, r.head); - if (f == pf or (t > pf and pt > f)) { - pri = i; - break; - } - } - return setRanges(pane, text, out[0..m], &.{}, pri, expl); - } - const below = kind == .copy_below; - var out: [max_selections]modal.Selection = undefined; - var m: usize = 0; - var pri: usize = 0; - const nlines = modal.cursorLineCount(text); - for (rs[0..n], 0..) |r, ri| { - const is_pri = ri == got.pri; - // head-exclusive: back the leading end off onto its own cell - const hp = modal.positionAt(text, if (r.anchor < r.head) modal.prevGrapheme(text, r.head) else r.head); - const ap = modal.positionAt(text, if (r.anchor < r.head) r.anchor else modal.prevGrapheme(text, r.anchor)); - const height = @max(hp.row, ap.row) - @min(hp.row, ap.row) + 1; - if (m >= max_selections) break; - if (is_pri) pri = m; - out[m] = r; - m += 1; - var made: usize = 0; - var k: usize = 0; - while (made < cnt and m < max_selections) : (k += 1) { - const d = (k + 1) * height; - const arow = if (below) ap.row + d else ap.row -| d; - const hrow = if (below) hp.row + d else hp.row -| d; - if (arow >= nlines or hrow >= nlines) break; - const a2 = modal.offsetAt(text, .{ .row = arow, .col = ap.col }); - const h2 = modal.offsetAt(text, .{ .row = hrow, .col = hp.col }); - // a line too short to reach the column is skipped, not clamped - if (modal.positionAt(text, a2).col == ap.col and modal.positionAt(text, h2).col == hp.col) { - if (is_pri) pri = m; - out[m] = modal.moveSelectionCursor(text, .{ .anchor = a2, .head = a2 }, h2, true); - m += 1; - made += 1; - } - if (arow == 0 and hrow == 0) break; - } - } - setRanges(pane, text, out[0..m], &.{}, pri, expl); - } - - /// a range's start CELL (document order key) — the smaller of its two ends - pub fn selStart(s: SelRange) struct { row: i32, col: i32 } { - if (s.arow < s.row or (s.arow == s.row and s.acol < s.col)) return .{ .row = s.arow, .col = s.acol }; - return .{ .row = s.row, .col = s.col }; - } - - pub fn maxLine(text: []const u8) usize { - const nl = modal.cursorLineCount(text); - return if (text.len == 0 or text[text.len - 1] == '\n') nl -| 2 else nl - 1; - } - - /// point-target motion: collapse there (extend in select mode) - pub fn pointMove(pane: *Pane, text: []const u8, range: modal.Selection, target: usize) void { - setRange(pane, text, 0, modal.moveSelectionCursor(text, range, target, pane.select), false); - } - - /// word motions select their traversed span (extend mode: head only) - pub fn wordMove(pane: *Pane, text: []const u8, range: modal.Selection, cnt: usize, target: modal.WordTarget) void { - const wr = modal.moveWord(text, range, cnt, target); - const res = if (pane.select) modal.moveSelectionCursor(text, range, modal.selectionCursor(text, wr), true) else wr; - setRange(pane, text, 0, res, false); - } - - /// f/t/F/T: anchor at the old cursor cell, head on the hit (not found: no move) - pub fn findMove(pane: *Pane, text: []const u8, range: modal.Selection, ch: u21, fwd: bool, till: bool, cnt: usize) void { - const cur = modal.selectionCursor(text, range); - const t = modal.findTarget(text, cur, ch, fwd, till, cnt) orelse return; - const res = if (pane.select) - modal.moveSelectionCursor(text, range, t, true) - else - modal.moveSelectionCursor(text, .{ .anchor = cur, .head = cur }, t, true); - setRange(pane, text, 0, res, false); - } - - /// j/k and friends: sticky goal column, clamped onto short lines' newline - pub fn verticalMove(pane: *Pane, text: []const u8, range: modal.Selection, down: bool, cnt: usize) void { - const cur = modal.selectionCursor(text, range); - const pos = File.textPosition(pane, text, cur); - const goal: usize = if (pane.sticky_col >= 0) - @intCast(pane.sticky_col) - else - File.rawDisplayCol(File.textLine(pane, text, pos.row), pos.col); - const last_row = File.textLineCount(pane, text) - 1; - const nline = if (down) @min(pos.row + @max(1, cnt), last_row) else pos.row -| @max(1, cnt); - const target_col = File.rawAtDisplay(File.textLine(pane, text, nline), goal); - const t = File.textOffset(pane, text, .{ .row = nline, .col = target_col }); - // extend mode never walks onto the empty trailing line (helix) - if (pane.select and t == text.len and text.len > 0 and text[text.len - 1] == '\n') return; - setRange(pane, text, 0, modal.moveSelectionCursor(text, range, t, pane.select), false); - pane.sticky_col = @intCast(goal); - } - - pub fn visualMove( - pane: *Pane, - text: []const u8, - range: modal.Selection, - down: bool, - cnt: usize, - width: usize, - ) void { - const cur = modal.selectionCursor(text, range); - const pos = File.textPosition(pane, text, cur); - const last_row = File.textLineCount(pane, text) - 1; - var row = pos.row; - var line = modal.lineSlice(text, row); - var vrow = File.visualRow(line, pos.col, width); - const goal: usize = if (pane.sticky_col >= 0) - @intCast(pane.sticky_col) - else - File.rawDisplayCol(line[vrow.start..vrow.end], pos.col -| vrow.start); - var steps = @max(1, cnt); - while (steps > 0) : (steps -= 1) { - if (down) { - if (vrow.end < line.len) { - vrow = File.visualRow(line, vrow.end, width); - continue; - } - if (row == last_row) break; - row += 1; - line = modal.lineSlice(text, row); - vrow = File.visualRow(line, 0, width); - } else { - if (vrow.start > 0) { - vrow = File.visualRow(line, vrow.start - 1, width); - continue; - } - if (row == 0) break; - row -= 1; - line = modal.lineSlice(text, row); - vrow = File.visualRow(line, line.len, width); - } - } - // The newline slot is a real cursor position, but the first byte of the - // NEXT visual row is not: landing there would read as two rows moved. - var target_col = vrow.start + File.rawAtDisplay(line[vrow.start..vrow.end], goal); - if (vrow.end < line.len and target_col >= vrow.end) - target_col = modal.graphemeStart(line, vrow.end - 1); - const t = File.textOffset(pane, text, .{ .row = row, .col = target_col }); - // extend mode never walks onto the empty trailing line (helix) - if (pane.select and t == text.len and text.len > 0 and text[text.len - 1] == '\n') return; - setRange(pane, text, 0, modal.moveSelectionCursor(text, range, t, pane.select), false); - pane.sticky_col = @intCast(goal); - } - - /// Ctrl-d/u: scroll half a page AND move the cursor by the same rows - pub fn halfPageMove(pane: *Pane, text: []const u8, range: modal.Selection, down: bool) void { - const half: i32 = @max(1, @divTrunc(@as(i32, pane.rows), 2)); - pane.scrollBy(if (down) half else -half); - verticalMove(pane, text, range, down, @intCast(half)); - } - - /// helix `scroll` without cursor sync (Ctrl-f/b, PgUp/PgDn, zj/zk): shift - /// the view, then snap a fallen-out cursor to the near scrolloff edge, col 0 - pub fn scrollViewMove(pane: *Pane, text: []const u8, range: modal.Selection, delta: i32) void { - const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, pane.rows) - 1, 2)); - pane.scrollBy(delta); - const top = pane.scroll(); - const last_row: i32 = @intCast(File.textLineCount(pane, text) - 1); - const cur = modal.selectionCursor(text, range); - if (delta > 0) { - const snap: i32 = @max(0, @min(top + margin, last_row)); - const head = File.textLineStart(pane, text, @intCast(snap)); - if (head <= cur) return; - const anchor = if (pane.select) range.anchor else head; - setRange(pane, text, 0, .{ .anchor = anchor, .head = head }, false); - } else { - const snap: i32 = @max(0, @min(top + @as(i32, pane.rows) - margin - 1, last_row)); - const head = File.textLineStart(pane, text, @intCast(snap)); - if (head >= cur) return; - const anchor = if (pane.select) range.anchor else head; - setRange(pane, text, 0, .{ .anchor = anchor, .head = head }, false); - } - } - - /// gt/gc/gb: view-relative rows, col 0, scrolloff clamped (helix goto_window) - pub fn gotoWindow(pane: *Pane, text: []const u8, range: modal.Selection, which: enum { top, center, bottom }, cnt: usize) void { - const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, pane.rows) - 1, 2)); - const top = pane.scroll(); - const last_row: i32 = @intCast(File.textLineCount(pane, text) - 1); - const last_vis: i32 = @min(@as(i32, pane.rows) - 1, last_row - top); - const n: i32 = @intCast(cnt - 1); - var vline: i32 = switch (which) { - .top => top + margin + n, - .center => top + @divTrunc(last_vis, 2), - .bottom => top + last_vis - (margin + n), - }; - vline = @max(vline, top + margin); - vline = @min(vline, top + last_vis - margin); - const row: i32 = std.math.clamp(vline, 0, last_row); - pointMove(pane, text, range, File.textLineStart(pane, text, @intCast(row))); - } - - /// helix Range::line_range — the inclusive line span a range covers - pub fn rangeLineSpan(text: []const u8, r: modal.Selection) struct { start: usize, end: usize } { - const from = @min(r.anchor, r.head); - const to = @max(r.anchor, r.head); - const to_adj = if (from == to) to else @max(modal.prevGrapheme(text, to), from); - return .{ .start = modal.lineAtOffset(text, from), .end = modal.lineAtOffset(text, to_adj) }; - } - - fn lineStartOrEof(text: []const u8, line: usize) usize { - if (line >= modal.cursorLineCount(text)) return text.len; - return modal.lineStartOffset(text, line); - } - - /// helix `x` extend_line_below: full lines incl. the newline, cursor ON - /// the last one's '\n'; an already-line-bounded selection grows downward - pub fn lineSelect(pane: *Pane, text: []const u8, range: modal.Selection, cnt: usize) void { - const span = rangeLineSpan(text, range); - const start = modal.lineStartOffset(text, span.start); - const end = lineStartOrEof(text, span.end + 1); - const full = @min(range.anchor, range.head) == start and @max(range.anchor, range.head) == end; - const head = lineStartOrEof(text, span.end + cnt + @intFromBool(full)); - setRange(pane, text, 0, .{ .anchor = start, .head = head }, true); - } - - /// helix `X` extend_to_line_bounds (direction kept) - pub fn lineBoundsSelect(pane: *Pane, text: []const u8, range: modal.Selection) void { - const span = rangeLineSpan(text, range); - const start = modal.lineStartOffset(text, span.start); - const end = lineStartOrEof(text, span.end + 1); - const r: modal.Selection = if (range.head < range.anchor) - .{ .anchor = end, .head = start } - else - .{ .anchor = start, .head = end }; - setRange(pane, text, 0, r, true); - } - - /// helix `Alt-x` shrink_to_line_bounds (single-line selections untouched) - pub fn shrinkSelToLineBounds(pane: *Pane, text: []const u8, range: modal.Selection) void { - const span = rangeLineSpan(text, range); - if (span.start == span.end) return; - const from = @min(range.anchor, range.head); - const to = @max(range.anchor, range.head); - var start = modal.lineStartOffset(text, span.start); - var end = lineStartOrEof(text, span.end + 1); - if (start != from) start = lineStartOrEof(text, span.start + 1); - if (end != to) end = modal.lineStartOffset(text, span.end); - const expl = (pane.vsel.active and pane.vsel.explicit) or pane.msel.active; - const r: modal.Selection = if (range.head < range.anchor) - .{ .anchor = end, .head = start } - else - .{ .anchor = start, .head = end }; - setRange(pane, text, 0, r, expl); - } - - /// pull the cursor back inside `text` after a rewrite; `row0` is the - /// absolute surface row of its first line (0 for a file) - pub fn clampCursor(pane: *Pane, text: []const u8, row0: i32) void { - const n = modal.lineCount(text); - const row: usize = @min(@as(usize, @intCast(@max(0, pane.cur_row - row0))), if (n == 0) 0 else n - 1); - const llen = modal.lineSlice(text, row).len; - pane.cur_row = @as(i32, @intCast(row)) + row0; - pane.cur_col = @intCast(@min(@as(usize, @intCast(@max(0, pane.cur_col))), llen)); - pane.cur_pinned = true; - pane.vsel.active = false; - pane.msel.active = false; - pane.ensureCursorVisible(); - } }; +pub const Text = @import("Text.zig"); + pub const File = @import("File.zig"); pub const Output = @import("Output.zig"); @@ -1134,6 +552,7 @@ pub const Terminal = @import("Terminal.zig"); test { _ = Pane; + _ = Text; _ = File; _ = Output; _ = Mini; diff --git a/src/pardes.zig b/src/pardes.zig index 97860cfe..15b2c49b 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -240,6 +240,7 @@ pub const pdf_raster_policy: PdfRasterPolicy = switch (platform) { }; pub const Pane = panes.Pane; +const Text = panes.Text; pub const MAX_PANES = 16; pub const BodyLayer = @import("body_layer.zig").Layer; @@ -875,19 +876,19 @@ test "Togglettymode builtin and keyboard chord share mode transitions including try std.testing.expect(std.mem.indexOf(u8, Pardes.curTail(pane), " Mode ") != null); p.seedTail(pane); try std.testing.expect(pane.appendTag(" Togglettymode")); - try std.testing.expectEqual(Pane.Mode.tty, pane.mode); + try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); try std.testing.expect(p.executeBuiltinLine(0, "Togglettymode")); - try std.testing.expectEqual(Pane.Mode.normal, pane.mode); + try std.testing.expectEqual(Text.Mode.normal, pane.body.mode); p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); - try std.testing.expectEqual(Pane.Mode.tty, pane.mode); + try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); p.enterTagEdit(pane, -1); - try std.testing.expectEqual(Pane.Mode.insert, pane.mode); + try std.testing.expectEqual(Text.Mode.insert, pane.body.mode); try std.testing.expect(p.executeBuiltinLine(0, "Togglettymode")); - try std.testing.expectEqual(Pane.Mode.normal, pane.mode); + try std.testing.expectEqual(Text.Mode.normal, pane.body.mode); try std.testing.expect(!pane.tag_edit); p.enterTagEdit(pane, -1); p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); - try std.testing.expectEqual(Pane.Mode.tty, pane.mode); + try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); try std.testing.expect(!pane.tag_edit); p.acknowledgePanelPresentation(&.{}); @@ -896,10 +897,10 @@ test "Togglettymode builtin and keyboard chord share mode transitions including const y = p.rects[0].y; p.update(.{ .mouse = .{ .button = .middle, .kind = .press, .col = x, .row = y } }); p.update(.{ .mouse = .{ .button = .middle, .kind = .release, .col = x, .row = y } }); - try std.testing.expectEqual(Pane.Mode.normal, pane.mode); + try std.testing.expectEqual(Text.Mode.normal, pane.body.mode); const file = try p.setTestFile("unchanged\n"); try std.testing.expect(p.executeBuiltinLine(0, "Togglettymode")); - try std.testing.expectEqual(Pane.Mode.normal, file.mode); + try std.testing.expectEqual(Text.Mode.normal, file.body.mode); try std.testing.expectEqualStrings("unchanged\n", file.file.?.content); } @@ -1143,7 +1144,7 @@ test "Tty spawns a raw shell in the caller's directory" { try std.testing.expect(free != 0); const nt = p.panes[free] orelse return error.NoNewPane; try std.testing.expect(nt.isTerminal()); - try std.testing.expect(nt.mode == .tty); + try std.testing.expect(nt.body.mode == .tty); var found = false; while (p.nextEffect()) |effect| switch (effect) { @@ -1165,7 +1166,7 @@ test "Tty9p marks only the new Linux terminal for a mounted shell" { try std.testing.expect(p.active != 0); try std.testing.expect(!p.panes[0].?.v9fs_on_spawn); const pane = p.panes[p.active].?; - try std.testing.expect(pane.isTerminal() and pane.mode == .tty); + try std.testing.expect(pane.isTerminal() and pane.body.mode == .tty); try std.testing.expect(pane.v9fs_on_spawn); try std.testing.expect(!pane.greet); try std.testing.expect(!exec.takesCommandLine(p, p.active)); @@ -1753,7 +1754,7 @@ test "owned cwd EOF failure retains the pane and Del retries its close" { p.update(.{ .eof = .{ .pane = 0 } }); try std.testing.expectEqual(parent, p.panes[0].?); try std.testing.expectEqual(parent, child.cwd.inherited); - try std.testing.expectEqual(Pane.Mode.normal, parent.mode); + try std.testing.expectEqual(Text.Mode.normal, parent.body.mode); try std.testing.expect(std.mem.indexOf(u8, parent.msg[0..parent.msg_len], "Del retries close") != null); try std.testing.expectEqual(@as(usize, 0), p.effects_len); allocator.fail_index = std.math.maxInt(usize); @@ -2626,7 +2627,7 @@ test "Unicode display cells map back to body and tag byte cursors" { // Both halves map to its one byte boundary. p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = text_x + 2, .row = body_y } }); p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = text_x + 2, .row = body_y } }); - try std.testing.expectEqual(@as(i32, 1), pane.cur_col); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); // A click in the wide path glyph likewise becomes a byte cursor at the // grapheme start; arrow motion then advances by the full UTF-8 cluster. @@ -2660,8 +2661,8 @@ test "tabbed file aligns syntax cursor and mouse at the nearest insertion gap" { @memset(f.highlights, @intFromEnum(syntax.Syn.none)); @memset(f.highlights[1..7], @intFromEnum(syntax.Syn.keyword)); f.syntax_dirty = false; - pane.cur_row = 0; - pane.cur_col = 1; + pane.body.cur_row = 0; + pane.body.cur_col = 1; var frame = std.heap.ArenaAllocator.init(gpa); defer frame.deinit(); @@ -2678,14 +2679,14 @@ test "tabbed file aligns syntax cursor and mouse at the nearest insertion gap" { const click_x = text_x + config.tab_width + 2; p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = click_x, .row = body_y } }); p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = click_x, .row = body_y } }); - try std.testing.expectEqual(@as(i32, 3), pane.cur_col); + try std.testing.expectEqual(@as(i32, 3), pane.body.cur_col); const line = modal.lineSlice(f.content, 0); const virtual: u16 = 3; const blank_x = text_x + @as(u16, @intCast(panes.File.displayWidth(line))) + virtual; p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = blank_x, .row = body_y } }); p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = blank_x, .row = body_y } }); - try std.testing.expectEqual(@as(i32, @intCast(line.len)), pane.cur_col); + try std.testing.expectEqual(@as(i32, @intCast(line.len)), pane.body.cur_col); _ = frame.reset(.retain_capacity); const virtual_surface = try p.render(frame.allocator()); @@ -3887,7 +3888,7 @@ pub const Pardes = struct { }, .tty, .tty_shell => { _ = try p.newShell(0, ""); - p.panes[0].?.mode = .tty; + p.panes[0].?.body.mode = .tty; p.oneColumn(); // A bare tty is still an editor: it opens with somewhere to put // text under the shell. The shell keeps the keyboard. @@ -4108,8 +4109,8 @@ pub const Pardes = struct { if (comptime pdf_enabled) if (pane.pdf) |*pv| panes.Pdf.deinitPane(p, pane, pv); if (pane.file) |*file| panes.File.deinit(p, pane, file); if (pane.ovl) |o| p.gpa.free(o.text); - for (pane.ed_undo[0..pane.ed_undo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); - for (pane.ed_redo[0..pane.ed_redo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); + for (pane.body.ed_undo[0..pane.body.ed_undo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); + for (pane.body.ed_redo[0..pane.body.ed_redo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); panes.Terminal.deinitEmulator(pane, p.gpa); pane.clearCwd(); pane.fs.deinit(p.gpa); @@ -4159,7 +4160,7 @@ pub const Pardes = struct { errdefer p.gpa.free(content); const np = try panes.Output.open(p, free, paneDir(src), .{ .cmd = .New }, "", content); np.cwd = .{ .inherited = src }; - np.cur_pinned = true; + np.body.cur_pinned = true; return np; } @@ -4170,7 +4171,7 @@ pub const Pardes = struct { const content = try p.gpa.dupe(u8, ""); errdefer p.gpa.free(content); const np = try panes.Output.open(p, free, dir, .{ .cmd = .New }, "", content); - np.cur_pinned = true; + np.body.cur_pinned = true; return np; } @@ -4685,7 +4686,7 @@ pub const Pardes = struct { ctlfs.pty.noteMarks(p, o.pane, pane); }, .eof => |e| p.removePane(e.pane, null) catch |err| { - if (p.panes[e.pane]) |pane| pane.mode = .normal; + if (p.panes[e.pane]) |pane| pane.body.mode = .normal; p.reportError(e.pane, "terminal exited; Del retries close", err); }, .lsp_resp => |r| p.lspResponse(r.id, r.rows), @@ -4839,12 +4840,12 @@ pub const Pardes = struct { const edit0: i32 = @intCast((p.tagPrefix(pane) catch return).len); p.seedTail(pane); if (!pane.tag_init) return; - if (!pane.tag_edit) pane.tag_mode = pane.mode; + if (!pane.tag_edit) pane.tag_mode = pane.body.mode; pane.tag_edit = true; pane.tag_sel = false; // a one-line tag has no use for normal mode: always insert - pane.mode = .insert; - pane.normal.clear(); + pane.body.mode = .insert; + pane.body.normal.clear(); const end = edit0 + @as(i32, @intCast(pane.tag_tail_len)); const tail = pane.tagSlice(); const lead: i32 = @intCast(tail.len - std.mem.trimStart(u8, tail, " ").len); @@ -4870,8 +4871,8 @@ pub const Pardes = struct { pub fn exitTagEdit(pane: *Pane) void { if (pane.tag_edit and pane.prompt == .none) pane.tag_saved_col = pane.tag_col; if (pane.isTerminal()) { - if (pane.tag_edit) pane.mode = pane.tag_mode; - } else pane.mode = .normal; + if (pane.tag_edit) pane.body.mode = pane.tag_mode; + } else pane.body.mode = .normal; pane.tag_edit = false; pane.tag_sel = false; pane.tag_name_len = null; @@ -5054,7 +5055,7 @@ pub const Pardes = struct { const id = p.active; const body_mode = pane.tag_mode; exitTagEdit(pane); // leave the tag FIRST: Del frees the pane - pane.mode = body_mode; + pane.body.mode = body_mode; exec.runBuiltin(p, cmd, id, "", txt); return; } @@ -5075,7 +5076,7 @@ pub const Pardes = struct { else cur)); pane.tag_sel = false; - pane.mode = .insert; + pane.body.mode = .insert; return; } const dir: ?Builtin = for (config.window_keys) |wk| { @@ -5096,7 +5097,7 @@ pub const Pardes = struct { const dest = p.panes[p.active] orelse return; exitTagEdit(pane); // the pane we left is fully out of its tag... p.enterTagEdit(dest, -1); - if (dest.tag_edit) dest.mode = .normal; + if (dest.tag_edit) dest.body.mode = .normal; return; } if (lineMotion(text, cur, key)) |r| setTagRange(pane, text, r); @@ -5244,7 +5245,7 @@ pub const Pardes = struct { p.exitHeader(); p.active = d; p.enterTagEdit(pane, -1); - if (pane.tag_edit) pane.mode = .normal; + if (pane.tag_edit) pane.body.mode = .normal; return; } if (hit(key, config.topbar_up)) { @@ -5268,19 +5269,19 @@ pub const Pardes = struct { pub fn cycleMode(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; if (pane.file == null and !pane.isTerminal()) return; - const previous = if (pane.tag_edit) pane.tag_mode else pane.mode; + const previous = if (pane.tag_edit) pane.tag_mode else pane.body.mode; p.active = id; p.exitHeader(); if (pane.tag_edit) exitTagEdit(pane); - pane.mode = previous; + pane.body.mode = previous; switch (previous) { .tty => { - pane.mode = .normal; - pane.normal.clear(); + pane.body.mode = .normal; + pane.body.normal.clear(); }, - .normal => edit.enterInsert(p, pane, .at, 1), + .normal => edit.enterInsert(p, &pane.body, .at, 1), .insert => { - edit.exitInsert(p, pane); + edit.exitInsert(p, &pane.body); if (pane.isTerminal()) panes.Terminal.enterTty(p, id); }, } @@ -5293,9 +5294,9 @@ pub const Pardes = struct { p.active = id; p.exitHeader(); if (pane.tag_edit) exitTagEdit(pane); - if (pane.mode == .tty) { - pane.mode = .normal; - pane.normal.clear(); + if (pane.body.mode == .tty) { + pane.body.mode = .normal; + pane.body.normal.clear(); } else panes.Terminal.enterTty(p, id); } @@ -5312,7 +5313,7 @@ pub const Pardes = struct { } if (p.topbar_col != null) return p.topbarKey(key); const pane = p.panes[p.active] orelse return; - if (pane.isTerminal() and pane.mode == .tty and !pane.tag_edit) { + if (pane.isTerminal() and pane.body.mode == .tty and !pane.tag_edit) { p.leader_on = false; p.ctrl_w_pending = false; if (key.ctrl and !key.alt and key.cp == p.opts.tty_toggle) @@ -5350,7 +5351,7 @@ pub const Pardes = struct { } // insert mode owns Ctrl-w (delete word backward, helix); the focus // prefix applies outside raw tty mode - if (hit(key, config.window_prefix) and pane.mode != .insert) { + if (hit(key, config.window_prefix) and pane.body.mode != .insert) { p.ctrl_w_pending = true; return; } @@ -5403,27 +5404,27 @@ pub const Pardes = struct { .none, .del_side => unreachable, } exitTagEdit(pane); - pane.mode = .normal; - pane.normal.clear(); + pane.body.mode = .normal; + pane.body.normal.clear(); return; } if (pane.tag_edit) { - if (pane.mode == .normal) p.tagNormalKey(pane, key) else p.tagInsertKey(pane, key); + if (pane.body.mode == .normal) p.tagNormalKey(pane, key) else p.tagInsertKey(pane, key); const pn = p.panes[p.active] orelse return; if (normal.selRegexArmed(pn)) |a| normal.applySelRegex(p, pn, a.pat, a.split); return; } - if (pane.mode == .normal and (hit(key, config.look_key) or hit(key, config.exec_key))) { + if (pane.body.mode == .normal and (hit(key, config.look_key) or hit(key, config.exec_key))) { const cmd = if (hit(key, config.look_key)) config.look_cmd else config.exec_cmd; - edit.pinPaneCursor(p, pane); + edit.pinPaneCursor(p, &pane.body); const explicit = (p.native_images and pane.hasPdfSelection()) or - (pane.vsel.active and pane.vsel.explicit) or pane.msel.active; + (pane.body.vsel.active and pane.body.vsel.explicit) or pane.body.msel.active; if (explicit) { if (exec.chordEachSel(p, pane, cmd)) return; if (edit.currentSelText(p, pane)) |txt| { - pane.vsel.active = false; - pane.msel.active = false; - pane.select = false; + pane.body.vsel.active = false; + pane.body.msel.active = false; + pane.body.select = false; exec.runBuiltin(p, cmd, p.active, "", txt); return; } @@ -5433,14 +5434,14 @@ pub const Pardes = struct { exec.runBuiltin(p, cmd, p.active, "", word); return; } - if (pane.mode == .normal and pane.hasPdf()) return normal.handlePdfNormal(p, pane, key); - switch (pane.mode) { + if (pane.body.mode == .normal and pane.hasPdf()) return normal.handlePdfNormal(p, pane, key); + switch (pane.body.mode) { .normal => { - normal.handleNormal(p, pane, key); + normal.handleNormal(p, &pane.body, key); }, .insert => { - if (hit(key, config.escape)) return edit.exitInsert(p, pane); - edit.handleInsert(p, pane, key); + if (hit(key, config.escape)) return edit.exitInsert(p, &pane.body); + edit.handleInsert(p, &pane.body, key); }, .tty => panes.Terminal.forwardKey(p, p.active, key), } @@ -5529,8 +5530,8 @@ pub const Pardes = struct { }; pane.tag_edit = true; pane.tag_sel = false; - pane.mode = .insert; - pane.normal.clear(); + pane.body.mode = .insert; + pane.body.normal.clear(); pane.tag_col = @intCast(prefix_len + pane.tag_tail_len); } @@ -5551,8 +5552,8 @@ pub const Pardes = struct { if (!zig_buf and std.mem.indexOfAny(u8, arg, " \t\r\n\"\\") != null) return; } const off = if (pane.file) |f| modal.offsetAt(f.content, .{ - .row = @intCast(@max(0, pane.cur_row)), - .col = @intCast(@max(0, pane.cur_col)), + .row = @intCast(@max(0, pane.body.cur_row)), + .col = @intCast(@max(0, pane.body.cur_col)), }) else 0; p.lsp_seq +%= 1; p.lsp_wait = .{ @@ -5562,8 +5563,8 @@ pub const Pardes = struct { .serial = pane.serial, .revision = if (pane.file) |f| f.revision else 0, .arg = .from(arg), - .row = pane.cur_row, - .col = pane.cur_col, + .row = pane.body.cur_row, + .col = pane.body.cur_col, }; p.emit(.{ .lsp = .{ .id = p.lsp_seq, @@ -5666,8 +5667,8 @@ pub const Pardes = struct { const replacement = p.gpa.alloc(u8, final_len) catch return false; const old_cursor = modal.offsetAt(f.content, .{ - .row = @intCast(@max(0, pane.cur_row)), - .col = @intCast(@max(0, pane.cur_col)), + .row = @intCast(@max(0, pane.body.cur_row)), + .col = @intCast(@max(0, pane.body.cur_col)), }); const mapped_cursor = mapLspEditOffset(edits, old_cursor); var read_at: usize = 0; @@ -5681,15 +5682,15 @@ pub const Pardes = struct { } @memcpy(replacement[write_at..], f.content[read_at..]); - edit.pushUndo(p, pane); + edit.pushUndo(p, &pane.body); panes.File.setContent(p, f, replacement); const cursor = modal.positionAt(f.content, mapped_cursor); - pane.cur_row = @intCast(cursor.row); - pane.cur_col = @intCast(cursor.col); - pane.vsel.active = false; - pane.msel.active = false; - pane.select = false; - pane.sticky_col = -1; + pane.body.cur_row = @intCast(cursor.row); + pane.body.cur_col = @intCast(cursor.col); + pane.body.vsel.active = false; + pane.body.msel.active = false; + pane.body.select = false; + pane.body.sticky_col = -1; pane.ensureCursorVisible(); return true; } @@ -5718,8 +5719,8 @@ pub const Pardes = struct { } else return; } if (rows.len == 0) { - if (w.kind == .completion and pane.mode == .insert and pane.nsel == 0 and - pane.cur_row == w.row and pane.cur_col == w.col) edit.insertTab(p, pane); + if (w.kind == .completion and pane.body.mode == .insert and pane.body.nsel == 0 and + pane.body.cur_row == w.row and pane.body.cur_col == w.col) edit.insertTab(p, &pane.body); return; } @@ -5789,7 +5790,7 @@ pub const Pardes = struct { errdefer p.gpa.destroy(history); const pane = try p.newDocPane(id); pane.file = .{ .path = path, .content = content, .history = history }; - pane.cur_pinned = true; + pane.body.cur_pinned = true; return pane; } @@ -5806,7 +5807,7 @@ pub const Pardes = struct { p.panes[0] = null; pane.file = .{ .path = path, .content = copy, .history = history }; p.installPane(0, pane); - pane.cur_pinned = true; + pane.body.cur_pinned = true; p.active = 0; p.sync(); return pane; @@ -6015,8 +6016,8 @@ pub const Pardes = struct { const now: Loc = .{ .pane = @intCast(p.active), .serial = pane.serial, - .line = if (pane.pdfPage()) |page| @intCast(page + 1) else if (pane.cur_pinned) @intCast(@max(0, pane.cur_row) + 1) else 0, - .col = if (pane.pdfPage() != null) 0 else if (pane.cur_pinned) @intCast(@max(0, pane.cur_col) + 1) else 0, + .line = if (pane.pdfPage()) |page| @intCast(page + 1) else if (pane.body.cur_pinned) @intCast(@max(0, pane.body.cur_row) + 1) else 0, + .col = if (pane.pdfPage() != null) 0 else if (pane.body.cur_pinned) @intCast(@max(0, pane.body.cur_col) + 1) else 0, }; if (p.njumps > 0 and p.samePlace(p.jumps[p.jcur], now)) { p.jumps[p.jcur] = now; // same visit; the entry IS where you are @@ -6289,7 +6290,7 @@ pub const Pardes = struct { if (prompt_col < printed.dropped) continue; const caret = printed.left + (prompt_col - printed.dropped); if (caret < tx + tw) - s.cursor = .{ .x = @intCast(caret), .y = row, .bar = pane.mode == .insert }; + s.cursor = .{ .x = @intCast(caret), .y = row, .bar = pane.body.mode == .insert }; } } @@ -6717,7 +6718,7 @@ pub const Pardes = struct { const typed = panes.File.displayWidth(text[0..@min(pane.tag_col - prompt0, text.len)]); const dropped = shown - panes.File.displayWidth(kept); if (typed < dropped) continue; - p.surface.tag_layers[layer_index].cursor = .{ .col = @intCast(pad + typed - dropped), .bar = pane.mode == .insert }; + p.surface.tag_layers[layer_index].cursor = .{ .col = @intCast(pad + typed - dropped), .bar = pane.body.mode == .insert }; } } if (p.columnBarHeight() > 0) for (0..p.ncol) |column| { @@ -6820,7 +6821,7 @@ pub const Pardes = struct { .font_role = .tagline, }; s.fill(r.x, tag_y, config.GUTTER, BOX_H, box_style); - const box_mode = if (pane.tag_edit) pane.tag_mode else pane.mode; + const box_mode = if (pane.tag_edit) pane.tag_mode else pane.body.mode; s.set(r.x, tag_y, switch (box_mode) { .normal => config.tag_normal, .insert => config.tag_insert, @@ -6929,7 +6930,7 @@ pub const Pardes = struct { if (active and pane.tag_edit) { // bar while typing, block for `:` normal mode (same rule as a body) const col = panes.File.rawDisplayCol(tag, pane.tag_col) -| pane.tag_scroll; - if (col < tw) s.cursor = .{ .x = tx + @as(u16, @intCast(col)), .y = tag_y, .bar = pane.mode == .insert }; + if (col < tw) s.cursor = .{ .x = tx + @as(u16, @intCast(col)), .y = tag_y, .bar = pane.body.mode == .insert }; } for (pane.sel, 0..) |selection, button| { @@ -7039,7 +7040,7 @@ test "raw terminal cursor obeys visibility without hiding modal and tag cursors" defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; - pane.mode = .tty; + pane.body.mode = .tty; p.update(.{ .output = .{ .pane = 0, .bytes = "abc" } }); var frame = std.heap.ArenaAllocator.init(gpa); defer frame.deinit(); @@ -7051,10 +7052,10 @@ test "raw terminal cursor obeys visibility without hiding modal and tag cursors" p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?25l" } }); try std.testing.expect((try p.render(frame.allocator())).cursor == null); - pane.mode = .normal; - pane.cur_pinned = true; - pane.cur_row = 0; - pane.cur_col = 1; + pane.body.mode = .normal; + pane.body.cur_pinned = true; + pane.body.cur_row = 0; + pane.body.cur_col = 1; const modal_cursor = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; try std.testing.expectEqual(rect.x + config.GUTTER + 1, modal_cursor.x); try std.testing.expectEqual(body_y, modal_cursor.y); @@ -7062,7 +7063,7 @@ test "raw terminal cursor obeys visibility without hiding modal and tag cursors" const tag_cursor = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; try std.testing.expectEqual(if (p.settings.tag_bottom) rect.y + rect.h - BOX_H else rect.y, tag_cursor.y); Pardes.exitTagEdit(pane); - pane.mode = .tty; + pane.body.mode = .tty; try std.testing.expect((try p.render(frame.allocator())).cursor == null); p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?25h\x1b[?1049h\x1b[2;5H" } }); @@ -7086,7 +7087,7 @@ test "raw terminal cursor follows its active row only while that row is visible" while (p.nextEffect()) |_| {} p.settings.tag_bottom = tag_bottom; const pane = p.panes[0].?; - pane.mode = .tty; + pane.body.mode = .tty; for (0..60) |_| p.update(.{ .output = .{ .pane = 0, .bytes = "row\r\n" } }); p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[3;4H" } }); var frame = std.heap.ArenaAllocator.init(gpa); @@ -7129,7 +7130,7 @@ test "Esc back into a tty leaves its view at the prompt" { try std.testing.expectEqual(shell, p.active); p.update(.{ .key = .{ .cp = Key.escape, .shift = true } }); - try std.testing.expectEqual(Pane.Mode.tty, sp.mode); + try std.testing.expectEqual(Text.Mode.tty, sp.body.mode); // tty mode follows output to the bottom, so a screenful and a half of it // rides the view down and leaves that pin far up in the scrollback. @@ -7368,7 +7369,7 @@ test "the bare tty startup opens a text pane under the shell, unfocused" { const shell = p.panes[p.col_panes[0][0]].?; const scratch = p.panes[p.col_panes[0][1]].?; try std.testing.expect(shell.isTerminal()); - try std.testing.expectEqual(Pane.Mode.tty, shell.mode); + try std.testing.expectEqual(Text.Mode.tty, shell.body.mode); try std.testing.expect(!scratch.isTerminal()); try std.testing.expectEqualStrings("", scratch.file.?.content); @@ -7391,7 +7392,7 @@ test "tty output follows only from the bottom" { const shell = p.active; const sp = p.panes[shell].?; p.update(.{ .key = .{ .cp = Key.escape, .shift = true } }); - try std.testing.expectEqual(Pane.Mode.tty, sp.mode); + try std.testing.expectEqual(Text.Mode.tty, sp.body.mode); for (0..60) |i| { var buf: [32]u8 = undefined; @@ -7445,7 +7446,7 @@ test "Esc back into a file leaves its view where it was" { for (0..20) |_| p.update(.{ .key = .{ .cp = 'j' } }); p.sync(); const view = dp.file.?.scroll; - const row = dp.cur_row; + const row = dp.body.cur_row; try std.testing.expect(view > 0); p.update(.{ .key = .{ .cp = Key.escape } }); // out to the shell @@ -7458,10 +7459,10 @@ test "Esc back into a file leaves its view where it was" { // Nothing moved. The old landing recentred the line under the cursor, so // coming back repainted the whole screen to show what was already on it. try std.testing.expectEqual(view, dp.file.?.scroll); - try std.testing.expectEqual(row, dp.cur_row); + try std.testing.expectEqual(row, dp.body.cur_row); // ...and the cursor is still on screen, which is all `.nearest` promises. - try std.testing.expect(dp.cur_row >= @as(i32, @intCast(view))); - try std.testing.expect(dp.cur_row < @as(i32, @intCast(view)) + @as(i32, dp.rows)); + try std.testing.expect(dp.body.cur_row >= @as(i32, @intCast(view))); + try std.testing.expect(dp.body.cur_row < @as(i32, @intCast(view)) + @as(i32, dp.rows)); // The other arm still centres: a look target, a `:NN`, a search hit. look.focusPaneLine(p, doc, .{ .line = @intCast(row + 1), .col = 1 }, .center); @@ -7488,7 +7489,7 @@ test "raw tty Escape only leaves at a shell prompt" { p.update(.{ .key = .{ .cp = Key.escape, .shift = true } }); try std.testing.expectEqual(@as(usize, 0), p.active); try std.testing.expectEqualStrings("", drainWrites(p, &buf)); - try std.testing.expectEqual(Pane.Mode.tty, pane.mode); + try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); p.update(.{ .key = .{ .cp = Key.escape } }); // back into the shell try std.testing.expectEqual(shell, p.active); @@ -7497,7 +7498,7 @@ test "raw tty Escape only leaves at a shell prompt" { p.update(.{ .key = .{ .cp = Key.escape } }); // bare Escape leaves at a prompt try std.testing.expectEqual(@as(usize, 0), p.active); try std.testing.expectEqualStrings("", drainWrites(p, &buf)); - try std.testing.expectEqual(Pane.Mode.tty, pane.mode); + try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); } test "raw tty Ctrl-B switches to editor mode without sending child input" { @@ -7511,7 +7512,7 @@ test "raw tty Ctrl-B switches to editor mode without sending child input" { _ = drainWrites(p, &buf); p.update(.{ .key = .{ .cp = 'b', .ctrl = true } }); try std.testing.expectEqual(shell, p.active); - try std.testing.expectEqual(Pane.Mode.normal, p.panes[shell].?.mode); + try std.testing.expectEqual(Text.Mode.normal, p.panes[shell].?.body.mode); try std.testing.expectEqualStrings("", drainWrites(p, &buf)); } @@ -7599,7 +7600,7 @@ test "raw tty forwards Ctrl letters and former global shortcuts to the child" { }; try std.testing.expectEqualStrings(encoded, drainWrites(p, &buf)); try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expectEqual(Pane.Mode.tty, p.panes[0].?.mode); + try std.testing.expectEqual(Text.Mode.tty, p.panes[0].?.body.mode); try std.testing.expect(!p.ctrl_w_pending and p.clip_pending == null); } // ...and the two paste chords are the exception: Ctrl-V types the register @@ -7745,13 +7746,13 @@ test "leaving tty hides the prompt and keeps the command typed at it" { // The BODY is what you look at, and it follows the mode: in tty the pane // is the program's own screen, so the prompt is there. - sp.mode = .tty; + sp.body.mode = .tty; try std.testing.expectEqualStrings( "user@box ~/src $ grep -rn TODO src/", bodyRowOf(p, sp, "grep") orelse return error.MissingPromptRow, ); - sp.mode = .normal; + sp.body.mode = .normal; try std.testing.expectEqualStrings( "grep -rn TODO src/", bodyRowOf(p, sp, "grep") orelse return error.MissingPromptRow, @@ -7788,7 +7789,7 @@ test "entering tty walks the shell cursor to the column clicked past the prompt" .bytes = "\x1b]133;A;cl=line\x1b\\prompt> \x1b]133;B\x1b\\0123456789", } }); p.sync(); - sp.mode = .normal; + sp.body.mode = .normal; p.shell_rows.stale = true; // The command shows LEFT-HUGGED, so its column 3 is the '3'... @@ -7802,9 +7803,9 @@ test "entering tty walks the shell cursor to the column clicked past the prompt" // ...but the shell's own cursor lives on the real grid, eight cells // further right, behind the prompt this pane is not showing. - sp.cur_row = row; - sp.cur_col = 3; - sp.cur_pinned = true; + sp.body.cur_row = row; + sp.body.cur_col = 3; + sp.body.cur_pinned = true; while (p.nextEffect()) |_| {} panes.Terminal.enterTty(p, shell); @@ -7897,8 +7898,8 @@ test "LSP failure clears only its matching wait without completion indentation" const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("x"); - pane.mode = .insert; - pane.cur_col = 1; + pane.body.mode = .insert; + pane.body.cur_col = 1; p.lspRequest(p.active, .completion, ""); const old_id = p.lsp_wait.?.id; @@ -7909,13 +7910,13 @@ test "LSP failure clears only its matching wait without completion indentation" p.update(.{ .lsp_resp = .{ .id = current_id, .rows = null } }); try std.testing.expect(p.lsp_wait == null); try std.testing.expectEqualStrings("x", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 1), pane.cur_col); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); p.lspRequest(p.active, .completion, ""); p.update(.{ .lsp_resp = .{ .id = p.lsp_wait.?.id, .rows = "" } }); try std.testing.expect(p.lsp_wait == null); try std.testing.expectEqualStrings("x ", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 4), pane.cur_col); + try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col); } test "board heap: every allocation failure during boot is a clean OutOfMemory" { @@ -7935,25 +7936,25 @@ test "jump history clears selections and lands at the recorded cursor" { p.jumps[0] = .{ .pane = 0, .serial = pane.serial, .line = 3, .col = 8 }; p.jumps[1] = .{ .pane = 0, .serial = pane.serial, .line = 1, .col = 1 }; for ([_]u21{ 'o', 'i' }, 0..) |key, index| { - pane.setRange(pane.file.?.content, 0, .{ .anchor = 1, .head = 5 }, true); + pane.body.setRange(pane.file.?.content, 0, .{ .anchor = 1, .head = 5 }, true); pane.sel[0] = .{ .state = .done, .c0 = 2, .c1 = 5, .r0 = 1, .r1 = 1 }; try edit.capturePointerSelection(p, pane, 0); - pane.select = true; + pane.body.select = true; p.update(.{ .key = .{ .cp = key, .ctrl = true } }); try std.testing.expectEqual(index, p.jcur); try std.testing.expectEqual(@as(usize, 2), p.njumps); try std.testing.expectEqual(@as(u32, 3), p.jumps[0].line); - try std.testing.expect(!pane.vsel.active and !pane.msel.active and !pane.select); - try std.testing.expectEqual(@as(u8, 0), pane.nsel); + try std.testing.expect(!pane.body.vsel.active and !pane.body.msel.active and !pane.body.select); + try std.testing.expectEqual(@as(u8, 0), pane.body.nsel); try std.testing.expectEqual(.none, pane.sel[0].state); try std.testing.expect(pane.pointer_selections[0] == null); - try std.testing.expectEqual(@as(i32, if (index == 0) 2 else 0), pane.cur_row); - try std.testing.expectEqual(@as(i32, if (index == 0) 7 else 0), pane.cur_col); + try std.testing.expectEqual(@as(i32, if (index == 0) 2 else 0), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, if (index == 0) 7 else 0), pane.body.cur_col); } - pane.setRange(pane.file.?.content, 0, .{ .anchor = 1, .head = 5 }, true); - const selected = pane.primaryRange(pane.file.?.content, 0); + pane.body.setRange(pane.file.?.content, 0, .{ .anchor = 1, .head = 5 }, true); + const selected = pane.body.primaryRange(pane.file.?.content, 0); p.jumpBy(1); // No forward entry: selection stays untouched. - try std.testing.expectEqualDeep(selected, pane.primaryRange(pane.file.?.content, 0)); + try std.testing.expectEqualDeep(selected, pane.body.primaryRange(pane.file.?.content, 0)); for ([_]Loc{ .{ .pane = 15, .serial = pane.serial, .line = 1, .col = 1 }, .{ .pane = 0, .serial = pane.serial + 1, .line = 1, .col = 1 }, @@ -7961,7 +7962,7 @@ test "jump history clears selections and lands at the recorded cursor" { p.jumps[0] = missing; p.jumpBy(-1); try std.testing.expectEqual(@as(usize, 1), p.jcur); - try std.testing.expectEqualDeep(selected, pane.primaryRange(pane.file.?.content, 0)); + try std.testing.expectEqualDeep(selected, pane.body.primaryRange(pane.file.?.content, 0)); } } diff --git a/src/pdf_view.zig b/src/pdf_view.zig index 721dac5a..92a05618 100644 --- a/src/pdf_view.zig +++ b/src/pdf_view.zig @@ -1911,7 +1911,7 @@ pub fn openPane( errdefer state.deinit(core.pdf_gpa); const pane = try core.newDocPane(id); pane.pdf = state; - pane.cur_pinned = true; + pane.body.cur_pinned = true; if (filesystem.localPath(path) != null) core.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } }); return pane; } @@ -1967,15 +1967,15 @@ fn refreshCleanSections(core: *pardes.Pardes, state: *State) void { File.setContent(core, file, content); const rows = File.lineCount(file.content); file.scroll = @min(file.scroll, rows - 1); - const row = @min(@as(usize, @intCast(@max(0, result.cur_row))), rows - 1); - result.cur_row = @intCast(row); - result.cur_col = @intCast(@min( - @as(usize, @intCast(@max(0, result.cur_col))), + const row = @min(@as(usize, @intCast(@max(0, result.body.cur_row))), rows - 1); + result.body.cur_row = @intCast(row); + result.body.cur_col = @intCast(@min( + @as(usize, @intCast(@max(0, result.body.cur_col))), modal.lineSlice(file.content, row).len, )); - result.msel.active = false; - result.vsel.active = false; - result.nsel = 0; + result.body.msel.active = false; + result.body.vsel.active = false; + result.body.nsel = 0; state.sections_output.?.revision = file.revision; } @@ -2003,11 +2003,11 @@ fn rearmCleanSections( if (file.revision != remembered.revision) return false; file.scroll = 0; - result.cur_row = 0; - result.cur_col = 0; - result.msel.active = false; - result.vsel.active = false; - result.nsel = 0; + result.body.cur_row = 0; + result.body.cur_col = 0; + result.body.msel.active = false; + result.body.vsel.active = false; + result.body.nsel = 0; pane.search_pane = remembered.pane; pane.search_row = null; look.armLookWalk(core, remembered.pane); @@ -2110,11 +2110,11 @@ pub fn lookSection( } pub fn resetPageChrome(pane: *pardes.Pane) void { - pane.cur_row = 0; - pane.cur_col = 0; - pane.vsel.active = false; - pane.msel.active = false; - pane.nsel = 0; + pane.body.cur_row = 0; + pane.body.cur_col = 0; + pane.body.vsel.active = false; + pane.body.msel.active = false; + pane.body.nsel = 0; } pub fn activatePage( @@ -2454,12 +2454,12 @@ pub fn pointerRelease( const dragged = grid_selection.c0 != grid_selection.c1 or grid_selection.r0 != grid_selection.r1; if (!dragged) state.clearSelection(core.pdf_gpa); - pane.cur_pinned = true; - pane.mode = .normal; - pane.msel.active = false; - pane.vsel.active = false; - pane.normal.clear(); - pane.nsel = 0; + pane.body.cur_pinned = true; + pane.body.mode = .normal; + pane.body.msel.active = false; + pane.body.vsel.active = false; + pane.body.normal.clear(); + pane.body.nsel = 0; state.clearDrag(); return .{}; } diff --git a/src/tty/tty.zig b/src/tty/tty.zig index e3378f5b..903c5c0c 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -1418,8 +1418,8 @@ test "TTY worker setup failures finish matching LSP and pipe requests" { try std.testing.expect(core.lsp_wait == null); try std.testing.expectEqualStrings("abc", pane.file.?.content); - pane.cur_col = 2; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + pane.body.cur_col = 2; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; core.update(.{ .key = .{ .cp = '|' } }); core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); core.update(.{ .key = .{ .cp = pardes.Key.enter } }); @@ -1607,7 +1607,7 @@ test "keypad Enter matches Return for editor input terminal writes and paste" { { const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer core.deinit(); - core.panes[0].?.mode = .tty; + core.panes[0].?.body.mode = .tty; while (core.nextEffect()) |_| {} core.update(event); var written: std.Io.Writer.Allocating = .init(std.testing.allocator); diff --git a/test/fs_bench.zig b/test/fs_bench.zig index 00601ca3..a816ebbd 100644 --- a/test/fs_bench.zig +++ b/test/fs_bench.zig @@ -281,7 +281,7 @@ pub fn main(init: std.process.Init) !void { var keys = try Session.init(&counting, 32 * 1024); defer keys.deinit(); const pane = keys.core.panes[keys.file_id].?; - pane.mode = .insert; + pane.body.mode = .insert; const initial_bytes = pane.file.?.content.len; key_body_bytes = initial_bytes; if (scripted) { @@ -295,7 +295,7 @@ pub fn main(init: std.process.Init) !void { while (keys.core.nextEffect()) |_| {} } const elapsed = nowNs() - start; - if (pane.file.?.content.len != initial_bytes + key_reps or pane.cur_col != key_reps or + if (pane.file.?.content.len != initial_bytes + key_reps or pane.body.cur_col != key_reps or !std.mem.allEqual(u8, pane.file.?.content[0..key_reps], 'x')) return error.MissingKeystroke; const events = &keys.core.panes[keys.file_id].?.fs.events; if (scripted) for (0..key_reps) |i| { diff --git a/test/hxdiff.zig b/test/hxdiff.zig index e79a6bb6..627bbac3 100644 --- a/test/hxdiff.zig +++ b/test/hxdiff.zig @@ -397,9 +397,9 @@ fn runCase(arena: std.mem.Allocator, case: Case, pane_kind: []const u8) !Result core.update(.{ .key = .{ .cp = core.opts.tty_toggle, .ctrl = true } }); pump(core); if (core.panes[core.active]) |pane| { - pane.cur_row = 0; - pane.cur_col = 0; - pane.cur_pinned = true; + pane.body.cur_row = 0; + pane.body.cur_col = 0; + pane.body.cur_pinned = true; } } else fatal("case {s}: unknown pane {s}", .{ case.name, pane_kind }); @@ -488,7 +488,7 @@ fn runCase(arena: std.mem.Allocator, case: Case, pane_kind: []const u8) !Result // the cursor's empty row below the output (see Pardes.shellRows), so // its line list is exactly a file content's — join it and you have the // same bytes, trailing newline included, with nothing to patch up. - const lines = try pardes.edit.paneCursorLines(core, pane); + const lines = try pardes.edit.paneCursorLines(core, &pane.body); var text_len: usize = if (lines.len == 0) 0 else lines.len - 1; for (lines) |ln| text_len = std.math.add(usize, text_len, ln.len) catch return error.OutOfMemory; const joined = try arena.alloc(u8, text_len); @@ -503,28 +503,28 @@ fn runCase(arena: std.mem.Allocator, case: Case, pane_kind: []const u8) !Result } text = joined; } - var anchor: Pos = .{ .row = pane.cur_row, .col = pane.cur_col }; - if (pane.vsel.active) { - anchor = .{ .row = pane.vsel.row, .col = pane.vsel.col }; - } else if (pane.msel.active) { + var anchor: Pos = .{ .row = pane.body.cur_row, .col = pane.body.cur_col }; + if (pane.body.vsel.active) { + anchor = .{ .row = pane.body.vsel.row, .col = pane.body.vsel.col }; + } else if (pane.body.msel.active) { // line selection: the far end (the r0/r1 not holding the cursor), col 0 - anchor = .{ .row = if (pane.cur_row == pane.msel.r1) pane.msel.r0 else pane.msel.r1, .col = 0 }; + anchor = .{ .row = if (pane.body.cur_row == pane.body.msel.r1) pane.body.msel.r0 else pane.body.msel.r1, .col = 0 }; } // mode "select" ONLY while v-extend is on (helix keeps x/%/mi selections - // in normal mode); pane.mode itself never holds a select state - const mode = if (pane.mode == .normal and pane.select) "select" else @tagName(pane.mode); + // in normal mode); pane.body.mode itself never holds a select state + const mode = if (pane.body.mode == .normal and pane.body.select) "select" else @tagName(pane.body.mode); // multiple cursors: the primary (cur_row/cur_col + the anchor above) and - // pane.sels, slotted together in document order. pane.sels is already + // pane.body.sels, slotted together in document order. pane.body.sels is already // ordered, so the primary is the only one that needs placing. var sels: ?[]const Sel = null; var primary: ?usize = null; - if (pane.nsel > 0) { - const out = try arena.alloc(Sel, @as(usize, pane.nsel) + 1); + if (pane.body.nsel > 0) { + const out = try arena.alloc(Sel, @as(usize, pane.body.nsel) + 1); var out_len: usize = 0; - const prim: Sel = .{ .cursor = .{ .row = pane.cur_row, .col = pane.cur_col }, .anchor = anchor }; + const prim: Sel = .{ .cursor = .{ .row = pane.body.cur_row, .col = pane.body.cur_col }, .anchor = anchor }; const pr_row = @min(prim.cursor.row, prim.anchor.row); const pr_col = if (prim.cursor.row == prim.anchor.row) @min(prim.cursor.col, prim.anchor.col) else if (prim.cursor.row < prim.anchor.row) prim.cursor.col else prim.anchor.col; - for (pane.sels[0..pane.nsel]) |s| { + for (pane.body.sels[0..pane.body.nsel]) |s| { const s_row = @min(s.row, s.arow); const s_col = if (s.row == s.arow) @min(s.col, s.acol) else if (s.row < s.arow) s.col else s.acol; if (primary == null and (pr_row < s_row or (pr_row == s_row and pr_col <= s_col))) { @@ -545,7 +545,7 @@ fn runCase(arena: std.mem.Allocator, case: Case, pane_kind: []const u8) !Result .name = case.name, .text = try arena.dupe(u8, text), .mode = mode, - .cursor = .{ .row = pane.cur_row, .col = pane.cur_col }, + .cursor = .{ .row = pane.body.cur_row, .col = pane.body.cur_col }, .anchor = anchor, .sels = sels, .primary = primary, diff --git a/test/mode.zig b/test/mode.zig index cc36ac04..19d59699 100644 --- a/test/mode.zig +++ b/test/mode.zig @@ -3,9 +3,9 @@ const pardes = @import("pardes"); const panes = pardes.panes; const Pardes = pardes.Pardes; -fn mode(p: *Pardes, id: usize, expected: pardes.Pane.Mode) !void { +fn mode(p: *Pardes, id: usize, expected: panes.Text.Mode) !void { try std.testing.expect(p.executeBuiltinLine(id, "Mode")); - try std.testing.expectEqual(expected, p.panes[id].?.mode); + try std.testing.expectEqual(expected, p.panes[id].?.body.mode); try std.testing.expect(!p.panes[id].?.tag_edit); } @@ -33,14 +33,14 @@ test "Mode cycles terminal modes and keeps legacy toggle and custom tags" { p.presentation.enabled = false; while (p.nextEffect()) |_| {} const pane = p.panes[0].?; - try std.testing.expectEqual(pardes.Pane.Mode.tty, pane.mode); + try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); try std.testing.expect(std.mem.indexOf(u8, try p.tagText(p.scratch.allocator(), pane), " Mode") != null); try mode(p, 0, .normal); try mode(p, 0, .insert); try clickModeTag(p); - try std.testing.expectEqual(pardes.Pane.Mode.insert, pane.tag_mode); + try std.testing.expectEqual(panes.Text.Mode.insert, pane.tag_mode); p.update(.{ .key = .{ .cp = pardes.Key.tab } }); - try std.testing.expectEqual(pardes.Pane.Mode.tty, pane.mode); + try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); try std.testing.expect(!pane.tag_edit); while (p.nextEffect()) |effect| try std.testing.expect(effect != .write); @@ -48,11 +48,11 @@ test "Mode cycles terminal modes and keeps legacy toggle and custom tags" { try mode(p, 0, .normal); try mode(p, 0, .insert); try std.testing.expect(p.executeBuiltinLine(0, "Togglettymode")); - try std.testing.expectEqual(pardes.Pane.Mode.tty, pane.mode); + try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); p.update(.{ .key = .{ .cp = 'b', .ctrl = true } }); - try std.testing.expectEqual(pardes.Pane.Mode.normal, pane.mode); + try std.testing.expectEqual(panes.Text.Mode.normal, pane.body.mode); p.update(.{ .key = .{ .cp = 'b', .ctrl = true } }); - try std.testing.expectEqual(pardes.Pane.Mode.tty, pane.mode); + try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); try std.testing.expectEqualStrings(" Togglettymode Keep", pane.tag_tail[0..pane.tag_tail_len]); } @@ -71,19 +71,19 @@ test "Mode from actual tag Exec preserves parked file and output insert transact p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); try std.testing.expectEqualStrings("界xab\n", pane.file.?.content); try clickModeTag(p); - try std.testing.expectEqual(pardes.Pane.Mode.insert, pane.tag_mode); - if (normal_tag) pane.mode = .normal; + try std.testing.expectEqual(panes.Text.Mode.insert, pane.tag_mode); + if (normal_tag) pane.body.mode = .normal; p.update(.{ .key = .{ .cp = pardes.Key.tab } }); - try std.testing.expectEqual(pardes.Pane.Mode.normal, pane.mode); + try std.testing.expectEqual(panes.Text.Mode.normal, pane.body.mode); try std.testing.expect(!pane.tag_edit); - try std.testing.expect(pane.append_at == null); + try std.testing.expect(pane.body.append_at == null); p.update(.{ .key = .{ .cp = 'u' } }); try std.testing.expectEqualStrings("ab\n", pane.file.?.content); p.update(.{ .key = .{ .cp = 'a' } }); p.update(.{ .key = .{ .cp = 'z', .text = "z" } }); - try std.testing.expect(pane.append_at != null); + try std.testing.expect(pane.body.append_at != null); try mode(p, 0, .normal); - try std.testing.expect(pane.append_at == null); + try std.testing.expect(pane.body.append_at == null); p.update(.{ .key = .{ .cp = 'u' } }); try std.testing.expectEqualStrings("ab\n", pane.file.?.content); } diff --git a/test/output.zig b/test/output.zig index 7c5f7f9b..c245e5f5 100644 --- a/test/output.zig +++ b/test/output.zig @@ -61,10 +61,10 @@ test "search tint survives wrapping and theme changes while selections remain au light_matches += 1; } try std.testing.expectEqual(@as(usize, 3), light_matches); - pane.mode = .normal; - pane.cur_row = 0; - pane.cur_col = @intCast(std.mem.indexOf(u8, text, "abc").? + 2); - pane.vsel = .{ .active = true, .row = 0, .col = pane.cur_col - 2, .explicit = true }; + pane.body.mode = .normal; + pane.body.cur_row = 0; + pane.body.cur_col = @intCast(std.mem.indexOf(u8, text, "abc").? + 2); + pane.body.vsel = .{ .active = true, .row = 0, .col = pane.body.cur_col - 2, .explicit = true }; const selected = try p.render(frame.allocator()); for (selected.cells) |cell| try std.testing.expect(!std.meta.eql(cell.style.bg, pardes.Color{ .rgb = p.theme().search_bg.? })); @@ -200,46 +200,46 @@ test "reference Look selects the next sorted row from the captured request and k const source = p.panes[0].?; const response = "m.zig:5:5-8 later\nz.zig:1:1 last-file\nm.zig:1:7-10 earlier\nm.zig:3:5-8 current\na.zig:1:1 first-file\nm.zig:4:5-8 next\n"; const sorted = "a.zig:1:1 first-file\nm.zig:1:7-10 earlier\nm.zig:3:5-8 current\nm.zig:4:5-8 next\nm.zig:5:5-8 later\nz.zig:1:1 last-file\n"; - source.cur_row = 2; - source.cur_col = 4; + source.body.cur_row = 2; + source.body.cur_col = 4; p.lspRequest(0, .references, ""); const request = p.lsp_wait.?.id; - source.cur_row = 4; + source.body.cur_row = 4; p.lspResponse(request, response); const rid = source.search_pane orelse return error.MissingResults; const results = p.panes[rid].?; try expectResultRows(sorted, &results.file.?); try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expectEqual(@as(i32, 3), source.cur_row); - try std.testing.expect(source.vsel.active); - try std.testing.expectEqual(@as(i32, 4), @min(source.cur_col, source.vsel.col)); - try std.testing.expectEqual(@as(i32, 7), @max(source.cur_col, source.vsel.col)); - try std.testing.expectEqual(@as(i32, 3), results.cur_row); + try std.testing.expectEqual(@as(i32, 3), source.body.cur_row); + try std.testing.expect(source.body.vsel.active); + try std.testing.expectEqual(@as(i32, 4), @min(source.body.cur_col, source.body.vsel.col)); + try std.testing.expectEqual(@as(i32, 7), @max(source.body.cur_col, source.body.vsel.col)); + try std.testing.expectEqual(@as(i32, 3), results.body.cur_row); try std.testing.expectEqual(@as(usize, 3), source.search_row.?); try std.testing.expectEqual(results.serial, p.look_walk_owner.?); try std.testing.expectEqual(@as(i32, 3), results.look_at.?.row); const available = p.freeSlot(); p.update(.{ .key = .{ .cp = 'n' } }); try std.testing.expectEqual(rid, p.active); - try std.testing.expectEqual(@as(i32, 4), results.cur_row); + try std.testing.expectEqual(@as(i32, 4), results.body.cur_row); try std.testing.expectEqual(available, p.freeSlot()); p.update(.{ .key = .{ .cp = 'N' } }); - try std.testing.expectEqual(@as(i32, 3), results.cur_row); + try std.testing.expectEqual(@as(i32, 3), results.body.cur_row); p.active = 0; - source.cur_row = 4; - source.cur_col = 4; + source.body.cur_row = 4; + source.body.cur_col = 4; p.lspRequest(0, .references, ""); p.lspResponse(p.lsp_wait.?.id, response); try std.testing.expect(std.mem.endsWith(u8, p.panes[p.active].?.file.?.path, "/z.zig")); - try std.testing.expectEqual(@as(i32, 5), results.cur_row); + try std.testing.expectEqual(@as(i32, 5), results.body.cur_row); try std.testing.expectEqual(@as(usize, 5), source.search_row.?); const last = p.active; p.lspRequest(last, .references, ""); p.lspResponse(p.lsp_wait.?.id, response); try std.testing.expect(std.mem.endsWith(u8, p.panes[p.active].?.file.?.path, "/a.zig")); const wrapped = p.panes[p.panes[last].?.search_pane.?].?; - try std.testing.expectEqual(@as(i32, 0), wrapped.cur_row); + try std.testing.expectEqual(@as(i32, 0), wrapped.body.cur_row); try std.testing.expectEqual(wrapped.serial, p.look_walk_owner.?); } @@ -280,7 +280,7 @@ test "a single language location opens the full spaced filename" { p.lspRequest(0, .references, ""); p.lspResponse(p.lsp_wait.?.id, "with space.zig:2:1 second\n"); try std.testing.expect(std.mem.endsWith(u8, p.panes[p.active].?.file.?.path, "/with space.zig")); - try std.testing.expectEqual(@as(i32, 1), p.panes[p.active].?.cur_row); + try std.testing.expectEqual(@as(i32, 1), p.panes[p.active].?.body.cur_row); for (p.panes) |slot| { const pane = slot orelse continue; if (pane.file) |file| try std.testing.expect(file.output == null); @@ -316,19 +316,19 @@ test "reordered identical results preserve the selected row and warm line index" const index = try panes.File.lineIndex(p.gpa, file); const content = file.content.ptr; const revision = file.revision; - result.cur_row = 1; - result.cur_col = 0; - result.vsel = .{ .active = true, .explicit = true, .row = 1, .col = 9 }; - result.select = true; - const selected = result.vsel; + result.body.cur_row = 1; + result.body.cur_col = 0; + result.body.vsel = .{ .active = true, .explicit = true, .row = 1, .col = 9 }; + result.body.select = true; + const selected = result.body.vsel; try panes.Output.fillResults(p, 0, "/tmp", .{ .query = .references }, "new request", try p.gpa.dupe(u8, "a.zig:10:1 second\na.zig:2:1 first\n"), 0); try expectResultRows(sorted, file); try std.testing.expectEqual(content, file.content.ptr); try std.testing.expectEqual(index.ptr, file.line_starts.ptr); try std.testing.expectEqual(revision, file.revision); - try std.testing.expectEqual(selected, result.vsel); - try std.testing.expect(result.select); - try std.testing.expectEqual(@as(i32, 1), result.cur_row); + try std.testing.expectEqual(selected, result.body.vsel); + try std.testing.expect(result.body.select); + try std.testing.expectEqual(@as(i32, 1), result.body.cur_row); try std.testing.expectEqual(@as(usize, 1), source.search_row.?); } @@ -390,7 +390,7 @@ test "result stepping reaches an unterminated last row" { try std.testing.expect(pardes.test_api.searchStep(p, 0, 1)); try std.testing.expectEqual(@as(usize, 1), source.search_row.?); const result = p.panes[source.search_pane.?].?; - try std.testing.expectEqual(@as(i32, 1), result.cur_row); + try std.testing.expectEqual(@as(i32, 1), result.body.cur_row); } test "Mini uses OS source precedence and refreshes one independent snapshot" { @@ -708,10 +708,10 @@ fn projectPaths(cwd_buf: *[4096]u8, path_buf: *[4096]u8) !ProjectPaths { fn selectedOutputText(pane: *const pardes.Pane) ?[]const u8 { const file = pane.file orelse return null; - if (!pane.vsel.active or pane.vsel.row != pane.cur_row or pane.cur_row < 0) return null; - const line = modal.lineSlice(file.content, @intCast(pane.cur_row)); - const lo: usize = @intCast(@max(0, @min(pane.vsel.col, pane.cur_col))); - const hi: usize = @intCast(@max(0, @max(pane.vsel.col, pane.cur_col))); + if (!pane.body.vsel.active or pane.body.vsel.row != pane.body.cur_row or pane.body.cur_row < 0) return null; + const line = modal.lineSlice(file.content, @intCast(pane.body.cur_row)); + const lo: usize = @intCast(@max(0, @min(pane.body.vsel.col, pane.body.cur_col))); + const hi: usize = @intCast(@max(0, @max(pane.body.vsel.col, pane.body.cur_col))); if (lo >= line.len) return ""; return line[lo..@min(line.len, hi + 1)]; } @@ -735,7 +735,7 @@ test "n/N in ordinary text skips comment slashes and retains real paths" { }) |step| { p.update(.{ .key = .{ .cp = step.key } }); try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expectEqual(step.row, pane.cur_row); + try std.testing.expectEqual(step.row, pane.body.cur_row); try std.testing.expectEqualStrings(step.text, selectedOutputText(pane) orelse ""); try std.testing.expectEqual(available, p.freeSlot()); } @@ -788,7 +788,7 @@ test "n/N skips formatted context and selects comment match locations" { p.update(.{ .key = .{ .cp = step.key } }); try std.testing.expectEqual(id, p.active); const row = matches[step.match]; - try std.testing.expectEqual(@as(i32, @intCast(row)), result.cur_row); + try std.testing.expectEqual(@as(i32, @intCast(row)), result.body.cur_row); const line = modal.lineSlice(file.content, row); try std.testing.expectEqualStrings(line[0..file.location_rows[row].location_end], selectedOutputText(result) orelse ""); try std.testing.expectEqual(available, p.freeSlot()); @@ -799,9 +799,9 @@ test "n/N skips formatted context and selects comment match locations" { pardes.look.armLookWalk(restored, id); const restored_result = restored.panes[id].?; restored.update(.{ .key = .{ .cp = 'n' } }); - try std.testing.expectEqual(@as(i32, @intCast(matches[0])), restored_result.cur_row); + try std.testing.expectEqual(@as(i32, @intCast(matches[0])), restored_result.body.cur_row); restored.update(.{ .key = .{ .cp = 'N' } }); - try std.testing.expectEqual(@as(i32, @intCast(matches[1])), restored_result.cur_row); + try std.testing.expectEqual(@as(i32, @intCast(matches[1])), restored_result.body.cur_row); const restored_file = &restored_result.file.?; const last = modal.lineSlice(restored_file.content, matches[1]); try std.testing.expectEqualStrings(last[0..restored_file.location_rows[matches[1]].location_end], selectedOutputText(restored_result) orelse ""); @@ -825,18 +825,18 @@ test "n/N selects one output location per row and opens nothing" { p.update(.{ .key = .{ .cp = 'n' } }); try std.testing.expectEqual(rid, p.active); try std.testing.expectEqual(panes_before, p.freeSlot()); - try std.testing.expect(results.vsel.active and results.vsel.explicit); + try std.testing.expect(results.body.vsel.active and results.body.vsel.explicit); try std.testing.expectEqualStrings("build.zig:1:1", selectedOutputText(results) orelse ""); try std.testing.expectEqual(panes.Output.Grain.line, panes.Output.grain(results.file.?.output)); p.update(.{ .key = .{ .cp = 'n' } }); - try std.testing.expectEqual(@as(i32, 1), results.cur_row); + try std.testing.expectEqual(@as(i32, 1), results.body.cur_row); try std.testing.expectEqualStrings("mise.toml", selectedOutputText(results) orelse ""); p.update(.{ .key = .{ .cp = 'n' } }); - try std.testing.expectEqual(@as(i32, 3), results.cur_row); // row 2 is not look-able + try std.testing.expectEqual(@as(i32, 3), results.body.cur_row); // row 2 is not look-able try std.testing.expectEqualStrings("uucode_config.zig:7:1", selectedOutputText(results) orelse ""); p.update(.{ .key = .{ .cp = 'n' } }); - try std.testing.expectEqual(@as(i32, 0), results.cur_row); // ring seam + try std.testing.expectEqual(@as(i32, 0), results.body.cur_row); // ring seam p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expect(p.freeSlot() != panes_before); @@ -861,16 +861,16 @@ test "n/N resumes the result output whose Look moved focus away" { try std.testing.expect(p.executeBuiltinLine(0, "Look target")); const rid = p.panes[0].?.search_pane orelse return error.MissingResults; const results = p.panes[rid].?; - const first = results.cur_row; + const first = results.body.cur_row; try std.testing.expectEqual(@as(usize, 0), p.active); try std.testing.expect(results.look_at != null); try std.testing.expectEqual(results.serial, p.look_walk_owner orelse return error.MissingLookOwner); p.update(.{ .key = .{ .cp = 'n' } }); try std.testing.expectEqual(rid, p.active); - try std.testing.expectEqual(first + 1, results.cur_row); + try std.testing.expectEqual(first + 1, results.body.cur_row); p.update(.{ .key = .{ .cp = 'N' } }); - try std.testing.expectEqual(first, results.cur_row); + try std.testing.expectEqual(first, results.body.cur_row); // A later no-match answer has no position to resume and therefore cannot // steal the provenance established by the Look above. @@ -888,7 +888,7 @@ test "n/N resumes the result output whose Look moved focus away" { try std.testing.expectEqual(owner, p.look_walk_owner.?); p.update(.{ .key = .{ .cp = 'n' } }); try std.testing.expectEqual(rid, p.active); - try std.testing.expectEqual(first + 1, results.cur_row); + try std.testing.expectEqual(first + 1, results.body.cur_row); // Emptying the owner itself keeps its identity as the ring's starting // point. Deleting it then leaves a stale serial, never an id that can bind @@ -920,7 +920,7 @@ test "N exactly reverses n across output panes and the ring seam" { const here = struct { fn at(pp: *Pardes) Mark { const pane = pp.panes[pp.active].?; - return .{ .pane = pp.active, .row = pane.cur_row, .col = pane.cur_col }; + return .{ .pane = pp.active, .row = pane.body.cur_row, .col = pane.body.cur_col }; } }.at; p.update(.{ .key = .{ .cp = 'n' } }); @@ -957,7 +957,7 @@ test "ThemeSel groups native themes first and skips headings in both directions" const list = p.panes[tid].?; const content = list.file.?.content; try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expectEqual(@as(i32, 0), list.cur_row); + try std.testing.expectEqual(@as(i32, 0), list.body.cur_row); try std.testing.expectEqual(@as(usize, 0), list.file.?.scroll); try std.testing.expectEqualStrings("# Pardes themes", modal.lineSlice(content, 0)); try std.testing.expectEqualStrings("# Legacy and imported themes", modal.lineSlice(content, pardes.native_theme_count + 2)); @@ -1024,10 +1024,10 @@ test "identical result refresh keeps warm content caches without allocation" { const id = source.search_pane orelse return error.MissingResults; const result = p.panes[id].?; const file = &result.file.?; - result.cur_row = 1; - result.cur_col = 12; - result.vsel = .{ .active = true, .explicit = true, .row = 0, .col = 2 }; - result.select = true; + result.body.cur_row = 1; + result.body.cur_col = 12; + result.body.vsel = .{ .active = true, .explicit = true, .row = 0, .col = 2 }; + result.body.select = true; file.scroll = 1; result.hscroll = 3; panes.File.refreshHighlights(p); @@ -1040,7 +1040,7 @@ test "identical result refresh keeps warm content caches without allocation" { const body_ptr = file.content.ptr; const style_ptr = file.highlights.ptr; const highlight_start = file.highlight_start; - const selected = result.vsel; + const selected = result.body.vsel; const event_node = pardes.ctlfs.Node.of(result.serial, .event); const opened = pardes.ctlfs.handle(p, .{ .tag = 0, .op = .open, .node = event_node }); try std.testing.expectEqual(.ok, opened.status); @@ -1071,10 +1071,10 @@ test "identical result refresh keeps warm content caches without allocation" { try std.testing.expectEqual(freed + text.len, allocator.freed_bytes); try std.testing.expectEqual(deallocations + 1, allocator.deallocations); try std.testing.expect(!allocator.has_induced_failure); - try std.testing.expectEqual(selected, result.vsel); - try std.testing.expect(result.select); - try std.testing.expectEqual(@as(i32, 1), result.cur_row); - try std.testing.expectEqual(@as(i32, 12), result.cur_col); + try std.testing.expectEqual(selected, result.body.vsel); + try std.testing.expect(result.body.select); + try std.testing.expectEqual(@as(i32, 1), result.body.cur_row); + try std.testing.expectEqual(@as(i32, 12), result.body.cur_col); try std.testing.expectEqual(@as(usize, 1), file.scroll); try std.testing.expectEqual(@as(i32, 3), result.hscroll); try std.testing.expectEqualStrings("after", file.output.?.arg()); @@ -1093,9 +1093,9 @@ test "identical result refresh keeps warm content caches without allocation" { try std.testing.expectEqualSlices(usize, &.{ 0, 6 }, file.line_starts); try std.testing.expectEqual(@as(usize, 0), file.highlights.len); try std.testing.expect(file.syntax_dirty); - try std.testing.expect(!result.vsel.active and !result.select); - try std.testing.expectEqual(@as(i32, 0), result.cur_row); - try std.testing.expectEqual(@as(i32, 0), result.cur_col); + try std.testing.expect(!result.body.vsel.active and !result.body.select); + try std.testing.expectEqual(@as(i32, 0), result.body.cur_row); + try std.testing.expectEqual(@as(i32, 0), result.body.cur_col); try std.testing.expectEqual(@as(usize, 0), file.scroll); try std.testing.expectEqual(@as(i32, 0), result.hscroll); try std.testing.expect(source.search_row == null); @@ -1211,15 +1211,15 @@ test "result alignment chunks keep seventeen matches independent and refresh sta const content = file.content.ptr; const revision = file.revision; const index = try panes.File.lineIndex(p.gpa, file); - result.cur_row = 8; - result.cur_col = @intCast(file.location_rows[8].code_start); + result.body.cur_row = 8; + result.body.cur_col = @intCast(file.location_rows[8].code_start); try panes.Output.fillResults(p, 0, "/", origin, "chunks", try p.gpa.dupe(u8, input.items), 8); try std.testing.expectEqual(result_id, source.search_pane.?); try std.testing.expectEqual(content, file.content.ptr); try std.testing.expectEqual(revision, file.revision); try std.testing.expectEqual(index.ptr, file.line_starts.ptr); try std.testing.expectEqual(@as(usize, 8), source.search_row.?); - try std.testing.expectEqual(@as(i32, 8), result.cur_row); + try std.testing.expectEqual(@as(i32, 8), result.body.cur_row); for (file.location_rows, starts) |row, start| try std.testing.expectEqual(start, row.code_start); // Simulate a restored view made by the previous global-padding @@ -1561,11 +1561,11 @@ test "stacked search and LSP results retain source tint navigation and dump owne const number = std.mem.indexOf(u8, file.content, "42").?; try std.testing.expectEqual(@intFromEnum(pardes.syntax.Syn.number), file.highlights[number]); p.active = id; - pane.mode = .normal; + pane.body.mode = .normal; pardes.look.armLookWalk(p, id); for ([_]struct { key: u21, match: usize }{ .{ .key = 'n', .match = 0 }, .{ .key = 'n', .match = 1 }, .{ .key = 'N', .match = 0 } }) |step| { p.update(.{ .key = .{ .cp = step.key } }); - try std.testing.expectEqual(@as(i32, @intCast(matches[step.match])), pane.cur_row); + try std.testing.expectEqual(@as(i32, @intCast(matches[step.match])), pane.body.cur_row); const row = file.location_rows[matches[step.match]]; const line = modal.lineSlice(file.content, matches[step.match]); try std.testing.expectEqualStrings(line[0..row.location_end], selectedOutputText(pane) orelse ""); @@ -1587,7 +1587,7 @@ test "stacked search and LSP results retain source tint navigation and dump owne restored.active = id; pardes.look.armLookWalk(restored, id); restored.update(.{ .key = .{ .cp = 'N' } }); - try std.testing.expectEqual(@as(i32, @intCast(matches[1])), restored.panes[id].?.cur_row); + try std.testing.expectEqual(@as(i32, @intCast(matches[1])), restored.panes[id].?.body.cur_row); try std.testing.expectEqualStrings(source_text, source.file.?.content); } } diff --git a/test/panes.zig b/test/panes.zig index 60dabb8a..4c969ab5 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -327,14 +327,14 @@ const TagNavigationTests = struct { key(p, 'i'); key(p, Key.end); const before = pane.tag_tail_len; - try std.testing.expect(pane.tag_edit and pane.mode == .insert); + try std.testing.expect(pane.tag_edit and pane.body.mode == .insert); for ("hjklHJKL") |letter| { const text = [_]u8{letter}; p.update(.{ .key = .{ .cp = letter, .text = &text } }); - try std.testing.expect(pane.tag_edit and pane.mode == .insert); + try std.testing.expect(pane.tag_edit and pane.body.mode == .insert); } try std.testing.expectEqualStrings("hjklHJKL", pane.tag_tail[before..pane.tag_tail_len]); - try std.testing.expect(pane.tag_edit and pane.mode == .insert and p.topbar_col == null); + try std.testing.expect(pane.tag_edit and pane.body.mode == .insert and p.topbar_col == null); try std.testing.expectEqual(@as(usize, 0), p.active); } } @@ -370,7 +370,7 @@ const BodyHitTests = struct { const expected = pane.wrapAt(row).line; p.update(.{ .mouse = mouse(layer, row, 2, .press) }); p.update(.{ .mouse = mouse(layer, row, 2, .release) }); - try std.testing.expectEqual(expected, pane.cur_row); + try std.testing.expectEqual(expected, pane.body.cur_row); try std.testing.expectEqual(top, pane.scroll()); } const last = pane.body_visible_rows - 1; @@ -383,11 +383,11 @@ const BodyHitTests = struct { try std.testing.expectEqualStrings("body\nbody", pardes.test_api.heldSelection(p, 0).?); p.update(.{ .mouse = mouse(layer, last, 10, .press) }); p.update(.{ .mouse = mouse(layer, last, 10, .release) }); - try std.testing.expectEqual(expected, pane.cur_row); + try std.testing.expectEqual(expected, pane.body.cur_row); var stale = mouse(layer, 0, 2, .press); stale.body_hit.?.serial +%= 1; p.update(.{ .mouse = stale }); - try std.testing.expectEqual(expected, pane.cur_row); + try std.testing.expectEqual(expected, pane.body.cur_row); p.update(.{ .key = .{ .cp = 'i' } }); p.update(.{ .key = .{ .cp = 'X', .text = "X" } }); try std.testing.expect(std.mem.indexOfScalar(u8, modal.lineSlice(pane.file.?.content, @intCast(expected)), 'X') != null); @@ -425,7 +425,7 @@ const LineNumberLookTests = struct { release.button = .right; p.update(.{ .mouse = press }); p.update(.{ .mouse = release }); - try std.testing.expectEqual(expected, pane.cur_row); + try std.testing.expectEqual(expected, pane.body.cur_row); } } }; @@ -496,9 +496,9 @@ const TreeContextTests = struct { try std.testing.expectEqual(@as(i32, 0), pane.scroll()); pardes.look.lookAt(p, 0, "/tree-context.zig:60"); try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expectEqual(@as(i32, 59), pane.cur_row); + try std.testing.expectEqual(@as(i32, 59), pane.body.cur_row); const surface = try p.render(frame.allocator()); - const visible = pane.wrapRow(pane.cur_row, pane.cur_col); + const visible = pane.wrapRow(pane.body.cur_row, pane.body.cur_col); try std.testing.expect(visible.row >= pane.context_rows); try std.testing.expect(visible.row < pane.rows); try std.testing.expectEqual(@as(i32, 59), pane.wrapAt(visible.row).line); @@ -528,8 +528,8 @@ const TreeContextTests = struct { const x = rect.x + config.GUTTER + panes.File.gutterWidth(pane); const y = p.bodyTop(rect); ClickCursorTests.click(p, .left, x + 6, y); - try std.testing.expectEqual(@as(i32, 0), pane.cur_row); - try std.testing.expectEqual(@as(i32, 6), pane.cur_col); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, 6), pane.body.cur_col); try std.testing.expectEqual(@as(i32, 7), pane.scroll()); const cursor = (try p.render(frame.allocator())).cursor orelse return error.MissingContextCursor; try std.testing.expectEqual(x + 6, cursor.x); @@ -552,7 +552,7 @@ const TreeContextTests = struct { try std.testing.expectEqual(pane.scroll(), pane.wrapAt(pane.context_rows).line); } try std.testing.expectEqual(@as(u16, 0), pane.context_rows); - try std.testing.expectEqual(@as(i32, 0), pane.wrapRow(0, pane.cur_col).row); + try std.testing.expectEqual(@as(i32, 0), pane.wrapRow(0, pane.body.cur_col).row); try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); pane.scrollBy(7); _ = try p.render(frame.allocator()); @@ -581,8 +581,8 @@ const TreeContextTests = struct { } const x = glyph_x orelse return error.MissingContextUnicode; ClickCursorTests.click(p, .left, x + 1, y); - try std.testing.expectEqual(@as(i32, 0), pane.cur_row); - try std.testing.expectEqual(@as(i32, 9), pane.cur_col); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, 9), pane.body.cur_col); try std.testing.expectEqual(@as(i32, 8), pane.scroll()); const cursor = (try p.render(frame.allocator())).cursor orelse return error.MissingContextCursor; try std.testing.expectEqual(x, cursor.x); @@ -617,8 +617,8 @@ const TreeContextTests = struct { }; const glyph = target orelse return error.MissingWrappedContextBody; ClickCursorTests.click(p, .left, glyph.x + 1, glyph.y); - try std.testing.expectEqual(@as(i32, 2), pane.cur_row); - try std.testing.expectEqual(@as(i32, @intCast(std.mem.indexOf(u8, body, "界").?)), pane.cur_col); + try std.testing.expectEqual(@as(i32, 2), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, @intCast(std.mem.indexOf(u8, body, "界").?)), pane.body.cur_col); const cursor = (try p.render(frame.allocator())).cursor orelse return error.MissingContextBodyCursor; try std.testing.expectEqual(glyph.x, cursor.x); try std.testing.expectEqual(glyph.y, cursor.y); @@ -652,7 +652,7 @@ const TtySelectionTests = struct { try std.testing.expectEqualStrings("lph", p.yank orelse return error.MissingAutomaticTtyYank); p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); p.update(.{ .key = .{ .cp = 'l' } }); - try std.testing.expectEqual(@as(i32, 4), pane.cur_col); + try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col); p.update(.{ .key = .{ .cp = 'y' } }); try std.testing.expectEqualStrings("a", p.yank.?); try noChildInput(p); @@ -664,7 +664,7 @@ const TtySelectionTests = struct { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); const pane = p.panes[0].?; - pane.mode = .tty; + pane.body.mode = .tty; pane.tty_filter = false; p.presentation.enabled = false; while (p.nextEffect()) |_| {} @@ -680,7 +680,7 @@ const TtySelectionTests = struct { const y = p.bodyTop(rect); JumpSelectionTests.drag(p, x + @as(u16, if (prompt) 0 else 1), y, x + 3, y + @as(u16, if (prompt) 0 else 1)); const expected = if (prompt) "$ ab" else "lph\nrav"; - try std.testing.expectEqual(Pane.Mode.tty, pane.mode); + try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); try std.testing.expectEqualStrings(expected, pardes.test_api.heldSelection(p, 0).?); try std.testing.expectEqualStrings(expected, p.yank orelse return error.MissingAutomaticTtyYank); try noChildInput(p); @@ -689,7 +689,7 @@ const TtySelectionTests = struct { try noChildInput(p); try std.testing.expectEqualStrings(expected, p.fallback.clipboard.items); p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); - try std.testing.expectEqual(Pane.Mode.normal, pane.mode); + try std.testing.expectEqual(panes.Text.Mode.normal, pane.body.mode); const normal = try p.render(frame.allocator()); if (!prompt) { const selection_bg: pardes.Color = .{ .rgb = p.theme().sel_bg }; @@ -701,13 +701,13 @@ const TtySelectionTests = struct { try std.testing.expectEqualStrings(expected, p.yank.?); try noChildInput(p); p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); - try std.testing.expectEqual(Pane.Mode.tty, pane.mode); + try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); try noChildInput(p); _ = try p.render(frame.allocator()); try std.testing.expectEqualStrings(expected, pardes.test_api.heldSelection(p, 0).?); p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;C\x07" ++ "\r\nnew output" ** 30 } }); _ = try p.render(frame.allocator()); - try std.testing.expectEqual(Pane.Mode.tty, pane.mode); + try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); try std.testing.expectEqualStrings(expected, pardes.test_api.heldSelection(p, 0).?); try std.testing.expectEqualStrings(expected, p.yank.?); try noChildInput(p); @@ -723,7 +723,7 @@ const TtySelectionTests = struct { p.presentation.enabled = false; pardes.exec.spawnTty(p, 0); for (p.panes[0..2]) |slot| { - slot.?.mode = .tty; + slot.?.body.mode = .tty; slot.?.tty_filter = false; slot.?.greet = false; slot.?.vweight = 1; @@ -765,8 +765,8 @@ const TtySelectionTests = struct { }); defer p.gpa.free(expected); try std.testing.expectEqualStrings(expected, written.written()); - try std.testing.expectEqual(Pane.Mode.tty, p.panes[0].?.mode); - try std.testing.expectEqual(Pane.Mode.tty, p.panes[1].?.mode); + try std.testing.expectEqual(panes.Text.Mode.tty, p.panes[0].?.body.mode); + try std.testing.expectEqual(panes.Text.Mode.tty, p.panes[1].?.body.mode); try std.testing.expectEqualStrings("lph\nrav", pardes.test_api.heldSelection(p, 0).?); } } @@ -799,7 +799,7 @@ const TtySelectionTests = struct { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); const pane = p.panes[0].?; - try std.testing.expectEqual(Pane.Mode.tty, pane.mode); + try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); if (bracketed) p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h" } }); try std.testing.expectEqual(bracketed, panes.Terminal.bracketedPaste(pane)); p.yank = try p.gpa.dupe(u8, "one\ntwo"); // what a `y` anywhere left behind @@ -867,13 +867,13 @@ const ClickCursorTests = struct { const x = rect.x + config.GUTTER + panes.File.gutterWidth(pane); const y = if (bottom_tag) rect.y else rect.y + pardes.BOX_H; click(p, .left, x + 15, y + case.click_row); - try std.testing.expectEqual(case.row, pane.cur_row); - try std.testing.expectEqual(case.col, pane.cur_col); + try std.testing.expectEqual(case.row, pane.body.cur_row); + try std.testing.expectEqual(case.col, pane.body.cur_col); const clicked = (try p.render(frame.allocator())).cursor orelse return error.MissingClickCursor; try std.testing.expectEqual(x + @as(u16, @intCast(case.col)), clicked.x); try std.testing.expectEqual(y + @as(u16, @intCast(case.row)), clicked.y); if (!already_insert) p.update(.{ .key = .{ .cp = 'i' } }); - try std.testing.expectEqual(Pane.Mode.insert, pane.mode); + try std.testing.expectEqual(panes.Text.Mode.insert, pane.body.mode); const insert = (try p.render(frame.allocator())).cursor orelse return error.MissingInsertCursor; try std.testing.expectEqual(clicked.x, insert.x); try std.testing.expectEqual(clicked.y, insert.y); @@ -906,12 +906,12 @@ const ClickCursorTests = struct { if (wrap) try std.testing.expect(glyph.y > p.rects[0].y + pardes.BOX_H); click(p, .left, glyph.x + 1, glyph.y); const byte = std.mem.indexOf(u8, source, "界").?; - try std.testing.expectEqual(@as(i32, @intCast(byte)), pane.cur_col); + try std.testing.expectEqual(@as(i32, @intCast(byte)), pane.body.cur_col); const clicked = (try p.render(frame.allocator())).cursor orelse return error.MissingClickCursor; try std.testing.expectEqual(glyph.x, clicked.x); try std.testing.expectEqual(glyph.y, clicked.y); if (!already_insert) p.update(.{ .key = .{ .cp = 'i' } }); - try std.testing.expectEqual(Pane.Mode.insert, pane.mode); + try std.testing.expectEqual(panes.Text.Mode.insert, pane.body.mode); const insert = (try p.render(frame.allocator())).cursor orelse return error.MissingInsertCursor; try std.testing.expectEqual(clicked.x, insert.x); try std.testing.expectEqual(clicked.y, insert.y); @@ -1016,10 +1016,10 @@ const JumpSelectionTests = struct { try std.testing.expectEqual(@as(usize, 0), p.jcur); try std.testing.expect(pane.file.?.scroll > 20); try LookResetTests.cleared(pane); - try std.testing.expect(!pane.vsel.active); + try std.testing.expect(!pane.body.vsel.active); try std.testing.expect(pardes.test_api.heldSelection(p, 0) == null); - try std.testing.expectEqual(@as(i32, 59), pane.cur_row); - try std.testing.expectEqual(@as(i32, 0), pane.cur_col); + try std.testing.expectEqual(@as(i32, 59), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_col); // A selection created after Back must also disappear on Forward. // Back announces itself, so the body sits under a notice band now. @@ -1032,10 +1032,10 @@ const JumpSelectionTests = struct { try std.testing.expectEqual(@as(usize, 1), p.jcur); try std.testing.expectEqual(@as(usize, 0), pane.file.?.scroll); try LookResetTests.cleared(pane); - try std.testing.expect(!pane.vsel.active); + try std.testing.expect(!pane.body.vsel.active); try std.testing.expect(pardes.test_api.heldSelection(p, 0) == null); - try std.testing.expectEqual(@as(i32, 0), pane.cur_row); - try std.testing.expectEqual(@as(i32, 0), pane.cur_col); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_col); } test "jump selection clears copied rectangles in both history directions" { @@ -1073,9 +1073,9 @@ const JumpSelectionTests = struct { try std.testing.expectEqual(@as(usize, 0), p.jcur); try LookResetTests.cleared(source); try LookResetTests.cleared(destination); - try std.testing.expect(!source.vsel.active and !destination.vsel.active); - try std.testing.expectEqual(@as(i32, 2), destination.cur_row); - try std.testing.expectEqual(@as(i32, 1), destination.cur_col); + try std.testing.expect(!source.body.vsel.active and !destination.body.vsel.active); + try std.testing.expectEqual(@as(i32, 2), destination.body.cur_row); + try std.testing.expectEqual(@as(i32, 1), destination.body.cur_col); try LookResetTests.seed(source, "new source held text"); try LookResetTests.seed(destination, "new destination held text"); @@ -1084,9 +1084,9 @@ const JumpSelectionTests = struct { try std.testing.expectEqual(@as(usize, 1), p.jcur); try LookResetTests.cleared(source); try LookResetTests.cleared(destination); - try std.testing.expect(!source.vsel.active and !destination.vsel.active); - try std.testing.expectEqual(@as(i32, 1), source.cur_row); - try std.testing.expectEqual(@as(i32, 0), source.cur_col); + try std.testing.expect(!source.body.vsel.active and !destination.body.vsel.active); + try std.testing.expectEqual(@as(i32, 1), source.body.cur_row); + try std.testing.expectEqual(@as(i32, 0), source.body.cur_col); } }; @@ -1395,7 +1395,7 @@ test "terminal overlay recoloring never materializes unrelated history" { const pane = p.panes[0].?; pane.tty_filter = false; for (0..1000) |_| p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[32mcaf\xc3\xa9 \xe7\x95\x8c\x1b[0m\r\n" } }); - pane.mode = .normal; + pane.body.mode = .normal; pane.ovl = .{ .row = 0, .rows = 1, .text = try p.gpa.dupe(u8, "edited history") }; var frame = std.heap.ArenaAllocator.init(testing.allocator); defer frame.deinit(); @@ -1422,7 +1422,7 @@ test "terminal output keeps following new rows after scrollback eviction" { defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; - pane.mode = .tty; + pane.body.mode = .tty; pane.tty_filter = false; const pages = &pane.terminal.?.vt.screens.active.pages; pages.explicit_max_size = 64 * 1024; @@ -1431,7 +1431,7 @@ test "terminal output keeps following new rows after scrollback eviction" { var evictions: usize = 0; for (0..3) |phase| { if (phase > 0) { - pane.mode = .normal; + pane.body.mode = .normal; panes.Terminal.scrollGrid(pane, -30); try std.testing.expect(pages.scrollbar().offset < pages.scrollbar().total - pane.rows); panes.Terminal.enterTty(p, 0); @@ -1483,7 +1483,7 @@ test "terminal edit stays on its surviving row when old scrollback is evicted" { defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; - pane.mode = .tty; + pane.body.mode = .tty; const pages = &pane.terminal.?.vt.screens.active.pages; pages.explicit_max_size = 64 * 1024; var next: usize = 0; @@ -1497,12 +1497,12 @@ test "terminal edit stays on its surviving row when old scrollback is evicted" { try std.testing.expect(next < 3000); var last_buf: [16]u8 = undefined; const last = try std.fmt.bufPrint(&last_buf, "row-{d:0>5}", .{next - 1}); - pane.mode = .normal; + pane.body.mode = .normal; const original_row: i32 = @intCast(pages.scrollbar().total - 2); pane.ovl = .{ .row = original_row, .rows = 1, .text = try gpa.dupe(u8, "my unsent edit") }; - pane.cur_row = original_row; - pane.cur_col = 3; - pane.cur_pinned = true; + pane.body.cur_row = original_row; + pane.body.cur_col = 3; + pane.body.cur_pinned = true; var removed: usize = 0; for (next..next + 3000) |n| { var buf: [32]u8 = undefined; @@ -1520,7 +1520,7 @@ test "terminal edit stays on its surviving row when old scrollback is evicted" { const row = original_row - @as(i32, @intCast(removed)); try std.testing.expectEqualStrings(last, modal.lineSlice(full, @intCast(row))); try std.testing.expectEqual(row, pane.ovl.?.row); - try std.testing.expectEqual(row, pane.cur_row); + try std.testing.expectEqual(row, pane.body.cur_row); try std.testing.expectEqualStrings("my unsent edit", pane.ovl.?.text); } @@ -1533,7 +1533,7 @@ test "terminal edits and undo survive partial history clearing and whole-screen defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; - pane.mode = .tty; + pane.body.mode = .tty; if (action == .reset_alternate) p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?1049h" } }); p.update(.{ .output = .{ .pane = 0, .bytes = "old row\r\n" ** 40 } }); @@ -1541,15 +1541,15 @@ test "terminal edits and undo survive partial history clearing and whole-screen pages.explicit_max_size = 64 * 1024; const row: i32 = @as(i32, @intCast(pages.total_rows - pane.rows)) + @as(i32, if (action == .partial_clear_history) -1 else 2); - pane.mode = .normal; + pane.body.mode = .normal; pane.ovl = .{ .row = row, .rows = if (action == .partial_clear_history) 3 else 2, .text = try gpa.dupe(u8, "edit one\nedit two") }; - pane.cur_row = row + 1; - pane.cur_col = 4; - pane.cur_pinned = true; - pane.vsel = .{ .active = true, .row = row, .col = 1 }; + pane.body.cur_row = row + 1; + pane.body.cur_col = 4; + pane.body.cur_pinned = true; + pane.body.vsel = .{ .active = true, .row = row, .col = 1 }; panes.Terminal.pushUndo(p, pane); - pane.ed_redo[0] = panes.Terminal.snap(p, pane) orelse return error.SnapshotFailed; - pane.ed_redo_len = 1; + pane.body.ed_redo[0] = panes.Terminal.snap(p, pane) orelse return error.SnapshotFailed; + pane.body.ed_redo_len = 1; if (action == .hidden_undo) { gpa.free(pane.ovl.?.text); pane.ovl = null; @@ -1566,10 +1566,10 @@ test "terminal edits and undo survive partial history clearing and whole-screen try std.testing.expectEqual(expected, edit.row); try std.testing.expectEqual(@as(i32, if (action == .clear_history or action == .partial_clear_history) 2 else 1), edit.rows); try std.testing.expectEqualStrings("edit one\nedit two", edit.text); - try std.testing.expectEqual(expected + 1, pane.cur_row); - try std.testing.expectEqual(expected, pane.vsel.row); + try std.testing.expectEqual(expected + 1, pane.body.cur_row); + try std.testing.expectEqual(expected, pane.body.vsel.row); } - for ([_]panes.Terminal.Snapshot{ pane.ed_undo[0], pane.ed_redo[0] }) |snapshot| { + for ([_]panes.Terminal.Snapshot{ pane.body.ed_undo[0], pane.body.ed_redo[0] }) |snapshot| { try std.testing.expectEqual(expected, snapshot.ovl.?.row); try std.testing.expectEqual(expected + 1, snapshot.cur_row); try std.testing.expectEqualStrings("edit one\nedit two", snapshot.ovl.?.text); @@ -1588,11 +1588,11 @@ test "terminal lower scroll regions do not move edits above them" { defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; - pane.mode = .normal; + pane.body.mode = .normal; p.update(.{ .output = .{ .pane = 0, .bytes = "top\r\nsecond\r\nthird" } }); pane.ovl = .{ .row = 1, .rows = 1, .text = try gpa.dupe(u8, "unsent") }; - pane.cur_row = 1; - pane.cur_pinned = true; + pane.body.cur_row = 1; + pane.body.cur_pinned = true; panes.Terminal.pushUndo(p, pane); const total = panes.Terminal.scrollbar(pane).total; var setup: [64]u8 = undefined; @@ -1601,8 +1601,8 @@ test "terminal lower scroll regions do not move edits above them" { p.update(.{ .output = .{ .pane = 0, .bytes = "tail\r\n" ** 50 } }); try std.testing.expectEqual(total, panes.Terminal.scrollbar(pane).total); try std.testing.expectEqual(@as(i32, 1), pane.ovl.?.row); - try std.testing.expectEqual(@as(i32, 1), pane.cur_row); - try std.testing.expectEqual(@as(i32, 1), pane.ed_undo[0].ovl.?.row); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, 1), pane.body.ed_undo[0].ovl.?.row); const full = try panes.Terminal.screenTextAlloc(pane, gpa); defer gpa.free(full); try std.testing.expect(std.mem.startsWith(u8, full, "top\nsecond\nthird\n")); @@ -1615,7 +1615,7 @@ test "terminal eviction and lower-region scrolling in one read preserve a surviv defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; - pane.mode = .tty; + pane.body.mode = .tty; const pages = &pane.terminal.?.vt.screens.active.pages; pages.explicit_max_size = 64 * 1024; var next: usize = 0; @@ -1630,10 +1630,10 @@ test "terminal eviction and lower-region scrolling in one read preserve a surviv try std.testing.expect(next < 3000); const removed = pages.pages.first.?.rows(); const old_row: i32 = @intCast(removed + 2); - pane.mode = .normal; + pane.body.mode = .normal; pane.ovl = .{ .row = old_row, .rows = 1, .text = try gpa.dupe(u8, "kept edit") }; - pane.cur_row = old_row; - pane.cur_pinned = true; + pane.body.cur_row = old_row; + pane.body.cur_pinned = true; panes.Terminal.pushUndo(p, pane); const old_total = pages.total_rows; var buf: [128]u8 = undefined; @@ -1641,8 +1641,8 @@ test "terminal eviction and lower-region scrolling in one read preserve a surviv p.update(.{ .output = .{ .pane = 0, .bytes = bytes } }); try std.testing.expectEqual(old_total + 1 - removed, pages.total_rows); try std.testing.expectEqual(@as(i32, 2), pane.ovl.?.row); - try std.testing.expectEqual(@as(i32, 2), pane.cur_row); - try std.testing.expectEqual(@as(i32, 2), pane.ed_undo[0].ovl.?.row); + try std.testing.expectEqual(@as(i32, 2), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, 2), pane.body.ed_undo[0].ovl.?.row); try std.testing.expectEqualStrings("kept edit", pane.ovl.?.text); } @@ -1667,9 +1667,9 @@ test "tag prompt entry and cancellation preserve exact text and cursor state" { pane.tag_init = true; pane.tag_sel = true; pane.tag_col = 1; - pane.cur_row = 1; - pane.cur_col = 2; - pane.cur_pinned = true; + pane.body.cur_row = 1; + pane.body.cur_col = 2; + pane.body.cur_pinned = true; if (case.key) |key| { p.update(.{ .key = key }); } else if (case.save) { @@ -1679,18 +1679,18 @@ test "tag prompt entry and cancellation preserve exact text and cursor state" { } try std.testing.expect(pane.tag_edit); try std.testing.expect(!pane.tag_sel); - try std.testing.expectEqual(.insert, pane.mode); - try std.testing.expectEqualDeep(modal.Normal.State{}, pane.normal); + try std.testing.expectEqual(.insert, pane.body.mode); + try std.testing.expectEqualDeep(modal.Normal.State{}, pane.body.normal); try std.testing.expectEqualStrings(tail, pane.tag_tail[0..tail.len]); try std.testing.expectEqualStrings(case.marker, pane.tag_tail[tail.len..pane.tag_tail_len]); try std.testing.expectEqual(pane.file.?.path.len + pane.tag_tail_len, pane.tag_col); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expect(pane.prompt == .none); try std.testing.expect(!pane.tag_edit); - try std.testing.expectEqual(.normal, pane.mode); + try std.testing.expectEqual(.normal, pane.body.mode); try std.testing.expectEqualStrings(tail, pane.tag_tail[0..pane.tag_tail_len]); - try std.testing.expectEqual(@as(i32, 1), pane.cur_row); - try std.testing.expectEqual(@as(i32, 2), pane.cur_col); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, 2), pane.body.cur_col); try std.testing.expectEqualStrings("one\ntwo\n", pane.file.?.content); } } @@ -1713,7 +1713,7 @@ test "tag prompt capacity refusal leaves the existing tail and input state untou try std.testing.expect(pane.prompt == .none); try std.testing.expect(!pane.tag_edit); try std.testing.expect(pane.tag_sel); - try std.testing.expectEqual(.normal, pane.mode); + try std.testing.expectEqual(.normal, pane.body.mode); try std.testing.expectEqual(@as(u16, 17), pane.tag_col); try std.testing.expectEqual(pane.tag_tail.len - 1, pane.tag_tail_len); for (pane.tag_tail) |byte| try std.testing.expectEqual(@as(u8, 'x'), byte); @@ -1739,9 +1739,9 @@ test "tag prompt owns the pipe behavior through cancellation and submission" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("one\ntwo\n"); - pane.cur_row = 0; - pane.cur_col = 2; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + pane.body.cur_row = 0; + pane.body.cur_col = 2; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; for (std.enums.values(modal.Normal.PipeBehavior)) |how| { p.startPrompt(pane, .{ .pipe = .append }); p.update(.{ .key = .{ .cp = Key.escape } }); @@ -1767,21 +1767,21 @@ test "tag prompt cancellation restores the selection before regex previews" { .{ .key = 'S', .pattern = " ", .secondary = 2 }, }; for (cases) |case| { - pane.cur_row = 0; - pane.cur_col = 10; - pane.cur_pinned = true; - pane.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; - pane.nsel = 0; + pane.body.cur_row = 0; + pane.body.cur_col = 10; + pane.body.cur_pinned = true; + pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; + pane.body.nsel = 0; p.update(.{ .key = .{ .cp = case.key } }); try std.testing.expect(pane.prompt == .search); p.update(.{ .key = .{ .cp = case.pattern[0], .text = case.pattern } }); - try std.testing.expectEqual(case.secondary, pane.nsel); + try std.testing.expectEqual(case.secondary, pane.body.nsel); p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expectEqual(@as(u8, 0), pane.nsel); + try std.testing.expectEqual(@as(u8, 0), pane.body.nsel); try std.testing.expectEqual(@as(u8, 0), pane.nsel_snap); - try std.testing.expectEqual(@as(i32, 10), pane.cur_col); - try std.testing.expectEqual(@as(i32, 0), pane.vsel.col); - try std.testing.expect(pane.vsel.active and pane.vsel.explicit); + try std.testing.expectEqual(@as(i32, 10), pane.body.cur_col); + try std.testing.expectEqual(@as(i32, 0), pane.body.vsel.col); + try std.testing.expect(pane.body.vsel.active and pane.body.vsel.explicit); try std.testing.expectEqualStrings("one two one", pane.file.?.content); } } @@ -1802,18 +1802,18 @@ test "tag prompt prefix allocation failure preserves an already seeded prompt" { pane.tag_sel = true; pane.tag_col = 14; pane.tag_anchor = 7; - pane.normal = .{ .count = 9, .prefix = .goto }; + pane.body.normal = .{ .count = 9, .prefix = .goto }; const previous_prompt = pane.prompt; - const previous_normal = pane.normal; + const previous_normal = pane.body.normal; _ = p.scratch.reset(.free_all); failing.fail_index = failing.alloc_index; p.startPrompt(pane, request); try std.testing.expect(failing.has_induced_failure); try std.testing.expectEqualDeep(previous_prompt, pane.prompt); - try std.testing.expectEqualDeep(previous_normal, pane.normal); + try std.testing.expectEqualDeep(previous_normal, pane.body.normal); try std.testing.expectEqualStrings(tail, pane.tag_tail[0..pane.tag_tail_len]); try std.testing.expect(pane.tag_edit and pane.tag_sel); - try std.testing.expectEqual(.normal, pane.mode); + try std.testing.expectEqual(.normal, pane.body.mode); try std.testing.expectEqual(@as(u16, 14), pane.tag_col); try std.testing.expectEqual(@as(u16, 7), pane.tag_anchor); } @@ -1867,7 +1867,7 @@ test "tag prompt successful seeded entry needs one scratch allocation" { const before = failing.alloc_index; p.startPrompt(pane, request); try std.testing.expectEqual(before + 1, failing.alloc_index); - try std.testing.expect(pane.tag_edit and pane.mode == .insert); + try std.testing.expect(pane.tag_edit and pane.body.mode == .insert); } } @@ -1892,20 +1892,20 @@ test "tag prompt failure may initialize only the default tail" { pane.tag_tail_len = 0; pane.tag_col = 17; pane.tag_sel = true; - pane.normal = .{ .count = 9, .prefix = .goto }; - const previous_normal = pane.normal; + pane.body.normal = .{ .count = 9, .prefix = .goto }; + const previous_normal = pane.body.normal; _ = p.scratch.reset(.free_all); failing.fail_index = failing.alloc_index + failure; p.startPrompt(pane, request); if (!failing.has_induced_failure) { - try std.testing.expect(pane.tag_edit and pane.mode == .insert); + try std.testing.expect(pane.tag_edit and pane.body.mode == .insert); succeeded = true; break; } try std.testing.expect(pane.prompt == .none); try std.testing.expect(!pane.tag_edit and pane.tag_sel); - try std.testing.expectEqual(.normal, pane.mode); - try std.testing.expectEqualDeep(previous_normal, pane.normal); + try std.testing.expectEqual(.normal, pane.body.mode); + try std.testing.expectEqualDeep(previous_normal, pane.body.normal); try std.testing.expectEqual(@as(u16, 17), pane.tag_col); if (pane.tag_init) { saw_seeded_failure = true; @@ -2390,10 +2390,10 @@ const OutputTests = struct { try std.testing.expectEqual(matches[1], pane.search_row.?); try std.testing.expect(pardes.test_api.searchStep(p, 0, -1)); try std.testing.expectEqual(matches[0], pane.search_row.?); - try std.testing.expectEqual(@as(i32, 3), pane.cur_row); + try std.testing.expectEqual(@as(i32, 3), pane.body.cur_row); try std.testing.expect(pardes.test_api.searchStep(p, 0, 1)); try std.testing.expectEqual(matches[1], pane.search_row.?); - try std.testing.expectEqual(@as(i32, 5), pane.cur_row); + try std.testing.expectEqual(@as(i32, 5), pane.body.cur_row); try std.testing.expect(pardes.test_api.searchStep(p, 0, 1)); try std.testing.expectEqual(matches[1], pane.search_row.?); @@ -2571,9 +2571,9 @@ const OutputTests = struct { const id = p.active; const help = p.panes[id].?; for ("gevkk") |key| p.update(.{ .key = .{ .cp = key } }); - try std.testing.expect(help.vsel.active); - try std.testing.expect(help.vsel.row > 5); - try std.testing.expect(help.cur_row != help.vsel.row); + try std.testing.expect(help.body.vsel.active); + try std.testing.expect(help.body.vsel.row > 5); + try std.testing.expect(help.body.cur_row != help.body.vsel.row); for (" h?") |key| p.update(.{ .key = .{ .cp = key } }); try std.testing.expectEqual(id, p.active); const content = help.file.?.content; @@ -2607,35 +2607,35 @@ const OutputTests = struct { const result = p.panes[id].?; p.active = id; for ("Cv3") |key| p.update(.{ .key = .{ .cp = key } }); - try std.testing.expect(result.nsel > 0); - try std.testing.expect(result.select); - try std.testing.expect(result.vsel.active); - try std.testing.expect(result.normal.count > 0); + try std.testing.expect(result.body.nsel > 0); + try std.testing.expect(result.body.select); + try std.testing.expect(result.body.vsel.active); + try std.testing.expect(result.body.normal.count > 0); result.file.?.scroll = 1; result.hscroll = 2; - const selected = result.vsel; - const selections = result.nsel; - const cursor_row = result.cur_row; - const cursor_col = result.cur_col; + const selected = result.body.vsel; + const selections = result.body.nsel; + const cursor_row = result.body.cur_row; + const cursor_col = result.body.cur_col; try fillResults(p, 0, "/", .{ .query = .hover }, "", try p.gpa.dupe(u8, content), null); - try std.testing.expectEqual(selected, result.vsel); - try std.testing.expectEqual(selections, result.nsel); - try std.testing.expectEqual(cursor_row, result.cur_row); - try std.testing.expectEqual(cursor_col, result.cur_col); + try std.testing.expectEqual(selected, result.body.vsel); + try std.testing.expectEqual(selections, result.body.nsel); + try std.testing.expectEqual(cursor_row, result.body.cur_row); + try std.testing.expectEqual(cursor_col, result.body.cur_col); try std.testing.expectEqual(@as(usize, 1), result.file.?.scroll); try std.testing.expectEqual(@as(i32, 2), result.hscroll); - try std.testing.expect(result.normal.count > 0); + try std.testing.expect(result.body.normal.count > 0); try fillResults(p, 0, "/", .{ .query = .hover }, "", try p.gpa.dupe(u8, "short\n"), null); try std.testing.expectEqualStrings("short\n", result.file.?.content); - try std.testing.expect(!result.vsel.active and !result.msel.active and !result.select); - try std.testing.expectEqual(@as(u8, 0), result.nsel); - try std.testing.expectEqual(@as(i32, 0), result.cur_row); - try std.testing.expectEqual(@as(i32, 0), result.cur_col); + try std.testing.expect(!result.body.vsel.active and !result.body.msel.active and !result.body.select); + try std.testing.expectEqual(@as(u8, 0), result.body.nsel); + try std.testing.expectEqual(@as(i32, 0), result.body.cur_row); + try std.testing.expectEqual(@as(i32, 0), result.body.cur_col); try std.testing.expectEqual(@as(usize, 0), result.file.?.scroll); try std.testing.expectEqual(@as(i32, 0), result.hscroll); - try std.testing.expectEqual(modal.Normal.State{}, result.normal); + try std.testing.expectEqual(modal.Normal.State{}, result.body.normal); } test "generated result replacement cancels an in-progress body selection" { @@ -2665,7 +2665,7 @@ const OutputTests = struct { try std.testing.expect(p.drag == .none); p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = x + 2, .row = y + 1 } }); for (result.sel) |selection| try std.testing.expectEqual(.none, selection.state); - try std.testing.expect(!result.vsel.active and !result.msel.active); + try std.testing.expect(!result.body.vsel.active and !result.body.msel.active); } test "dump origins accept only builtins that actually own output panes" { @@ -2993,8 +2993,8 @@ const TerminalTests = struct { gpa.free(sn.style); }; - for ([_]pardes.Pane.Mode{ .tty, .normal }, 0..) |mode, i| { - pane.mode = mode; + for ([_]panes.Text.Mode{ .tty, .normal }, 0..) |mode, i| { + pane.body.mode = mode; p.shell_rows.stale = true; _ = frame.reset(.retain_capacity); const s = try p.render(frame.allocator()); @@ -3204,7 +3204,7 @@ const TerminalTests = struct { while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tty_filter = false; - pane.mode = .normal; + pane.body.mode = .normal; p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[31mAAA\x1b[0m\r\n\x1b[32mBBB\x1b[0m\r\n\x1b[34mCCC\x1b[0m" } }); @@ -3254,7 +3254,7 @@ const TerminalTests = struct { while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tty_filter = false; - pane.mode = .normal; + pane.body.mode = .normal; // A ONE-cell prompt carrying a combining mark — an NFD `e` — then `ABC` // typed at it. The cell walk that finds the prompt's end must step ONE @@ -3290,7 +3290,7 @@ const TerminalTests = struct { // Raw palette, so a leaked background reads back as `.index` — the theme // filter would repaint every blank cell and hide the evidence. pane.tty_filter = false; - pane.mode = .normal; + pane.body.mode = .normal; // Sixty rows, each a distinct background, so a leaked colour names the row // it leaked from. @@ -3346,7 +3346,7 @@ const TerminalTests = struct { while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tty_filter = false; - pane.mode = .normal; + pane.body.mode = .normal; p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[31mAAA\x1b[0m\r\n\x1b[32mBBB\x1b[0m\r\n\x1b[34mCCC\x1b[0m" } }); @@ -3383,7 +3383,7 @@ const TerminalTests = struct { while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tty_filter = false; - pane.mode = .normal; + pane.body.mode = .normal; p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[31mAAA\x1b[0m\r\n\x1b[32mBBB\x1b[0m\r\n\x1b[34mCCC\x1b[0m" } }); @@ -3459,7 +3459,7 @@ const TerminalTests = struct { while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tty_filter = filter; - pane.mode = .normal; + pane.body.mode = .normal; var buf: [256]u8 = undefined; const bytes = try std.fmt.bufPrint( @@ -3539,7 +3539,7 @@ const TerminalTests = struct { while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tty_filter = false; - pane.mode = .tty; + pane.body.mode = .tty; for (0..60) |i| { var buf: [40]u8 = undefined; @@ -3598,13 +3598,13 @@ const TerminalTests = struct { // ABSOLUTE assertions: both modes were wrong identically here, so a // tty/normal differential says nothing. for ([_]bool{ false, true }) |filter| { - for ([_]pardes.Pane.Mode{ .tty, .normal }) |mode| { + for ([_]panes.Text.Mode{ .tty, .normal }) |mode| { const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 8 }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tty_filter = filter; - pane.mode = mode; + pane.body.mode = mode; p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[32m\u{754C}\x1b[41m\x1b[K\x1b[7G\x1b[44m\x1b[K\r\n" } }); var frame = std.heap.ArenaAllocator.init(testing.allocator); @@ -3634,13 +3634,13 @@ const TerminalTests = struct { // ghostty leaves a `spacer_head` in that last column, carrying the row's // background, and wraps the glyph to the next row. A head OWNS its column, // so skipping it the way a tail is skipped left the row's final column bare. - for ([_]pardes.Pane.Mode{ .tty, .normal }) |mode| { + for ([_]panes.Text.Mode{ .tty, .normal }) |mode| { const p = try Pardes.init(testing.allocator, .{ .startup_config = "Theme helix\n", .tty_only = true, .cols = 16, .rows = 8 }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tty_filter = false; - pane.mode = mode; + pane.body.mode = mode; p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[41mzzzzzzzzzzzzz\u{754C}\x1b[0m\r\n" } }); var frame = std.heap.ArenaAllocator.init(testing.allocator); @@ -3667,7 +3667,7 @@ const TerminalTests = struct { while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tty_filter = false; - pane.mode = .tty; + pane.body.mode = .tty; for (0..40) |i| { var buf: [64]u8 = undefined; const bytes = std.fmt.bufPrint(&buf, "\x1b[38;5;{d}mline-{d:0>2}\x1b[0m\r\n", .{ 20 + i, i }) catch unreachable; @@ -3717,7 +3717,7 @@ const TerminalTests = struct { while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tty_filter = filter; - pane.mode = .normal; + pane.body.mode = .normal; var frame = std.heap.ArenaAllocator.init(testing.allocator); defer frame.deinit(); @@ -3749,7 +3749,7 @@ const TerminalTests = struct { while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tty_filter = false; - pane.mode = .normal; + pane.body.mode = .normal; for (0..6) |i| { var buf: [40]u8 = undefined; @@ -3791,7 +3791,7 @@ const TerminalTests = struct { while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tty_filter = false; - pane.mode = .normal; + pane.body.mode = .normal; p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[31m000\x1b[0m\r\n\x1b[32m111\x1b[0m\r\n\r\n\x1b[34m333\x1b[0m\r\n\x1b[35m444\x1b[0m" } }); @@ -3825,7 +3825,7 @@ const TerminalTests = struct { while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tty_filter = false; - pane.mode = .tty; + pane.body.mode = .tty; p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[31mAAA\x1b[0m\r\n\x1b[32mBBB\x1b[0m\r\n\x1b[34mCCC\x1b[0m" } }); @@ -3862,7 +3862,7 @@ const TerminalTests = struct { while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tty_filter = false; - pane.mode = .normal; + pane.body.mode = .normal; for (0..6) |i| { var buf: [64]u8 = undefined; const bytes = std.fmt.bufPrint(&buf, "\x1b[38;5;{d}mrow-{d}-abcdefgh\x1b[0m\r\n", .{ 30 + i, i }) catch unreachable; @@ -3912,7 +3912,7 @@ const TerminalTests = struct { while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tty_filter = false; - pane.mode = .normal; + pane.body.mode = .normal; for (0..26) |i| { var buf: [64]u8 = undefined; const bytes = std.fmt.bufPrint(&buf, "\x1b[38;5;{d}mrow-{d:0>2}-xyzzy\x1b[0m\r\n", .{ 20 + i, i }) catch unreachable; @@ -3971,7 +3971,7 @@ const TerminalTests = struct { // The raw palette, so a row's text names its exact colour instead of one // this test would have to re-derive from the theme. pane.tty_filter = false; - pane.mode = .normal; + pane.body.mode = .normal; for (0..26) |i| { var buf: [64]u8 = undefined; const bytes = std.fmt.bufPrint(&buf, "\x1b[38;5;{d}mrow-{d:0>2}-xyzzy\x1b[0m\r\n", .{ 20 + i, i }) catch unreachable; @@ -4059,7 +4059,7 @@ const TerminalTests = struct { while (p.nextEffect()) |_| {} const pane = p.panes[0].?; pane.tty_filter = false; - pane.mode = .normal; + pane.body.mode = .normal; for (0..26) |i| { var buf: [64]u8 = undefined; const bytes = std.fmt.bufPrint(&buf, "\x1b[38;5;{d}mrow-{d:0>2}-xyzzy\x1b[0m\r\n", .{ 20 + i, i }) catch unreachable; @@ -4130,9 +4130,9 @@ test "an empty counted paste leaves no count for the next motion" { const pane = try p.setTestFile("abcdefgh\n"); if (empty_register) p.yank = try p.gpa.dupe(u8, ""); for ("3p") |cp| p.update(.{ .key = .{ .cp = cp } }); - try std.testing.expectEqual(modal.Normal.State{}, pane.normal); + try std.testing.expectEqual(modal.Normal.State{}, pane.body.normal); p.update(.{ .key = .{ .cp = 'l' } }); - try std.testing.expectEqual(@as(i32, 1), pane.cur_col); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); try std.testing.expectEqualStrings("abcdefgh\n", pane.file.?.content); } } @@ -4156,7 +4156,7 @@ test "cancelled normal gestures leave no count or subprefix after mouse and focu defer frame.deinit(); _ = try p.render(frame.allocator()); for (keys) |cp| p.update(.{ .key = .{ .cp = cp } }); - try std.testing.expect(!std.meta.eql(modal.Normal.State{}, pane.normal)); + try std.testing.expect(!std.meta.eql(modal.Normal.State{}, pane.body.normal)); switch (gesture) { .body, .tag => { const rect = p.rects[0]; @@ -4185,10 +4185,10 @@ test "cancelled normal gestures leave no count or subprefix after mouse and focu try std.testing.expectEqual(@as(usize, 0), p.active); }, } - try std.testing.expectEqual(modal.Normal.State{}, pane.normal); - const col = pane.cur_col; + try std.testing.expectEqual(modal.Normal.State{}, pane.body.normal); + const col = pane.body.cur_col; p.update(.{ .key = .{ .cp = 'l' } }); - try std.testing.expectEqual(col + 1, pane.cur_col); + try std.testing.expectEqual(col + 1, pane.body.cur_col); try std.testing.expectEqualStrings("abcdefghij\n", pane.file.?.content); } } @@ -4199,16 +4199,16 @@ test "cancelled normal gestures leave no count or subprefix through raw tty mode const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 12 }); defer p.deinit(); const pane = p.panes[0].?; - pane.mode = .normal; + pane.body.mode = .normal; p.update(.{ .output = .{ .pane = 0, .bytes = "abcdefghij\r\n" } }); for (keys) |cp| p.update(.{ .key = .{ .cp = cp } }); - try std.testing.expect(!std.meta.eql(modal.Normal.State{}, pane.normal)); + try std.testing.expect(!std.meta.eql(modal.Normal.State{}, pane.body.normal)); p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); - try std.testing.expectEqual(pardes.Pane.Mode.tty, pane.mode); - try std.testing.expectEqual(modal.Normal.State{}, pane.normal); + try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); + try std.testing.expectEqual(modal.Normal.State{}, pane.body.normal); p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); - try std.testing.expectEqual(pardes.Pane.Mode.normal, pane.mode); - try std.testing.expectEqual(modal.Normal.State{}, pane.normal); + try std.testing.expectEqual(panes.Text.Mode.normal, pane.body.mode); + try std.testing.expectEqual(modal.Normal.State{}, pane.body.normal); } } @@ -4333,8 +4333,8 @@ test "Zig keywords keep every rendered byte colored across line-number widths" { gpa.free(file.path); file.path = try gpa.dupe(u8, "/highlight.zig"); file.scroll = line - 1; - pane.cur_row = @intCast(line - 1); - pane.cur_col = @intCast(std.mem.indexOf(u8, sample, "fn").?); + pane.body.cur_row = @intCast(line - 1); + pane.body.cur_col = @intCast(std.mem.indexOf(u8, sample, "fn").?); pane.hscroll = view.horizontal; p.settings.colors = true; p.settings.wrap = view.wrap; @@ -4373,8 +4373,8 @@ test "Zig keywords keep every rendered byte colored across line-number widths" { const clicked = if_position.?; p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = clicked.x, .row = clicked.y } }); p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = clicked.x, .row = clicked.y } }); - try std.testing.expectEqual(@as(i32, @intCast(line - 1)), pane.cur_row); - try std.testing.expectEqual(@as(i32, @intCast(std.mem.indexOf(u8, sample, "if").?)), pane.cur_col); + try std.testing.expectEqual(@as(i32, @intCast(line - 1)), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, @intCast(std.mem.indexOf(u8, sample, "if").?)), pane.body.cur_col); } } } @@ -4389,7 +4389,7 @@ test "terminal overlays preserve trailing blank styles without coloring inserted const pane = p.panes[0].?; pane.tty_filter = false; p.update(.{ .output = .{ .pane = 0, .bytes = "A\r\n\x1b[41m\x1b[2K\r\n\x1b[42m\x1b[2K\r\n\x1b[44m\x1b[2K\x1b[0m" } }); - pane.mode = .normal; + pane.body.mode = .normal; pane.ovl = .{ .row = 0, .rows = 3, .text = try gpa.dupe(u8, "A\n\n") }; var frame = std.heap.ArenaAllocator.init(gpa); defer frame.deinit(); @@ -4421,16 +4421,16 @@ test "terminal overlays preserve trailing blank styles without coloring inserted const LookResetTests = struct { fn seed(pane: *Pane, operand: []const u8) !void { - pane.cur_row = 0; - pane.cur_col = 3; - pane.vsel = .{ .active = true, .explicit = true, .row = 0, .col = 0 }; - pane.msel = .{ .active = true, .r0 = 0, .r1 = 1 }; - pane.sels[0] = .{ .row = 1, .col = 2, .arow = 0, .acol = 1 }; - pane.nsel = 1; - pane.select = true; - pane.normal.count = 5; - pane.append_at = .{ .row = 0, .col = 3 }; - pane.sticky_col = 7; + pane.body.cur_row = 0; + pane.body.cur_col = 3; + pane.body.vsel = .{ .active = true, .explicit = true, .row = 0, .col = 0 }; + pane.body.msel = .{ .active = true, .r0 = 0, .r1 = 1 }; + pane.body.sels[0] = .{ .row = 1, .col = 2, .arow = 0, .acol = 1 }; + pane.body.nsel = 1; + pane.body.select = true; + pane.body.normal.count = 5; + pane.body.append_at = .{ .row = 0, .col = 3 }; + pane.body.sticky_col = 7; for (0..pane.sel.len) |slot| { pane.clearPointerSelection(slot); pane.sel[slot] = .{ .state = .done, .source_id = slot + 1, .r0 = 1, .r1 = 1, .c0 = 0, .c1 = 3 }; @@ -4445,21 +4445,21 @@ const LookResetTests = struct { } fn cleared(pane: *const Pane) !void { - try std.testing.expect(!pane.msel.active); - try std.testing.expectEqual(@as(u8, 0), pane.nsel); - try std.testing.expect(!pane.select); - try std.testing.expectEqual(modal.Normal.State{}, pane.normal); - try std.testing.expect(pane.append_at == null); - try std.testing.expectEqual(@as(i32, -1), pane.sticky_col); + try std.testing.expect(!pane.body.msel.active); + try std.testing.expectEqual(@as(u8, 0), pane.body.nsel); + try std.testing.expect(!pane.body.select); + try std.testing.expectEqual(modal.Normal.State{}, pane.body.normal); + try std.testing.expect(pane.body.append_at == null); + try std.testing.expectEqual(@as(i32, -1), pane.body.sticky_col); for (pane.sel) |selection| try std.testing.expectEqual(.none, selection.state); for (pane.pointer_selections) |selection| try std.testing.expect(selection == null); } fn selected(pane: *const Pane) []const u8 { - if (!pane.vsel.active or pane.cur_row != pane.vsel.row) return ""; - const line = modal.lineSlice(pane.file.?.content, @intCast(pane.cur_row)); - const lo: usize = @intCast(@min(pane.cur_col, pane.vsel.col)); - const hi: usize = @intCast(@max(pane.cur_col, pane.vsel.col)); + if (!pane.body.vsel.active or pane.body.cur_row != pane.body.vsel.row) return ""; + const line = modal.lineSlice(pane.file.?.content, @intCast(pane.body.cur_row)); + const lo: usize = @intCast(@min(pane.body.cur_col, pane.body.vsel.col)); + const hi: usize = @intCast(@max(pane.body.cur_col, pane.body.vsel.col)); return line[lo..modal.nextGrapheme(line, hi)]; } @@ -4472,14 +4472,14 @@ const LookResetTests = struct { pardes.look.lookAt(p, 0, pane.pointer_selections[0].?.raw_text.?); try cleared(pane); try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expectEqual(@as(i32, 2), pane.cur_row); - try std.testing.expectEqual(@as(i32, 1), pane.cur_col); - try std.testing.expect(!pane.vsel.active); + try std.testing.expectEqual(@as(i32, 2), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); + try std.testing.expect(!pane.body.vsel.active); try seed(pane, "/test.txt:2:2-4"); pardes.look.lookAt(p, 0, pane.pointer_selections[0].?.raw_text.?); try cleared(pane); - try std.testing.expectEqual(@as(i32, 1), pane.cur_row); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); try std.testing.expectEqualStrings("rav", selected(pane)); p.gpa.free(pane.file.?.path); @@ -4487,7 +4487,7 @@ const LookResetTests = struct { try seed(pane, "needle"); pardes.look.lookAt(p, 0, pane.pointer_selections[0].?.raw_text.?); try cleared(pane); - try std.testing.expectEqual(@as(i32, 3), pane.cur_row); + try std.testing.expectEqual(@as(i32, 3), pane.body.cur_row); try std.testing.expectEqualStrings("needle", selected(pane)); } @@ -4512,14 +4512,14 @@ const LookResetTests = struct { try std.testing.expectEqual(id, p.active); try cleared(source); try cleared(destination); - try std.testing.expect(!source.vsel.active); + try std.testing.expect(!source.body.vsel.active); if (range) { - try std.testing.expectEqual(@as(i32, 1), destination.cur_row); + try std.testing.expectEqual(@as(i32, 1), destination.body.cur_row); try std.testing.expectEqualStrings("rav", selected(destination)); } else { - try std.testing.expectEqual(@as(i32, 2), destination.cur_row); - try std.testing.expectEqual(@as(i32, 1), destination.cur_col); - try std.testing.expect(!destination.vsel.active); + try std.testing.expectEqual(@as(i32, 2), destination.body.cur_row); + try std.testing.expectEqual(@as(i32, 1), destination.body.cur_col); + try std.testing.expect(!destination.body.vsel.active); } } } diff --git a/test/pdf.zig b/test/pdf.zig index 8e87dfb1..52fb62aa 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -13,7 +13,7 @@ const Pardes = pardes.Pardes; const Builtin = builtins.registry.Builtin(); const Key = pardes.Key; const Event = pardes.Event; -const Mode = pardes.Pane.Mode; +const Mode = panes.Text.Mode; const Surface = pardes.Surface; const ImagePlace = pardes.ImagePlace; const PdfFitMode = panes.Pdf.FitMode; @@ -457,8 +457,8 @@ test "watched PDF reload replaces MuPDF state and preserves the reading view" { anchor_fraction * @as(f64, @floatFromInt(state.page_heights[2])); state.scroll_to_page_pending = false; state.layout_anchor_pending = false; - pane.cur_row = 9; - pane.cur_col = 8; + pane.body.cur_row = 9; + pane.body.cur_col = 8; try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "live.pdf", .data = replacement }); try std.testing.expect(p.reloadWatchedFile(0, &.{})); @@ -482,8 +482,8 @@ test "watched PDF reload replaces MuPDF state and preserves the reading view" { try std.testing.expect(state.layout_anchor_pending); try std.testing.expectEqual(@as(usize, 2), state.layout_anchor_page); try std.testing.expectApproxEqAbs(anchor_fraction, state.layout_anchor_fraction, 0.0001); - try std.testing.expectEqual(@as(i32, 0), pane.cur_row); - try std.testing.expectEqual(@as(i32, 0), pane.cur_col); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); + try std.testing.expectEqual(@as(i32, 0), pane.body.cur_col); _ = state.ensureText(p.pdf_gpa); const text_lines = std.mem.count(u8, state.text, "\n") + 1; try std.testing.expect(state.text_scroll < text_lines); @@ -690,8 +690,8 @@ test "MuPDF pane renders, navigates, searches, and round-trips its page" { p.update(.{ .key = .{ .cp = '4' } }); p.update(.{ .key = .{ .cp = 'g' } }); p.update(.{ .key = .{ .cp = '?' } }); - try std.testing.expectEqual(.none, pane.normal.prefix); - try std.testing.expectEqual(@as(u32, 0), pane.normal.count); + try std.testing.expectEqual(.none, pane.body.normal.prefix); + try std.testing.expectEqual(@as(u32, 0), pane.body.normal.count); p.update(.{ .key = .{ .cp = 'j' } }); try std.testing.expectEqual(row_scroll, pane.pdf.?.document_scroll_y); @@ -893,9 +893,9 @@ test "MuPDF pane renders, navigates, searches, and round-trips its page" { p.update(.{ .key = .{ .cp = 'n' } }); try std.testing.expectEqual(results_id, p.active); const results_pane = p.panes[results_id].?; - try std.testing.expect(results_pane.vsel.active and results_pane.vsel.explicit); - try std.testing.expectEqual(@as(i32, 0), results_pane.cur_row); - try std.testing.expectEqual(@as(i32, 0), results_pane.cur_col); + try std.testing.expect(results_pane.body.vsel.active and results_pane.body.vsel.explicit); + try std.testing.expectEqual(@as(i32, 0), results_pane.body.cur_row); + try std.testing.expectEqual(@as(i32, 0), results_pane.body.cur_col); p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expectEqual(@as(usize, 0), p.active); try std.testing.expectEqualStrings("Pardes", pane.pdf.?.search_query); @@ -1097,15 +1097,15 @@ test "PDF normal adapter consumes unsupported actions and navigates page fallbac p.update(.{ .key = .{ .cp = '|' } }); try std.testing.expectEqual(page_before_noop, pv.page); try std.testing.expectEqual(revision_before_noop, pv.next_raster_revision); - try std.testing.expectEqual(@as(u32, 0), pane.normal.count); - try std.testing.expectEqual(.none, pane.normal.prefix); - try std.testing.expect(!pane.vsel.active and !pane.msel.active and pane.nsel == 0); + try std.testing.expectEqual(@as(u32, 0), pane.body.normal.count); + try std.testing.expectEqual(.none, pane.body.normal.prefix); + try std.testing.expect(!pane.body.vsel.active and !pane.body.msel.active and pane.body.nsel == 0); try std.testing.expect(!pane.tag_edit); // Cross-pane BODY-NORMAL actions keep their established shared paths. p.update(.{ .key = .{ .cp = ':' } }); try std.testing.expect(pane.tag_edit); - try std.testing.expectEqual(Mode.normal, pane.mode); + try std.testing.expectEqual(Mode.normal, pane.body.mode); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expect(!pane.tag_edit); p.update(.{ .key = .{ .cp = ' ' } }); @@ -1167,8 +1167,8 @@ test "Escape cancels PDF chrome in place and Shift-Escape leaves the pane" { try std.testing.expect(!pv.highlights_dirty and !pv.search_reveal_pending); try std.testing.expectEqual(page_before, pv.page); try std.testing.expectEqual(scroll_before, pv.document_scroll_y); - try std.testing.expectEqual(@as(u32, 0), pane.normal.count); - try std.testing.expectEqual(.none, pane.normal.prefix); + try std.testing.expectEqual(@as(u32, 0), pane.body.normal.count); + try std.testing.expectEqual(.none, pane.body.normal.prefix); // A second Escape on a bare document is inert rather than an exit. p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expectEqual(@as(usize, 0), p.active); @@ -1781,8 +1781,8 @@ test "PDF native mouse selection, Look, and highlights share page geometry" { const page_before = pv.page; const scroll_before = pv.document_scroll_y; const sels_before = pane.sel; - const cursor_before = .{ pane.cur_row, pane.cur_col }; - const modal_before = .{ pane.msel, pane.vsel, pane.nsel }; + const cursor_before = .{ pane.body.cur_row, pane.body.cur_col }; + const modal_before = .{ pane.body.msel, pane.body.vsel, pane.body.nsel }; const selection_before = pv.selection orelse return error.MissingPdfSelection; const selection_quads_before = try gpa.dupe(pdf_impl.Quad, selection_before.quads); defer gpa.free(selection_quads_before); @@ -1836,8 +1836,8 @@ test "PDF native mouse selection, Look, and highlights share page geometry" { try std.testing.expectEqual(page_before, pv.page); try std.testing.expectEqual(scroll_before, pv.document_scroll_y); try std.testing.expect(std.meta.eql(sels_before, pane.sel)); - try std.testing.expectEqual(cursor_before, .{ pane.cur_row, pane.cur_col }); - try std.testing.expect(std.meta.eql(modal_before, .{ pane.msel, pane.vsel, pane.nsel })); + try std.testing.expectEqual(cursor_before, .{ pane.body.cur_row, pane.body.cur_col }); + try std.testing.expect(std.meta.eql(modal_before, .{ pane.body.msel, pane.body.vsel, pane.body.nsel })); const selection_after = pv.selection orelse return error.HoverDroppedPdfSelection; try std.testing.expectEqualSlices(pdf_impl.Quad, selection_quads_before, selection_after.quads); try std.testing.expectEqualStrings(selection_text_before, pv.selection_text); @@ -1938,7 +1938,7 @@ test "PDF native mouse selection, Look, and highlights share page geometry" { try std.testing.expect(panes.Pdf.beginSelection(p, pane, word_col, selected_row)); p.update(.{ .key = .{ .cp = 'v' } }); try std.testing.expect(pv.selection != null); - try std.testing.expect(!pane.vsel.active); + try std.testing.expect(!pane.body.vsel.active); p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = word_col, .row = selected_row } }); p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = word_col, .row = selected_row } }); try std.testing.expect(pv.selection == null); diff --git a/test/perf.zig b/test/perf.zig index 6ce8f014..8eec1ed0 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -229,7 +229,7 @@ fn measureStartup(io: std.Io, reps: usize, json: bool) !void { try std.json.Stringify.valueAlloc(gpa, result, .{}) else try std.fmt.allocPrint(gpa, "{s}: boot {d} ns (cold {d}), first frame {d} ns, {d} allocations / {d} B, peak {d} B", .{ - result.case, result.init_median_ns, result.cold_ns, result.frame_median_ns, + result.case, result.init_median_ns, result.cold_ns, result.frame_median_ns, result.allocations, result.allocated_bytes, result.peak_bytes, }); defer gpa.free(text); @@ -473,7 +473,7 @@ fn measure(op: Op, fx: Fixture, path: []const u8, expected_bytes: usize, reps: u for (0..warmup + reps) |n| { seek(pane, fx, n); _ = try frame(core); // settle the view at the new spot, untimed - const before = .{ .row = pane.cur_row, .col = pane.cur_col, .scroll = pane.scroll(), .len = pane.file.?.content.len }; + const before = .{ .row = pane.body.cur_row, .col = pane.body.cur_col, .scroll = pane.scroll(), .len = pane.file.?.content.len }; const rect = core.rects[id]; const wheel_col = rect.x + pardes.config.GUTTER; const wheel_row = if (core.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H; @@ -492,16 +492,16 @@ fn measure(op: Op, fx: Fixture, path: []const u8, expected_bytes: usize, reps: u const dt = nowNs() -| t0; switch (op) { .open => unreachable, - .render => if (pane.cur_row != before.row or pane.cur_col != before.col or pane.file.?.content.len != before.len) + .render => if (pane.body.cur_row != before.row or pane.body.cur_col != before.col or pane.file.?.content.len != before.len) return error.RenderChangedDocument, - .key_down => if (pane.cur_row != before.row + 1) return error.DownDidNotMove, - .key_right => if (pane.cur_row != before.row or pane.cur_col != before.col + 1) return error.RightDidNotMove, + .key_down => if (pane.body.cur_row != before.row + 1) return error.DownDidNotMove, + .key_right => if (pane.body.cur_row != before.row or pane.body.cur_col != before.col + 1) return error.RightDidNotMove, .page_down => if (pane.scroll() <= before.scroll and before.scroll < @as(i32, @intCast(fx.lines)) - pane.rows) return error.PageDidNotScroll, .wheel => if (pane.scroll() <= before.scroll and before.scroll < @as(i32, @intCast(fx.lines)) - pane.rows) return error.WheelDidNotScroll, .edit_char => { - if (pane.file.?.content.len != before.len + 1 or pane.cur_row != before.row or pane.cur_col != before.col + 1) + if (pane.file.?.content.len != before.len + 1 or pane.body.cur_row != before.row or pane.body.cur_col != before.col + 1) return error.CharacterWasNotInserted; const line = pardes.panes.File.sourceLine(pane, before.row); if (line[@intCast(before.col)] != 'x') return error.CharacterWasNotInserted; @@ -521,13 +521,13 @@ fn measureTerm(op: TermOp, fx: TermFixture, reps: usize) !Cell { defer core.deinit(); const pane = core.panes[0] orelse return error.MissingTerminal; const state = pane.terminal orelse return error.MissingTerminal; - if (op == .key_down or op == .edit_char) pane.mode = .normal; + if (op == .key_down or op == .edit_char) pane.body.mode = .normal; if (op == .edit_char) { core.update(.{ .key = .{ .cp = 'i', .text = "i" } }); pump(core); } _ = try frame(core); - const motion_rows = if (op == .key_down) (try pardes.edit.paneCursorLines(core, pane)).len else 0; + const motion_rows = if (op == .key_down) (try pardes.edit.paneCursorLines(core, &pane.body)).len else 0; if (op == .key_down and motion_rows < 3) return error.EmptyTerminalFixture; var cols = screen_cols; @@ -535,16 +535,16 @@ fn measureTerm(op: TermOp, fx: TermFixture, reps: usize) !Cell { for (0..warmup + reps) |n| { if (op == .key_down) { const span = @max(1, motion_rows * 8 / 10); - pane.cur_row = @intCast(@min(motion_rows - 2, motion_rows / 10 + (n *% 7919) % span)); - pane.cur_col = 0; - pane.cur_pinned = true; - pane.sticky_col = -1; + pane.body.cur_row = @intCast(@min(motion_rows - 2, motion_rows / 10 + (n *% 7919) % span)); + pane.body.cur_col = 0; + pane.body.cur_pinned = true; + pane.body.sticky_col = -1; pane.ensureCursorVisible(); _ = try frame(core); } const before = .{ - .row = pane.cur_row, - .col = pane.cur_col, + .row = pane.body.cur_row, + .col = pane.body.cur_col, .edit_len = if (pane.ovl) |overlay| overlay.text.len else 0, .replay_head = state.replay.head, .replay_len = state.replay.len, @@ -570,7 +570,7 @@ fn measureTerm(op: TermOp, fx: TermFixture, reps: usize) !Cell { _ = try frame(core); const dt = nowNs() -| t0; switch (op) { - .render => if (pane.cur_row != before.row or pane.cur_col != before.col or + .render => if (pane.body.cur_row != before.row or pane.body.cur_col != before.col or state.replay.head != before.replay_head or state.replay.len != before.replay_len) return error.RenderChangedTerminal, .output => { @@ -590,12 +590,12 @@ fn measureTerm(op: TermOp, fx: TermFixture, reps: usize) !Cell { state.vt.screens.active.pages.rows != pane.rows) return error.TerminalDidNotResize, .resize_cols => if (pane.cols == before.cols or pane.rows != before.rows or state.vt.screens.active.pages.cols != pane.cols) return error.TerminalDidNotResize, - .key_down => if (pane.cur_row != before.row + 1) return error.DownDidNotMove, + .key_down => if (pane.body.cur_row != before.row + 1) return error.DownDidNotMove, .edit_char => { const overlay = pane.ovl orelse return error.CharacterWasNotInserted; - if (overlay.text.len != before.edit_len + 1 or pane.cur_row != before.row or pane.cur_col != before.col + 1) + if (overlay.text.len != before.edit_len + 1 or pane.body.cur_row != before.row or pane.body.cur_col != before.col + 1) return error.CharacterWasNotInserted; - const line = pardes.modal.lineSlice(overlay.text, @intCast(pane.cur_row - overlay.row)); + const line = pardes.modal.lineSlice(overlay.text, @intCast(pane.body.cur_row - overlay.row)); if (before.col < 0 or before.col >= line.len or line[@intCast(before.col)] != 'x') return error.CharacterWasNotInserted; }, @@ -711,7 +711,7 @@ const UndoOutput = struct { fn measureUndoOutput(core: *pardes.Pardes, counter: *Allocations, arena: *std.heap.ArenaAllocator, samples: []u64) ![3]UndoOutput { const pane = core.panes[0].?; const pages = &pane.terminal.?.vt.screens.active.pages; - if (pane.ed_undo_len != 0 or pane.ed_redo_len != 0) return error.UnexpectedTerminalHistory; + if (pane.body.ed_undo_len != 0 or pane.body.ed_redo_len != 0) return error.UnexpectedTerminalHistory; if (pane.ovl) |overlay| core.gpa.free(overlay.text); pane.ovl = null; var result: [3]UndoOutput = undefined; @@ -722,17 +722,17 @@ fn measureUndoOutput(core: *pardes.Pardes, counter: *Allocations, arena: *std.he const first: i32 = @intCast(@min(128, pages.total_rows - 2)); for (0..depth) |index| { pane.ovl = .{ .row = first, .rows = 2, .text = try std.fmt.allocPrint(core.gpa, "saved edit {d}\nsecond row", .{index}) }; - pane.cur_row = first + 1; - pane.cur_col = 1; - pane.vsel = .{ .active = true, .row = first, .col = 0 }; + pane.body.cur_row = first + 1; + pane.body.cur_col = 1; + pane.body.vsel = .{ .active = true, .row = first, .col = 0 }; pardes.panes.Terminal.pushUndo(core, pane); core.gpa.free(pane.ovl.?.text); pane.ovl = null; - if (pane.ed_undo_len != index + 1) return error.TerminalUndoSnapshotFailed; + if (pane.body.ed_undo_len != index + 1) return error.TerminalUndoSnapshotFailed; } defer { - for (pane.ed_undo[0..pane.ed_undo_len]) |snapshot| if (snapshot.ovl) |overlay| core.gpa.free(overlay.text); - pane.ed_undo_len = 0; + for (pane.body.ed_undo[0..pane.body.ed_undo_len]) |snapshot| if (snapshot.ovl) |overlay| core.gpa.free(overlay.text); + pane.body.ed_undo_len = 0; } pardes.panes.Terminal.enterTty(core, 0); pump(core); @@ -767,7 +767,7 @@ fn measureUndoOutput(core: *pardes.Pardes, counter: *Allocations, arena: *std.he if (pages.countTrackedPins() != tracked_before + 2) return error.TerminalPinsLeaked; const expected: i32 = if (start.garbage) 0 else @intCast((pages.pointFromPin(.screen, start.*) orelse return error.TerminalAnchorLost).screen.y); const last: i32 = if (end.garbage) 0 else @intCast((pages.pointFromPin(.screen, end.*) orelse return error.TerminalAnchorLost).screen.y); - for (pane.ed_undo[0..pane.ed_undo_len], 0..) |snapshot, index| { + for (pane.body.ed_undo[0..pane.body.ed_undo_len], 0..) |snapshot, index| { const overlay = snapshot.ovl orelse return error.TerminalUndoTextLost; var expected_buffer: [64]u8 = undefined; const text = try std.fmt.bufPrint(&expected_buffer, "saved edit {d}\nsecond row", .{index}); @@ -812,7 +812,7 @@ fn measureTerminalSession(io: std.Io, mib: usize, reps: usize, json: bool) !void pump(core); const pane = core.panes[0] orelse return error.MissingTerminal; const state = pane.terminal orelse return error.MissingTerminal; - pane.mode = .tty; + pane.body.mode = .tty; pane.tty_filter = false; var arena: std.heap.ArenaAllocator = .init(counter.allocator()); defer arena.deinit(); @@ -855,17 +855,17 @@ fn measureTerminalSession(io: std.Io, mib: usize, reps: usize, json: bool) !void pump(core); _ = try core.render(arena.allocator()); const first_modal_ns = nowNs() - modal_begin; - if (pane.mode != .normal or !pane.cur_pinned or pane.cur_row != first_row - 1) return error.FirstModalKeyDidNotMove; + if (pane.body.mode != .normal or !pane.body.cur_pinned or pane.body.cur_row != first_row - 1) return error.FirstModalKeyDidNotMove; for (modal_samples, 0..) |*sample, index| { const down = index % 2 == 0; - const before = pane.cur_row; + const before = pane.body.cur_row; _ = arena.reset(.retain_capacity); const begin = nowNs(); core.update(.{ .key = .{ .cp = if (down) 'j' else 'k' } }); pump(core); _ = try core.render(arena.allocator()); sample.* = nowNs() - begin; - if (pane.cur_row != before + @as(i32, if (down) 1 else -1)) return error.ModalKeyDidNotMove; + if (pane.body.cur_row != before + @as(i32, if (down) 1 else -1)) return error.ModalKeyDidNotMove; } core.update(.{ .key = .{ .cp = core.opts.tty_toggle, .ctrl = true } }); pump(core); @@ -883,8 +883,8 @@ fn measureTerminalSession(io: std.Io, mib: usize, reps: usize, json: bool) !void const live_after_modal = counter.live; var overlay_median_ns: [2]u64 = undefined; var overlay_p95_ns: [2]u64 = undefined; - pane.mode = .normal; - pane.cur_pinned = true; + pane.body.mode = .normal; + pane.body.cur_pinned = true; pane.ovl = .{ .row = 0, .rows = 1, .text = try core.gpa.dupe(u8, "edited output") }; for (0..2) |phase| { for (modal_samples, 0..) |*sample, index| { @@ -897,8 +897,8 @@ fn measureTerminalSession(io: std.Io, mib: usize, reps: usize, json: bool) !void pump(core); const cursor_row = pardes.panes.Terminal.gridOffset(pane) + @as(i32, pardes.panes.Terminal.gridCursor(pane).y); pane.ovl.?.row = if (phase == 0) 0 else cursor_row - 1; - pane.cur_row = pane.ovl.?.row; - pane.cur_col = 0; + pane.body.cur_row = pane.ovl.?.row; + pane.body.cur_col = 0; const surface = try core.render(arena.allocator()); sample.* = nowNs() - begin; try checkTerminalTail(core, surface, tail_id); @@ -1146,11 +1146,11 @@ fn seek(pane: *pardes.Pane, fx: Fixture, n: usize) void { const row = fx.lines / 10 + (n *% 7919) % span; f.scroll = @min(row, fx.lines -| 1); f.syntax_dirty = true; - pane.cur_row = @intCast(f.scroll); - pane.cur_col = if (fx.cols > 200) @intCast(fx.cols * 3 / 4) else 0; - pane.cur_pinned = true; - pane.hscroll = @max(0, pane.cur_col - 40); - pane.sticky_col = -1; + pane.body.cur_row = @intCast(f.scroll); + pane.body.cur_col = if (fx.cols > 200) @intCast(fx.cols * 3 / 4) else 0; + pane.body.cur_pinned = true; + pane.hscroll = @max(0, pane.body.cur_col - 40); + pane.body.sticky_col = -1; } fn boot() !*pardes.Pardes { -- cgit v1.3 From 9584b0682b45f17aaa42157540947904d867777a Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 23:42:53 -0300 Subject: Give prompts their own line to type into instead of the tag's tail A search, pipe or Save prompt wrote its marker and answer onto the end of the tag, so the tag's cursor, its selection, its 9P writes and a prompt abandoned by a click all shared one buffer: the abandoned text stayed in the tag and a 9P write landed inside the prompt. The answer is now its own Text on the pane, typed in insert mode and shown on the notice band where it was already drawn, and the tag never holds any of it. Co-Authored-By: Claude Opus 5.5 --- docs/helix-keys.md | 5 +- src/File.zig | 3 +- src/Pipe.zig | 19 ++-- src/Text.zig | 33 +++++-- src/body_layer.zig | 4 +- src/edit.zig | 116 +++++++++++++++--------- src/exec.zig | 8 +- src/mouse.zig | 4 + src/normal.zig | 11 +-- src/panes.zig | 36 ++++---- src/pardes.zig | 168 +++++++++++++++++++---------------- test/panes.zig | 154 ++++++++------------------------ test/pdf.zig | 4 +- test/snapshots/find.golden | 1 - test/snapshots/find.snap | 3 +- test/snapshots/tagbottomshort.golden | 2 +- test/snapshots/tagbottomshort.snap | 9 +- 17 files changed, 282 insertions(+), 298 deletions(-) (limited to 'src/File.zig') diff --git a/docs/helix-keys.md b/docs/helix-keys.md index 4de3901a..0813c193 100644 --- a/docs/helix-keys.md +++ b/docs/helix-keys.md @@ -235,8 +235,9 @@ other cursors where they are (`FileSnap` holds one range). ### Regex selection (`s` / `S`) — the interactive pair -Both arm the tag input the same way `/` does — the pattern is typed into the -tag tail after a marker, no popup — and both re-run on EVERY keystroke, from +Both arm the prompt the same way `/` does — the pattern is typed after a +marker on the prompt's own line in the notice band, no popup — and both +re-run on EVERY keystroke, from the selection the prompt opened on (`Pane.sel_snap`). That is what makes the selection a live preview, what makes typing a pattern one character at a time land where pasting it whole would, and what makes Esc a plain restore. Enter diff --git a/src/File.zig b/src/File.zig index 239aa4ba..bf4bf08c 100644 --- a/src/File.zig +++ b/src/File.zig @@ -1129,7 +1129,8 @@ pub fn drawGutter(p: *Pardes, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, bod const goff = pane.scroll(); const gcur = Terminal.gridCursor(pane); const gcrow = if (pane.body.cur_pinned) pane.body.cur_row else @as(i32, gcur.y) + goff; - const cur_line: i32 = if (active and !pane.tag_edit) gcrow else std.math.minInt(i32); + const typing_body = !pane.tag_edit and (pane.prompt == .none or pane.prompt == .del_side); + const cur_line: i32 = if (active and typing_body) gcrow else std.math.minInt(i32); // the body's first row, the way renderPane derives it (Tagbottom) const body_y = p.bodyTop(r); const context_bg = p.theme().tag_bg; diff --git a/src/Pipe.zig b/src/Pipe.zig index c2b49f31..3e6752a8 100644 --- a/src/Pipe.zig +++ b/src/Pipe.zig @@ -73,13 +73,12 @@ pub fn submitPipe(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; const f = pane.file orelse return; if (!panes.Output.fileTraits(f.output).saves) return; - const prompt = switch (pane.prompt) { + const how = switch (pane.prompt) { .pipe => |pipe| pipe, else => return, }; - const tail = pane.tagSlice(); - const armed = tail[@min(prompt.at, tail.len)..]; - const marker = pipeMarker(prompt.how); + const armed = pane.promptText() orelse return; + const marker = pipeMarker(how); if (!std.mem.startsWith(u8, armed, marker)) return; const command = armed[marker.len..]; if (command.len == 0) return; @@ -87,11 +86,11 @@ pub fn submitPipe(p: *Pardes, id: usize) void { var ranges: [panes.Text.max_selections]modal.Selection = undefined; const got = pane.body.ranges(f.content, 0, &ranges); // `!`/`A-!` take no stdin and run ONCE — see `PendingPipe.nranges`. - const ninputs = if (prompt.how.pipes()) got.n else 1; + const ninputs = if (how.pipes()) got.n else 1; const inputs = p.gpa.alloc(selection_pipe.Input, ninputs) catch return; var made: usize = 0; for (ranges[0..ninputs], 0..) |range, i| { - const bytes = if (prompt.how.pipes()) bytes: { + const bytes = if (how.pipes()) bytes: { const lo = @min(range.anchor, range.head); const hi = @max(range.anchor, range.head); if (hi > f.content.len) break; @@ -131,7 +130,7 @@ pub fn submitPipe(p: *Pardes, id: usize) void { .ranges = ranges, .primary = @intCast(got.pri), .explicit = (pane.body.vsel.active and pane.body.vsel.explicit) or pane.body.msel.active, - .how = prompt.how, + .how = how, .nranges = @intCast(got.n), }; p.emit(.{ .pipe = .{ .id = p.pipe.seq } }); @@ -295,12 +294,12 @@ test "selection pipe prompt submits exact request and Escape cancels" { pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; p.update(.{ .key = .{ .cp = '|' } }); - try std.testing.expect(pane.tag_edit and pane.prompt == .pipe); - try std.testing.expect(std.mem.endsWith(u8, pane.tagSlice(), config.pipe_marker)); + try std.testing.expect(!pane.tag_edit and pane.prompt == .pipe); + try std.testing.expectEqualStrings(config.pipe_marker, pane.promptText().?); try std.testing.expect(nextPipeEffect(p) == null); p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); p.update(.{ .key = .{ .cp = Key.enter } }); - try std.testing.expect(!pane.tag_edit and pane.prompt != .pipe); + try std.testing.expect(!pane.tag_edit and pane.prompt != .pipe and pane.input.own == null); const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; const request = p.pipe.pipeRequest(id) orelse return error.MissingPipeRequest; try std.testing.expectEqualStrings("tr a-z A-Z", request.command); diff --git a/src/Text.zig b/src/Text.zig index ad5aa186..aaa6dc88 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -1,9 +1,11 @@ //! One editable text, acme's Text (editors/acme/dat.h:171-190, text.c): the //! cursor, the selections and the modal state that edit it, and the undo of -//! an edit buffer. A pane's body is one. Where its characters come from -- a -//! file's content, a terminal's edit overlay, a PDF's text -- is the window's -//! business (edit.zig's editText and flatSurface), the way acme's Text reads -//! its File; everything here works on the flat text it is handed. +//! an edit buffer. A pane's body is one, and so is the answer typed into a +//! pane's prompt. Where a body's characters come from -- a file's content, a +//! terminal's edit overlay, a PDF's text -- is the window's business +//! (edit.zig's editText and flatSurface), the way acme's Text reads its File; +//! every other text owns its characters. Everything here works on the flat +//! text it is handed. const std = @import("std"); const panes = @import("panes.zig"); const modal = @import("modal.zig"); @@ -15,6 +17,10 @@ const Text = @This(); pub const Mode = enum { normal, insert, tty }; +/// Which text of its window this is, acme's `what`. It says where the +/// characters live and whether moving the cursor scrolls a body. +pub const What = enum { body, input }; + /// A modal line selection (helix `x`): whole rows [r0, r1], absolute. pub const LineSel = struct { active: bool = false, @@ -41,6 +47,10 @@ pub const SelRange = struct { sticky: i32 = -1, }; +what: What = .body, +/// The characters of a text that holds its own (gpa-owned): everything but +/// a body, which reads its pane's. +own: ?[]u8 = null, mode: Mode = .normal, cur_pinned: bool = false, cur_row: i32 = 0, @@ -65,7 +75,16 @@ ed_redo_len: usize = 0, /// The window this text belongs to (acme's t->w). pub fn pane(t: *Text) *Pane { - return @alignCast(@fieldParentPtr("body", t)); + return switch (t.what) { + .body => @alignCast(@fieldParentPtr("body", t)), + .input => @alignCast(@fieldParentPtr("input", t)), + }; +} + +/// Bring the cursor into view (acme's textshow). Only a body scrolls to it; +/// a prompt's answer is drawn whole. +pub fn show(t: *Text) void { + if (t.what == .body) t.pane().ensureCursorVisible(); } pub fn toModalCursor(t: *Text) modal.Cursor { @@ -143,7 +162,7 @@ pub fn setRange(t: *Text, text: []const u8, row0: i32, r0: modal.Selection, expl t.cur_pinned = true; t.sticky_col = -1; t.normal.clear(); - t.pane().ensureCursorVisible(); + t.show(); } pub fn ranges(t: *Text, text: []const u8, row0: i32, out: *[max_selections]modal.Selection) struct { n: usize, pri: usize } { @@ -602,5 +621,5 @@ pub fn clampCursor(t: *Text, text: []const u8, row0: i32) void { t.cur_pinned = true; t.vsel.active = false; t.msel.active = false; - t.pane().ensureCursorVisible(); + t.show(); } diff --git a/src/body_layer.zig b/src/body_layer.zig index 71529326..1f210220 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -460,8 +460,8 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id } // cursor: tracks the shell cursor until pinned by a click or a key - // (the tag cursor above wins while the tag is focused) - if (active and !pane.tag_edit) { + // (the tag's or a prompt's cursor wins while that is being typed into) + if (active and !pane.tag_edit and (pane.prompt == .none or pane.prompt == .del_side)) { if (pane.body.mode != .tty) { const cur = panes.Terminal.gridCursor(pane); const goff = panes.Terminal.gridOffset(pane); diff --git a/src/edit.zig b/src/edit.zig index f1b381d6..5249a64c 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -84,12 +84,23 @@ pub fn applyPaste(p: *Pardes, bytes: []const u8) void { const pane = p.panes[id] orelse return; if (req) |r| if (pane.serial != r.serial) return; p.active = id; + if (pane.prompt != .none and pane.prompt != .del_side) { + // an answer is one line: a newline in it would only be submitting it + const line = p.scratch.allocator().alloc(u8, bytes.len) catch return; + var n: usize = 0; + for (bytes) |byte| if (byte != '\n' and byte != '\r') { + line[n] = byte; + n += 1; + }; + if (n > 0) insertKey(p, &pane.input, .{ .cp = line[0], .text = line[0..n] }); + if (normal.selRegexArmed(pane)) |a| normal.applySelRegex(p, pane, a.pat, a.split); + return; + } if (pane.tag_edit) { const text = p.tagText(p.scratch.allocator(), pane) catch return; const range: @TypeOf(Pardes.tagSelBounds(pane)) = if (pane.tag_sel) Pardes.tagSelBounds(pane) else .{ .lo = pane.tag_col, .hi = pane.tag_col }; const hi = if (pane.tag_sel) modal.nextGrapheme(text, range.hi) else range.hi; _ = p.replaceTagText(pane, range.lo, hi, bytes); - if (normal.selRegexArmed(pane)) |a| normal.applySelRegex(p, pane, a.pat, a.split); return; } if (pane.isTerminal() and pane.body.mode == .tty) return typeToTty(p, id, pane, bytes); @@ -274,7 +285,7 @@ pub fn exitInsert(p: *Pardes, t: *Text) void { t.cur_col = @intCast(bc.col); t.vsel = .{ .active = a_off != back, .row = aa.row, .col = aa.col, .explicit = false }; t.cur_pinned = true; - t.pane().ensureCursorVisible(); + t.show(); for (t.sels[0..t.nsel]) |*s| { const sgap = modal.offsetAt(text, .{ .row = @intCast(@max(0, s.row)), .col = @intCast(@max(0, s.col)) }); const b2 = if (back == gap) sgap else modal.prevGrapheme(text, sgap); @@ -288,8 +299,15 @@ pub fn exitInsert(p: *Pardes, t: *Text) void { } pub fn paneCursorLines(p: *Pardes, t: *Text) ![]const []const u8 { - const pane = t.pane(); const arena = p.scratch.allocator(); + if (t.what != .body) { + const text = t.own orelse ""; + const lines = try arena.alloc([]const u8, std.mem.count(u8, text, "\n") + 1); + var it = std.mem.splitScalar(u8, text, '\n'); + for (lines) |*line| line.* = it.next().?; + return lines; + } + const pane = t.pane(); if (pane.file) |*f| return panes.File.cursorLines(arena, pane, f); if (pane.hasPdf()) { if (comptime pdf_enabled) return panes.Pdf.textLines(&pane.pdf.?, p.pdf_gpa, arena); @@ -299,9 +317,8 @@ pub fn paneCursorLines(p: *Pardes, t: *Text) ![]const []const u8 { } pub fn paneByteAtDisplay(p: *Pardes, t: *Text, row: i32, from_raw: i32, display_col: i32) i32 { - const pane = t.pane(); - if (pane.file != null) - return panes.File.byteAtRowDisplay(pane, row, from_raw, display_col); + if (t.what == .body and t.pane().file != null) + return panes.File.byteAtRowDisplay(t.pane(), row, from_raw, display_col); const lines = paneCursorLines(p, t) catch return @max(0, from_raw + display_col); const local = row; if (local < 0 or @as(usize, @intCast(local)) >= lines.len) @@ -316,14 +333,20 @@ pub fn paneByteAtDisplay(p: *Pardes, t: *Text, row: i32, from_raw: i32, display_ /// Freeze the live terminal cursor into the modal coordinate space. The /// emulator reports screen cells; editing state stores UTF-8 byte offsets. pub fn pinPaneCursor(p: *Pardes, t: *Text) void { - const pane = t.pane(); if (t.cur_pinned) return; + // Only a body has a live cursor of someone else's to freeze. + if (t.what != .body) { + t.cur_pinned = true; + return; + } + const pane = t.pane(); pane.pinCursor(); if (pane.file == null and !pane.hasPdf()) t.cur_col = paneByteAtDisplay(p, t, t.cur_row, 0, t.cur_col); } pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { + if (t.what != .body) return t.own orelse ""; const pane = t.pane(); if (pane.file) |f| return f.content; if (pane.hasPdf()) { @@ -335,13 +358,16 @@ pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { } pub fn paneWrapWidth(p: *const Pardes, t: *Text) usize { + if (t.what != .body) return 0; const pane = t.pane(); if (pane.file == null) return 0; return panes.File.wrapWidth(pane, p.settings.wrap); } -/// Route shared edit operations to a file's content or a terminal overlay. +/// Route shared edit operations to the characters `t` edits: its own, or +/// for a body its file's content or its terminal's overlay. fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText { + if (t.what != .body) return .{ .text = t.own orelse &.{}, .row0 = 0 }; const pane = t.pane(); if (pane.file) |f| return .{ .text = f.content, .row0 = 0 }; if (pane.image != null or pane.hasPdf()) return null; @@ -358,6 +384,11 @@ fn editTextEol(p: *Pardes, t: *Text, b: Bounds) ?panes.EditText { /// install a rewritten editable text (frees the old one) fn setEditText(p: *Pardes, t: *Text, new: []u8) void { + if (t.what != .body) { + if (t.own) |old| p.gpa.free(old); + t.own = new; + return; + } const pane = t.pane(); if (pane.file) |*f| return panes.File.setContent(p, f, new); panes.Terminal.setEditText(p, pane, new); @@ -368,6 +399,7 @@ pub const InsertAt = enum { at, append, line_start, line_end, open_below, open_a /// Files insert only inside existing rows and at grapheme boundaries. /// Terminal overlays can materialize virtual rows/columns, so keep those. pub fn clampFileCursor(t: *Text) bool { + if (t.what != .body) return false; const pane = t.pane(); const file = if (pane.file) |*file| file else return false; const old_row = t.cur_row; @@ -380,8 +412,7 @@ pub fn clampFileCursor(t: *Text) bool { } pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) void { - const pane = t.pane(); - if (pane.hasPdf()) return; + if (t.what == .body and t.pane().hasPdf()) return; pinPaneCursor(p, t); _ = clampFileCursor(t); // snapshot once per insert session (WITH the pre-insert selection) so @@ -478,7 +509,7 @@ pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) void { t.mode = .insert; t.msel.active = false; t.normal.clear(); - pane.ensureCursorVisible(); + t.show(); } pub fn handleInsert(p: *Pardes, t: *Text, key: Key) void { @@ -487,7 +518,6 @@ pub fn handleInsert(p: *Pardes, t: *Text, key: Key) void { } pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { - const pane = t.pane(); // helix aliases: normalize to the base key and re-dispatch if (hit(key, config.insert_backspace_alias)) return insertKey(p, t, .{ .cp = Key.backspace }); if (hit(key, config.insert_enter_alias)) return insertKey(p, t, .{ .cp = Key.enter }); @@ -507,7 +537,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { else => cur0, }; t.fromModalCursor(nc); - pane.ensureCursorVisible(); + t.show(); return; }, Key.page_up, Key.page_down => { @@ -515,14 +545,15 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { // scroll + cursor snap as normal mode const flat = flatSurface(p, t) catch return; const range = t.primaryRange(flat, 0); - const step: i32 = @intCast(@max(1, pane.rows)); + if (t.what != .body) return; + const step: i32 = @intCast(@max(1, t.pane().rows)); t.scrollViewMove(flat, range, if (key.cp == Key.page_down) step else -step); return; }, Key.home => { t.cur_col = 0; t.cur_pinned = true; - pane.ensureCursorVisible(); + t.show(); return; }, Key.end => { @@ -531,7 +562,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { const cur0 = t.toModalCursor(); t.cur_col = @intCast(panes.File.textLine(t, text, cur0.row).len); t.cur_pinned = true; - pane.ensureCursorVisible(); + t.show(); return; }, else => {}, @@ -549,7 +580,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { } else t.cur_col += 1; } t.cur_pinned = true; - pane.ensureCursorVisible(); + t.show(); return; } // helix insert-mode kills (word/line; deleteSpan is exclusive) @@ -569,7 +600,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { t.cur_row = @as(i32, @intCast(fc.row)) + e2.row0; t.cur_col = @intCast(fc.col); t.cur_pinned = true; - pane.ensureCursorVisible(); + t.show(); return; } if (hit(key, config.delete_word_forward)) { @@ -592,7 +623,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { setEditText(p, t, new); t.cur_col = 0; t.cur_pinned = true; - pane.ensureCursorVisible(); + t.show(); return; } if (hit(key, config.kill_to_line_end)) { @@ -615,7 +646,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { t.cur_row += 1; t.cur_col = @intCast(indent); t.cur_pinned = true; - pane.ensureCursorVisible(); + t.show(); }, Key.backspace => { if (t.cur_col > 0) { @@ -625,7 +656,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { setEditText(p, t, new); t.cur_col = @intCast(prev); t.cur_pinned = true; - pane.ensureCursorVisible(); + t.show(); return; } // at col 0: eat the newline above (join up) — a terminal grows @@ -640,7 +671,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { t.cur_row -= 1; t.cur_col = @intCast(prevlen); t.cur_pinned = true; - pane.ensureCursorVisible(); + t.show(); }, Key.delete => { // delete forward; at line end eat the newline (join), which on @@ -661,7 +692,8 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { Key.tab => { const ln = modal.lineSlice(text, c.row); if (!p.multi_on and c.col > 0 and c.col <= ln.len and ln[c.col - 1] == '.') dot: { - const f = pane.file orelse break :dot; + if (t.what != .body) break :dot; + const f = t.pane().file orelse break :dot; if (f.output != null or !lsp.speaks(f.path)) break :dot; const seq = p.lsp_seq; p.lspRequest(p.active, .completion, ""); @@ -684,7 +716,7 @@ pub fn insertTab(p: *Pardes, t: *Text) void { setEditText(p, t, new); t.cur_col += @intCast(pad); t.cur_pinned = true; - t.pane().ensureCursorVisible(); + t.show(); } const Bounds = struct { lo_row: i32, lo_col: i32, hi_row: i32, hi_col: i32 }; @@ -779,7 +811,7 @@ pub fn normalDelete(p: *Pardes, t: *Text, yank: bool) void { t.cur_col = 0; t.msel.active = false; t.cur_pinned = true; - t.pane().ensureCursorVisible(); + t.show(); } else { pushUndo(p, t); const eb = editTextEol(p, t, .{ .lo_row = t.cur_row, .lo_col = t.cur_col, .hi_row = t.cur_row, .hi_col = t.cur_col }) orelse return; @@ -799,12 +831,11 @@ pub fn normalDelete(p: *Pardes, t: *Text, yank: bool) void { } pub fn normalYank(p: *Pardes, t: *Text) void { - const pane = t.pane(); t.select = false; - if (pane.rawPointerText(pane.sel[sel_slot])) |text| { + if (t.what == .body) if (t.pane().rawPointerText(t.pane().sel[sel_slot])) |text| { setYank(p, text); return; - } + }; if (t.vsel.active) { setYank(p, vselText(p, t)); return; @@ -882,11 +913,10 @@ pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usiz } t.msel.active = false; t.cur_pinned = true; - t.pane().ensureCursorVisible(); + t.show(); } pub fn normalChange(p: *Pardes, t: *Text) void { - const pane = t.pane(); t.select = false; t.sticky_col = -1; if (t.vsel.active) { @@ -913,7 +943,7 @@ pub fn normalChange(p: *Pardes, t: *Text) void { t.cur_pinned = true; t.mode = .insert; t.normal.clear(); - pane.ensureCursorVisible(); + t.show(); return; } setYank(p, vselText(p, t)); @@ -974,7 +1004,7 @@ pub fn normalChange(p: *Pardes, t: *Text) void { t.cur_pinned = true; t.mode = .insert; t.normal.clear(); - pane.ensureCursorVisible(); + t.show(); } else { pushUndo(p, t); const eb = editTextEol(p, t, .{ .lo_row = t.cur_row, .lo_col = t.cur_col, .hi_row = t.cur_row, .hi_col = t.cur_col }) orelse return; @@ -1075,7 +1105,7 @@ fn replaceWithText(p: *Pardes, t: *Text, y: []const u8) void { } t.cur_pinned = true; t.sticky_col = -1; - t.pane().ensureCursorVisible(); + t.show(); } /// `~` / `` ` `` / ``Alt-` ``: case-map the selection (or the cursor char), @@ -1174,7 +1204,7 @@ pub fn normalJoin(p: *Pardes, t: *Text) void { t.msel.active = false; t.cur_pinned = true; t.sticky_col = -1; - t.pane().ensureCursorVisible(); + t.show(); } pub fn normalIndent(p: *Pardes, t: *Text, cnt: usize, add: bool) void { @@ -1242,7 +1272,7 @@ pub fn normalIndent(p: *Pardes, t: *Text, cnt: usize, add: bool) void { t.msel.active = false; t.cur_pinned = true; t.sticky_col = -1; - t.pane().ensureCursorVisible(); + t.show(); } pub fn normalToggleComment(p: *Pardes, t: *Text) void { @@ -1277,7 +1307,7 @@ pub fn normalToggleComment(p: *Pardes, t: *Text) void { } next = @max(next, end); } - const ext = if (t.pane().file) |f| std.fs.path.extension(f.path) else ""; + const ext = if (t.what != .body) "" else if (t.pane().file) |f| std.fs.path.extension(f.path) else ""; var token: []const u8 = config.comment_token_default; lang: for (config.comment_tokens) |row| { for (row.exts) |e| if (std.ascii.eqlIgnoreCase(ext, e)) { @@ -1359,7 +1389,7 @@ pub fn normalAdjustNumber(p: *Pardes, t: *Text, delta: i64) void { t.cur_col = @intCast(cc.col); t.cur_pinned = true; t.sticky_col = -1; - t.pane().ensureCursorVisible(); + t.show(); } /// `]Space` / `[Space`: add blank lines below/above, the cursor staying @@ -1381,7 +1411,7 @@ pub fn addNewline(p: *Pardes, t: *Text, below: bool, cnt: usize) void { t.vsel.row += @intCast(cnt); } t.cur_pinned = true; - t.pane().ensureCursorVisible(); + t.show(); } /// pair mapping for m-mode: either bracket names the pair; anything else @@ -1450,7 +1480,7 @@ pub fn surroundAdd(p: *Pardes, t: *Text, ch: u21) void { t.cur_col = @intCast(close_col + @as(usize, if (r.a.row == r.b.row) 1 else 0)); t.cur_pinned = true; t.sticky_col = -1; - t.pane().ensureCursorVisible(); + t.show(); } /// `md`: delete the enclosing pair's chars; the cursor maps through @@ -1487,7 +1517,7 @@ pub fn surroundDelete(p: *Pardes, t: *Text, ch: u21) void { t.vsel.active = false; t.msel.active = false; t.cur_pinned = true; - t.pane().ensureCursorVisible(); + t.show(); } /// `mr`: swap the enclosing pair's chars for 's @@ -1512,20 +1542,24 @@ pub fn surroundReplace(p: *Pardes, t: *Text, from: u21, to: u21) void { } pub fn pushUndo(p: *Pardes, t: *Text) void { - const pane = t.pane(); // one keystroke, one undo step — even when it edited at ten cursors. if (p.multi_on and !p.multi_first) return; + // a prompt's answer is typed once and gone; it keeps no history + if (t.what != .body) return; + const pane = t.pane(); if (pane.file != null) return panes.File.pushUndo(p, pane); panes.Terminal.pushUndo(p, pane); } pub fn doUndo(p: *Pardes, t: *Text) void { + if (t.what != .body) return; const pane = t.pane(); if (pane.file != null) return panes.File.undo(p, pane); panes.Terminal.undo(p, pane); } pub fn doRedo(p: *Pardes, t: *Text) void { + if (t.what != .body) return; const pane = t.pane(); if (pane.file != null) return panes.File.redo(p, pane); panes.Terminal.redo(p, pane); diff --git a/src/exec.zig b/src/exec.zig index 0a9d6f31..a2dbac7c 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -219,12 +219,8 @@ pub fn withArg(p: *Pardes, txt: []const u8, arg: ?[]const u8) []const u8 { /// Enter on a save input: the path is everything past the marker. pub fn submitSave(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; - const at = switch (pane.prompt) { - .save => |a| a, - else => return, - }; - const armed = pane.tag_tail[at..pane.tag_tail_len]; - pane.tag_tail_len = at; // drop the prompt back to the seeded tail + if (pane.prompt != .save) return; + const armed = pane.promptText() orelse return; if (!std.mem.startsWith(u8, armed, config.save_marker)) return; const path = std.mem.trim(u8, armed[config.save_marker.len..], " \t\r\n"); if (path.len == 0) return; diff --git a/src/mouse.zig b/src/mouse.zig index a840c8fc..5f77634b 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -304,6 +304,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { { if (m.button == config.select_button) if (p.panes[p.active]) |pane| { if (pane.tag_edit) Pardes.exitTagEdit(pane); + pane.closePrompt(); }; var column: ?usize = null; var x: u16 = 0; @@ -439,6 +440,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { const pane = p.panes[id] orelse return; if (id != p.active) if (p.panes[p.active]) |previous| { if (previous.tag_edit) Pardes.exitTagEdit(previous); + previous.closePrompt(); }; const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; const body_y = p.bodyTop(r); @@ -449,12 +451,14 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { } else if (mrow >= tag_y and mrow < tag_y + BOX_H) { if (mcol < r.x + TAG_TEXT_INSET) return; p.active = id; + pane.closePrompt(); p.enterTagEdit(pane, if (tagColumn(p, .pane, id, p.pointer_tag_hit, false)) |value| @as(i32, value) else @as(i32, mcol) - @as(i32, r.x + TAG_TEXT_INSET)); pane.tag_anchor = pane.tag_col; p.drag = .{ .tag = .{ .id = id } }; } else { p.active = id; if (pane.tag_edit) Pardes.exitTagEdit(pane); + pane.closePrompt(); const pointed = edit.pointerTextSelection(p, id, mcol, mrow, m.body_hit, p.pointer_tag_hit) orelse return; pane.clearPointerSelection(sel_slot); pane.sel[sel_slot] = pointed.sel; diff --git a/src/normal.zig b/src/normal.zig index 192fd933..a77f27a7 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -76,13 +76,8 @@ fn startSelRegex(p: *Pardes, pane: *Pane, split: bool) void { } pub fn selRegexArmed(pane: *Pane) ?struct { pat: []const u8, split: bool } { - const prompt_at = switch (pane.prompt) { - .search => |at| at, - else => return null, - }; - if (pane.nsel_snap == 0) return null; - const tail = pane.tagSlice(); - const armed = tail[@min(prompt_at, tail.len)..]; + if (pane.prompt != .search or pane.nsel_snap == 0) return null; + const armed = pane.input.own orelse ""; const split = std.mem.startsWith(u8, armed, config.split_marker); if (!split and !std.mem.startsWith(u8, armed, config.select_marker)) return null; const slash = std.mem.indexOfScalar(u8, armed, '/') orelse return null; @@ -274,7 +269,7 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { } t.setRanges(text, rs[0..n], st[0..n], pri, after_expl); after.into(t); - t.pane().ensureCursorVisible(); // the view follows the PRIMARY, not the last pass + t.show(); // the view follows the PRIMARY, not the last pass } pub fn handleNormal(p: *Pardes, t: *Text, key: Key) void { diff --git a/src/panes.zig b/src/panes.zig index e6634583..c26065ca 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -59,12 +59,13 @@ pub const Pane = struct { const PdfSlot = if (Pdf.enabled) ?Pdf.State else void; + /// What an open prompt is asking. The answer is typed into `input`. pub const Prompt = union(enum) { none, - search: u16, - pipe: struct { at: u16, how: modal.Normal.PipeBehavior }, - /// Save on a scratch buffer or a terminal: the tail is a path to write to. - save: u16, + search, + pipe: modal.Normal.PipeBehavior, + /// Save on a scratch buffer or a terminal: the answer is a path to write to. + save, /// Del from the keyboard with open panes both above and below: which /// one takes the rows. Nothing is typed; one key answers. del_side, @@ -94,9 +95,11 @@ pub const Pane = struct { file: ?File.State = null, image: ?Image.State = null, pdf: PdfSlot = if (Pdf.enabled) null else {}, - /// Tag-tail input state. The tag text is presentation; this tag carries - /// which operation owns it and the tail offset restored on submit/cancel. prompt: Prompt = .none, + /// The answer to an open prompt: its marker and what is typed after it, + /// edited in insert mode and shown on the notice band. It is its own text + /// so a prompt never touches the tag. + input: Text = .{ .what = .input }, search_pane: ?usize = null, search_row: ?usize = null, look_at: ?LookSpot = null, @@ -297,20 +300,23 @@ pub const Pane = struct { pub fn tagSlice(p: *const Pane) []const u8 { return p.tag_tail[0..p.tag_tail_len]; } - pub fn promptAt(p: *const Pane) ?u16 { - return switch (p.prompt) { - .none, .del_side => null, - .search, .save => |at| at, - .pipe => |pipe| pipe.at, - }; + /// Close an open prompt, answered or not. Its answer goes with it, and an + /// s/S preview keeps whatever it last previewed. + pub fn closePrompt(pane: *Pane) void { + if (pane.input.own) |text| pane.gpa.free(text); + pane.input = .{ .what = .input }; + pane.prompt = .none; + pane.nsel_snap = 0; } /// What an open prompt shows on its notice band: the one answer every /// painter of the band reads. pub fn promptText(p: *const Pane) ?[]const u8 { - if (p.prompt == .del_side) return config.del_question; - const at = p.promptAt() orelse return null; - return p.tagSlice()[@min(at, p.tag_tail_len)..]; + return switch (p.prompt) { + .none => null, + .del_side => config.del_question, + else => p.input.own orelse "", + }; } pub fn appendTag(p: *Pane, text: []const u8) bool { diff --git a/src/pardes.zig b/src/pardes.zig index 15b2c49b..a29973e7 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -1824,10 +1824,10 @@ test "Save on a scratch asks for a path in its inherited dir and makes it a file // Save on a scratch arms a PATH input, prefilled with the inherited dir try std.testing.expect(p.executeBuiltinLine(id, "Save")); try std.testing.expect(np.prompt == .save); - try std.testing.expect(std.mem.endsWith(u8, np.tagSlice(), " Save /tmp/pardes-save-dir/")); + try std.testing.expectEqualStrings(" Save /tmp/pardes-save-dir/", np.promptText().?); // typing the filename and submitting converts it into an ordinary file - try std.testing.expect(np.appendTag("note.txt")); + edit.insertKey(p, &np.input, .{ .cp = 'n', .text = "note.txt" }); exec.submitSave(p, id); try std.testing.expect(np.file.?.output == null); try std.testing.expectEqualStrings("/tmp/pardes-save-dir/note.txt", np.file.?.path); @@ -1852,7 +1852,7 @@ test "Save on a terminal writes its plaintext scrollback and stays a terminal" { try std.testing.expect(p.executeBuiltinLine(0, "Save")); try std.testing.expect(pane.prompt == .save); - try std.testing.expect(pane.appendTag("log.txt")); + edit.insertKey(p, &pane.input, .{ .cp = 'l', .text = "log.txt" }); exec.submitSave(p, 0); // the pane is untouched: still a terminal, no file behind it @@ -1901,7 +1901,7 @@ test "Save on an output buffer writes its rows out and leaves the buffer alone" try std.testing.expectEqualStrings(file_pane_tail, Pardes.curTail(out)); try std.testing.expect(p.executeBuiltinLine(id, "Save")); try std.testing.expect(out.prompt == .save); - try std.testing.expect(out.appendTag("help.txt")); + edit.insertKey(p, &out.input, .{ .cp = 'h', .text = "help.txt" }); exec.submitSave(p, id); // the buffer itself is untouched: same origin, same name, still refillable @@ -4109,6 +4109,7 @@ pub const Pardes = struct { if (comptime pdf_enabled) if (pane.pdf) |*pv| panes.Pdf.deinitPane(p, pane, pv); if (pane.file) |*file| panes.File.deinit(p, pane, file); if (pane.ovl) |o| p.gpa.free(o.text); + if (pane.input.own) |text| p.gpa.free(text); for (pane.body.ed_undo[0..pane.body.ed_undo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); for (pane.body.ed_redo[0..pane.body.ed_redo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); panes.Terminal.deinitEmulator(pane, p.gpa); @@ -4836,7 +4837,7 @@ pub const Pardes = struct { } pub fn enterTagEdit(p: *Pardes, pane: *Pane, col: i32) void { - if (pane.tag_edit and pane.prompt == .none) pane.tag_saved_col = pane.tag_col; + if (pane.tag_edit) pane.tag_saved_col = pane.tag_col; const edit0: i32 = @intCast((p.tagPrefix(pane) catch return).len); p.seedTail(pane); if (!pane.tag_init) return; @@ -4869,7 +4870,7 @@ pub const Pardes = struct { } pub fn exitTagEdit(pane: *Pane) void { - if (pane.tag_edit and pane.prompt == .none) pane.tag_saved_col = pane.tag_col; + if (pane.tag_edit) pane.tag_saved_col = pane.tag_col; if (pane.isTerminal()) { if (pane.tag_edit) pane.body.mode = pane.tag_mode; } else pane.body.mode = .normal; @@ -4877,8 +4878,6 @@ pub const Pardes = struct { pane.tag_sel = false; pane.tag_name_len = null; pane.tag_scroll = 0; - pane.prompt = .none; // an abandoned prompt stays as tag text - pane.nsel_snap = 0; // ...and its s/S preview keeps whatever it previewed } pub fn tagSelBounds(pane: *Pane) struct { lo: usize, hi: usize } { @@ -5273,6 +5272,7 @@ pub const Pardes = struct { p.active = id; p.exitHeader(); if (pane.tag_edit) exitTagEdit(pane); + pane.closePrompt(); pane.body.mode = previous; switch (previous) { .tty => { @@ -5294,6 +5294,7 @@ pub const Pardes = struct { p.active = id; p.exitHeader(); if (pane.tag_edit) exitTagEdit(pane); + pane.closePrompt(); if (pane.body.mode == .tty) { pane.body.mode = .normal; pane.body.normal.clear(); @@ -5351,7 +5352,7 @@ pub const Pardes = struct { } // insert mode owns Ctrl-w (delete word backward, helix); the focus // prefix applies outside raw tty mode - if (hit(key, config.window_prefix) and pane.body.mode != .insert) { + if (hit(key, config.window_prefix) and pane.body.mode != .insert and pane.prompt == .none) { p.ctrl_w_pending = true; return; } @@ -5384,34 +5385,29 @@ pub const Pardes = struct { if (pane.isTerminal() and tty_toggle) { return p.toggleTty(p.active); } - if (pane.prompt != .none and (hit(key, config.search_submit) or hit(key, config.escape))) { - const submit = hit(key, config.search_submit); - switch (pane.prompt) { - .pipe => |pipe| { - if (submit) Pipe.submitPipe(p, p.active); - pane.tag_tail_len = @min(pipe.at, pane.tag_tail_len); - }, - .save => |at| { - if (submit) exec.submitSave(p, p.active) else pane.tag_tail_len = @min(at, pane.tag_tail_len); - }, - .search => |at| { - if (submit) + if (pane.prompt != .none) { + if (hit(key, config.search_submit) or hit(key, config.escape)) { + const submit = hit(key, config.search_submit); + switch (pane.prompt) { + .pipe => if (submit) Pipe.submitPipe(p, p.active), + .save => if (submit) exec.submitSave(p, p.active), + .search => if (submit) look.submitSearch(p, p.active) else if (normal.selRegexArmed(pane)) |_| - normal.applySelRegex(p, pane, "", false); - pane.tag_tail_len = @min(at, pane.tag_tail_len); - }, - .none, .del_side => unreachable, + normal.applySelRegex(p, pane, "", false), + .none, .del_side => unreachable, + } + pane.closePrompt(); + pane.body.mode = .normal; + pane.body.normal.clear(); + return; } - exitTagEdit(pane); - pane.body.mode = .normal; - pane.body.normal.clear(); + edit.handleInsert(p, &pane.input, key); + if (normal.selRegexArmed(pane)) |a| normal.applySelRegex(p, pane, a.pat, a.split); return; } if (pane.tag_edit) { if (pane.body.mode == .normal) p.tagNormalKey(pane, key) else p.tagInsertKey(pane, key); - const pn = p.panes[p.active] orelse return; - if (normal.selRegexArmed(pn)) |a| normal.applySelRegex(p, pn, a.pat, a.split); return; } if (pane.body.mode == .normal and (hit(key, config.look_key) or hit(key, config.exec_key))) { @@ -5506,33 +5502,24 @@ pub const Pardes = struct { break :pipe Pipe.pipeMarker(how); }, }; - p.seedTail(pane); - if (!pane.tag_init) return; + // Save asks for a path, so its answer starts out as the pane's own + // directory for the name to be typed onto. const dir = if (request == .save) paneDir(pane) else ""; - const slash = request == .save and (dir.len == 0 or dir[dir.len - 1] != '/'); - var room = pane.tag_tail.len - pane.tag_tail_len; - if (marker.len > room) return; - room -= marker.len; - if (dir.len > room) return; - room -= dir.len; - if (slash and room == 0) return; - const prefix_len = (p.tagPrefix(pane) catch return).len; - const prompt_at: u16 = @intCast(pane.tag_tail_len); - _ = pane.appendTag(marker); - if (request == .save) { - _ = pane.appendTag(dir); - if (slash) _ = pane.appendTag("/"); - } + const slash: []const u8 = if (request == .save and (dir.len == 0 or dir[dir.len - 1] != '/')) "/" else ""; + const answer = std.mem.concat(p.gpa, u8, &.{ marker, dir, slash }) catch return; + if (pane.tag_edit) exitTagEdit(pane); + // Not closePrompt: an s/S snapshot was taken for this very prompt. + if (pane.input.own) |old| p.gpa.free(old); pane.prompt = switch (request) { - .search => .{ .search = prompt_at }, - .pipe => |how| .{ .pipe = .{ .at = prompt_at, .how = how } }, - .save => .{ .save = prompt_at }, + .search => .search, + .pipe => |how| .{ .pipe = how }, + .save => .save, }; - pane.tag_edit = true; - pane.tag_sel = false; - pane.body.mode = .insert; + pane.input = .{ .what = .input, .own = answer, .mode = .insert, .cur_pinned = true, .cur_col = @intCast(answer.len) }; + // Whatever mode the body was in, it is in normal mode once the + // prompt is answered or dropped. + pane.body.mode = .normal; pane.body.normal.clear(); - pane.tag_col = @intCast(prefix_len + pane.tag_tail_len); } pub const SavePath = Effect.Buf(effect_path_cap); @@ -6066,7 +6053,7 @@ pub const Pardes = struct { p.trackJump(); for (&p.panes, 0..) |*slot, id| { const pane = slot.* orelse continue; - if (pane.tag_edit and pane.prompt == .none and (id != p.active or p.topbar_col != null)) + if (pane.tag_edit and (id != p.active or p.topbar_col != null)) exitTagEdit(pane); if (comptime terminal_panes) if (pane.terminal) |state| { var off: u16 = 0; @@ -6279,18 +6266,14 @@ pub const Pardes = struct { // the detached wire will encode -- which drops every frame for // as long as the prompt is up. const printed = Messages.printRight(s, cx, row, chip -| 1, text, style); - if (kind != .prompt or id != p.active) continue; - const at = pane.promptAt() orelse continue; - const prompt0 = (p.tagPrefix(pane) catch continue).len + at; - const col = @as(usize, pane.tag_col); - if (col < prompt0) continue; + if (kind != .prompt or id != p.active or pane.prompt == .del_side) continue; // The cursor follows the text to wherever it landed; a caret // in the part a narrow band dropped has nowhere to be. - const prompt_col = panes.File.displayWidth(text[0..@min(col - prompt0, text.len)]); + const prompt_col = panes.File.displayWidth(text[0..@min(@as(usize, @intCast(@max(0, pane.input.cur_col))), text.len)]); if (prompt_col < printed.dropped) continue; const caret = printed.left + (prompt_col - printed.dropped); if (caret < tx + tw) - s.cursor = .{ .x = @intCast(caret), .y = row, .bar = pane.body.mode == .insert }; + s.cursor = .{ .x = @intCast(caret), .y = row, .bar = pane.input.mode == .insert }; } } @@ -6652,7 +6635,7 @@ pub const Pardes = struct { layer.viewport = .{ .x = r.x + TAG_TEXT_INSET, .y = if (p.settings.tag_bottom) r.y + r.h - BOX_H else r.y, .w = r.w - TAG_TEXT_INSET, .h = BOX_H }; layer.cols = columns; layer.bg = if (id == p.active and p.settings.focus_tint) chrome.tag_active_bg else chrome.tag_bg; - layer.cursor = if (p.topbar_col == null and pane.promptAt() == null and temporary.cursor != null) .{ .col = temporary.cursor.?.x - TAG_TEXT_INSET, .bar = temporary.cursor.?.bar } else null; + layer.cursor = if (p.topbar_col == null and temporary.cursor != null) .{ .col = temporary.cursor.?.x - TAG_TEXT_INSET, .bar = temporary.cursor.?.bar } else null; } var text_buf: [1200]u8 = undefined; // With the workspace tag row handed to native chrome there is no @@ -6711,14 +6694,11 @@ pub const Pardes = struct { p.surface.tag_layers[layer_index].fade = fade; // The caret rides the band, where the prompt's glyphs are, // at the same place in the text the grid pass puts it. - if (kind != .prompt or id != p.active) continue; - const at = pane.promptAt() orelse continue; - const prompt0 = (p.tagPrefix(pane) catch continue).len + at; - if (pane.tag_col < prompt0) continue; - const typed = panes.File.displayWidth(text[0..@min(pane.tag_col - prompt0, text.len)]); + if (kind != .prompt or id != p.active or pane.prompt == .del_side) continue; + const typed = panes.File.displayWidth(text[0..@min(@as(usize, @intCast(@max(0, pane.input.cur_col))), text.len)]); const dropped = shown - panes.File.displayWidth(kept); if (typed < dropped) continue; - p.surface.tag_layers[layer_index].cursor = .{ .col = @intCast(pad + typed - dropped), .bar = pane.body.mode == .insert }; + p.surface.tag_layers[layer_index].cursor = .{ .col = @intCast(pad + typed - dropped), .bar = pane.input.mode == .insert }; } } if (p.columnBarHeight() > 0) for (0..p.ncol) |column| { @@ -6877,8 +6857,7 @@ pub const Pardes = struct { .font_role = .tagline, }); const tag = try p.tagText(arena, pane); - const prompt_at = pane.promptAt(); - if (active and pane.tag_edit and prompt_at == null) { + if (active and pane.tag_edit) { const caret = panes.File.rawDisplayCol(tag, pane.tag_col); var scroll: usize = pane.tag_scroll; if (caret < scroll) scroll = caret; @@ -6890,16 +6869,12 @@ pub const Pardes = struct { scroll = panes.File.rawDisplayCol(tag, raw); } pane.tag_scroll = @intCast(scroll); - } else if (!pane.tag_edit or prompt_at != null) pane.tag_scroll = 0; - const tag_cut = if (prompt_at) |at| - @min(tag.len, tag.len - @min(tag.len, pane.tag_tail_len) + at) - else - tag.len; - const tag_start = @min(tag_cut, panes.File.rawAtDisplay(tag, pane.tag_scroll)); - _ = s.print(tx, tag_y, tw, tag[tag_start..tag_cut], tag_style); + } else pane.tag_scroll = 0; + const tag_start = panes.File.rawAtDisplay(tag, pane.tag_scroll); + _ = s.print(tx, tag_y, tw, tag[tag_start..], tag_style); if (tagTintRange(pane, tag, tag.len - curTail(pane).len)) |name| { const lo = @max(name.lo, tag_start); - const hi = @min(name.hi, tag_cut); + const hi = @min(name.hi, tag.len); if (lo < hi) { var col = panes.File.rawDisplayCol(tag, lo) -| pane.tag_scroll; const end = panes.File.rawDisplayCol(tag, hi) -| pane.tag_scroll; @@ -7204,6 +7179,43 @@ test "a prompt chip is a band with its caret, still on the grid, and only the ch for (pane.sel) |selection| try std.testing.expect(selection.state == .none); } +test "a prompt is typed on its own line in the notice band and leaves the tag row alone" { + if (platform == .web) return; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = try p.setTestFile("one two\n"); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + const tag_before = try std.testing.allocator.dupe(Cell, p.surface.tag_layers[0].cells); + defer std.testing.allocator.free(tag_before); + + p.update(.{ .key = .{ .cp = '/' } }); + p.update(.{ .key = .{ .cp = 't', .text = "tw" } }); + p.update(.{ .key = .{ .cp = Key.left } }); + try std.testing.expect(pane.prompt == .search and !pane.tag_edit); + try std.testing.expectEqualStrings(config.search_marker ++ "tw", pane.promptText().?); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + // The tagline is exactly what it was: nothing of the prompt is in it. + try std.testing.expectEqual(tag_before.len, p.surface.tag_layers[0].cells.len); + for (tag_before, p.surface.tag_layers[0].cells) |was, is| try std.testing.expect(was.visuallyEqual(&is)); + try std.testing.expect(p.surface.tag_layers[0].cursor == null); + // The band carries the answer and the caret, one cell back from its end. + const band = for (p.surface.tagLayers()) |*layer| { + if (layer.cols != 0 and layer.kind == .notice) break layer; + } else return error.NoPromptBand; + const caret = band.cursor orelse return error.MissingBandCaret; + try std.testing.expectEqualStrings("t", band.cells[caret.col - 1].grapheme()); + try std.testing.expectEqualStrings("w", band.cells[caret.col].grapheme()); + const grid = p.surface.cursor orelse return error.MissingPromptCursor; + try std.testing.expectEqual(p.bodyTop(p.rects[0]), grid.y); + + // Submitting searches for what was typed and gives the prompt its line back. + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(pane.prompt == .none and pane.input.own == null); +} + test "a stillborn pane gives its column to the first pane that joins it" { if (platform == .web) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 40 }); diff --git a/test/panes.zig b/test/panes.zig index 4c969ab5..f1adafee 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -1353,8 +1353,9 @@ test "paste into pane commands and prompts never inserts into the body" { try std.testing.expect(std.mem.endsWith(u8, pane.tagSlice(), " CustomCommand")); p.update(.{ .key = .{ .cp = Key.escape } }); p.startPrompt(pane, .{ .search = config.search_marker }); - p.update(.{ .paste = "two" }); - try std.testing.expect(std.mem.endsWith(u8, pane.tagSlice(), "two")); + p.update(.{ .paste = "t\r\nwo" }); + try std.testing.expectEqualStrings(config.search_marker ++ "two", pane.promptText().?); + try std.testing.expect(std.mem.endsWith(u8, pane.tagSlice(), " CustomCommand")); try std.testing.expectEqualStrings("one two one\n", pane.file.?.content); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expect(std.mem.endsWith(u8, pane.tagSlice(), " CustomCommand")); @@ -1646,7 +1647,7 @@ test "terminal eviction and lower-region scrolling in one read preserve a surviv try std.testing.expectEqualStrings("kept edit", pane.ovl.?.text); } -test "tag prompt entry and cancellation preserve exact text and cursor state" { +test "a prompt's entry and cancellation leave the tag, the body and its cursor as they were" { const Case = struct { key: ?Key = null, save: bool = false, marker: []const u8 }; const cases = [_]Case{ .{ .marker = config.search_marker }, @@ -1665,8 +1666,6 @@ test "tag prompt entry and cancellation preserve exact text and cursor state" { @memcpy(pane.tag_tail[0..tail.len], tail); pane.tag_tail_len = tail.len; pane.tag_init = true; - pane.tag_sel = true; - pane.tag_col = 1; pane.body.cur_row = 1; pane.body.cur_col = 2; pane.body.cur_pinned = true; @@ -1677,16 +1676,16 @@ test "tag prompt entry and cancellation preserve exact text and cursor state" { } else { p.startPrompt(pane, .{ .search = config.search_marker }); } - try std.testing.expect(pane.tag_edit); - try std.testing.expect(!pane.tag_sel); - try std.testing.expectEqual(.insert, pane.body.mode); + // The answer is typed into the prompt's own line, never the tag. + try std.testing.expect(!pane.tag_edit); + try std.testing.expectEqual(.insert, pane.input.mode); + try std.testing.expectEqualStrings(case.marker, pane.promptText().?); + try std.testing.expectEqual(@as(i32, @intCast(case.marker.len)), pane.input.cur_col); + try std.testing.expectEqualStrings(tail, pane.tag_tail[0..pane.tag_tail_len]); try std.testing.expectEqualDeep(modal.Normal.State{}, pane.body.normal); - try std.testing.expectEqualStrings(tail, pane.tag_tail[0..tail.len]); - try std.testing.expectEqualStrings(case.marker, pane.tag_tail[tail.len..pane.tag_tail_len]); - try std.testing.expectEqual(pane.file.?.path.len + pane.tag_tail_len, pane.tag_col); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expect(pane.prompt == .none); - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.input.own == null); try std.testing.expectEqual(.normal, pane.body.mode); try std.testing.expectEqualStrings(tail, pane.tag_tail[0..pane.tag_tail_len]); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); @@ -1695,28 +1694,23 @@ test "tag prompt entry and cancellation preserve exact text and cursor state" { } } -test "tag prompt capacity refusal leaves the existing tail and input state untouched" { +test "a prompt opens whatever the tag already holds" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("one\n"); @memset(&pane.tag_tail, 'x'); - pane.tag_tail_len = pane.tag_tail.len - 1; + pane.tag_tail_len = pane.tag_tail.len; pane.tag_init = true; - pane.tag_col = 17; - pane.tag_sel = true; for (0..3) |case| { switch (case) { 0 => p.startPrompt(pane, .{ .search = config.search_marker }), 1 => p.startPrompt(pane, .save), else => p.update(.{ .key = .{ .cp = '|' } }), } - try std.testing.expect(pane.prompt == .none); - try std.testing.expect(!pane.tag_edit); - try std.testing.expect(pane.tag_sel); - try std.testing.expectEqual(.normal, pane.body.mode); - try std.testing.expectEqual(@as(u16, 17), pane.tag_col); - try std.testing.expectEqual(pane.tag_tail.len - 1, pane.tag_tail_len); + try std.testing.expect(pane.prompt != .none); + try std.testing.expectEqual(pane.tag_tail.len, pane.tag_tail_len); for (pane.tag_tail) |byte| try std.testing.expectEqual(@as(u8, 'x'), byte); + p.update(.{ .key = .{ .cp = Key.escape } }); } } @@ -1735,7 +1729,7 @@ test "generated output refuses every pipe prompt before seeding the tag" { } } -test "tag prompt owns the pipe behavior through cancellation and submission" { +test "a prompt owns the pipe behavior through cancellation and submission" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("one\ntwo\n"); @@ -1746,7 +1740,7 @@ test "tag prompt owns the pipe behavior through cancellation and submission" { p.startPrompt(pane, .{ .pipe = .append }); p.update(.{ .key = .{ .cp = Key.escape } }); p.startPrompt(pane, .{ .pipe = how }); - try std.testing.expectEqual(how, pane.prompt.pipe.how); + try std.testing.expectEqual(how, pane.prompt.pipe); p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); p.update(.{ .key = .{ .cp = Key.enter } }); const pending = p.pipe.wait orelse return error.MissingPipe; @@ -1758,7 +1752,7 @@ test "tag prompt owns the pipe behavior through cancellation and submission" { } } -test "tag prompt cancellation restores the selection before regex previews" { +test "prompt cancellation restores the selection before regex previews" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("one two one"); @@ -1786,133 +1780,57 @@ test "tag prompt cancellation restores the selection before regex previews" { } } -test "tag prompt prefix allocation failure preserves an already seeded prompt" { +test "a prompt that cannot be opened leaves the open one as it was" { const Request = @typeInfo(@TypeOf(Pardes.startPrompt)).@"fn".params[2].type.?; for ([_]Request{ .{ .search = config.search_marker }, .save, .{ .pipe = .replace }, .{ .pipe = .ignore }, .{ .pipe = .insert }, .{ .pipe = .append } }) |request| { var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); const p = try Pardes.init(failing.allocator(), .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("one\n"); - const tail = " keep /prior"; - @memcpy(pane.tag_tail[0..tail.len], tail); - pane.tag_tail_len = tail.len; - pane.tag_init = true; - pane.prompt = .{ .search = 5 }; - pane.tag_edit = true; - pane.tag_sel = true; - pane.tag_col = 14; - pane.tag_anchor = 7; + p.startPrompt(pane, .{ .search = config.search_marker }); + p.update(.{ .key = .{ .cp = 'p', .text = "prior" } }); pane.body.normal = .{ .count = 9, .prefix = .goto }; - const previous_prompt = pane.prompt; const previous_normal = pane.body.normal; _ = p.scratch.reset(.free_all); failing.fail_index = failing.alloc_index; p.startPrompt(pane, request); try std.testing.expect(failing.has_induced_failure); - try std.testing.expectEqualDeep(previous_prompt, pane.prompt); + try std.testing.expect(pane.prompt == .search); + try std.testing.expectEqualStrings(config.search_marker ++ "prior", pane.promptText().?); try std.testing.expectEqualDeep(previous_normal, pane.body.normal); - try std.testing.expectEqualStrings(tail, pane.tag_tail[0..pane.tag_tail_len]); - try std.testing.expect(pane.tag_edit and pane.tag_sel); - try std.testing.expectEqual(.normal, pane.body.mode); - try std.testing.expectEqual(@as(u16, 14), pane.tag_col); - try std.testing.expectEqual(@as(u16, 7), pane.tag_anchor); + try std.testing.expect(!pane.tag_init and !pane.tag_edit); } } -test "tag prompt Save requires room for its complete directory prefix" { +test "Save's prompt starts from the pane's directory" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("one\n"); for ([_][]const u8{ "/dír space", "/dír space/", "" }) |dir| { try pane.setOwnedCwd(dir); - const slash: usize = @intFromBool(dir.len == 0 or dir[dir.len - 1] != '/'); - const needed = config.save_marker.len + dir.len + slash; - for ([_]usize{ 1, 0 }) |shortfall| { - @memset(&pane.tag_tail, 'x'); - pane.tag_tail_len = pane.tag_tail.len - needed + shortfall; - pane.tag_init = true; - pane.tag_edit = false; - pane.tag_sel = true; - pane.tag_col = 17; - const start = pane.tag_tail_len; - p.startPrompt(pane, .save); - if (shortfall != 0) { - try std.testing.expect(pane.prompt == .none); - try std.testing.expectEqual(start, pane.tag_tail_len); - try std.testing.expect(!pane.tag_edit and pane.tag_sel); - try std.testing.expectEqual(@as(u16, 17), pane.tag_col); - for (pane.tag_tail) |byte| try std.testing.expectEqual(@as(u8, 'x'), byte); - } else { - try std.testing.expect(pane.prompt == .save); - try std.testing.expectEqual(pane.tag_tail.len, pane.tag_tail_len); - try std.testing.expectEqualStrings(config.save_marker, pane.tag_tail[start..][0..config.save_marker.len]); - try std.testing.expectEqualStrings(dir, pane.tag_tail[start + config.save_marker.len ..][0..dir.len]); - try std.testing.expectEqual(@as(u8, '/'), pane.tag_tail[pane.tag_tail_len - 1]); - p.update(.{ .key = .{ .cp = Key.escape } }); - } - } + const slash = if (dir.len == 0 or dir[dir.len - 1] != '/') "/" else ""; + p.startPrompt(pane, .save); + try std.testing.expect(pane.prompt == .save); + const answer = pane.promptText().?; + try std.testing.expect(std.mem.startsWith(u8, answer, config.save_marker)); + try std.testing.expectEqualStrings(dir, answer[config.save_marker.len..][0..dir.len]); + try std.testing.expectEqualStrings(slash, answer[config.save_marker.len + dir.len ..]); + p.update(.{ .key = .{ .cp = Key.escape } }); } } -test "tag prompt successful seeded entry needs one scratch allocation" { +test "a prompt opens with one allocation" { const Request = @typeInfo(@TypeOf(Pardes.startPrompt)).@"fn".params[2].type.?; for ([_]Request{ .{ .search = config.search_marker }, .save, .{ .pipe = .replace }, .{ .pipe = .ignore }, .{ .pipe = .insert }, .{ .pipe = .append } }) |request| { var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); const p = try Pardes.init(failing.allocator(), .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("one\n"); - pane.tag_tail_len = 0; - pane.tag_init = true; _ = p.scratch.reset(.free_all); const before = failing.alloc_index; p.startPrompt(pane, request); try std.testing.expectEqual(before + 1, failing.alloc_index); - try std.testing.expect(pane.tag_edit and pane.body.mode == .insert); - } -} - -test "tag prompt failure may initialize only the default tail" { - const Request = @typeInfo(@TypeOf(Pardes.startPrompt)).@"fn".params[2].type.?; - for ([_]Request{ .{ .search = config.search_marker }, .save, .{ .pipe = .replace }, .{ .pipe = .ignore }, .{ .pipe = .insert }, .{ .pipe = .append } }) |request| { - var saw_seeded_failure = false; - var succeeded = false; - for (0..16) |failure| { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); - const p = try Pardes.init(failing.allocator(), .{ .tty_only = true }); - defer p.deinit(); - const pane = try p.setTestFile("one\n"); - const path = try p.gpa.dupe(u8, "/" ++ "a" ** 2048 ++ ".zig"); - p.gpa.free(pane.file.?.path); - pane.file.?.path = path; - p.seedTail(pane); - try std.testing.expect(pane.tag_init); - const default_tail = pane.tag_tail; - const default_len = pane.tag_tail_len; - pane.tag_init = false; - pane.tag_tail_len = 0; - pane.tag_col = 17; - pane.tag_sel = true; - pane.body.normal = .{ .count = 9, .prefix = .goto }; - const previous_normal = pane.body.normal; - _ = p.scratch.reset(.free_all); - failing.fail_index = failing.alloc_index + failure; - p.startPrompt(pane, request); - if (!failing.has_induced_failure) { - try std.testing.expect(pane.tag_edit and pane.body.mode == .insert); - succeeded = true; - break; - } - try std.testing.expect(pane.prompt == .none); - try std.testing.expect(!pane.tag_edit and pane.tag_sel); - try std.testing.expectEqual(.normal, pane.body.mode); - try std.testing.expectEqualDeep(previous_normal, pane.body.normal); - try std.testing.expectEqual(@as(u16, 17), pane.tag_col); - if (pane.tag_init) { - saw_seeded_failure = true; - try std.testing.expectEqualStrings(default_tail[0..default_len], pane.tag_tail[0..pane.tag_tail_len]); - } else try std.testing.expectEqual(@as(usize, 0), pane.tag_tail_len); - } - try std.testing.expect(succeeded and saw_seeded_failure); + try std.testing.expect(!pane.tag_edit and pane.input.mode == .insert); } } diff --git a/test/pdf.zig b/test/pdf.zig index 52fb62aa..5bc271d4 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -1113,9 +1113,9 @@ test "PDF normal adapter consumes unsupported actions and navigates page fallbac p.update(.{ .key = .{ .cp = '!' } }); try std.testing.expect(!p.leader_on); p.update(.{ .key = .{ .cp = '/' } }); - try std.testing.expect(pane.tag_edit); + try std.testing.expect(pane.prompt == .search and !pane.tag_edit); p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.prompt == .none); } test "Escape cancels PDF chrome in place and Shift-Escape leaves the pane" { diff --git a/test/snapshots/find.golden b/test/snapshots/find.golden index 12dac242..b6b7b322 100644 --- a/test/snapshots/find.golden +++ b/test/snapshots/find.golden @@ -81,7 +81,6 @@ |4: |30: 1 gamma body Last == snap nomatch grid=120x41 cursor=7,39 -|2: /tmp/pardes-snap/find/cwd/here.txt Save Tty Collapse Del Find / |3: 1 Find |18: /tmp/pardes-snap/find/cwd/+Search Save Tty Collapse Del |19: 1 diff --git a/test/snapshots/find.snap b/test/snapshots/find.snap index fbd585f7..fe1ecad3 100644 --- a/test/snapshots/find.snap +++ b/test/snapshots/find.snap @@ -64,7 +64,8 @@ key enter stable 700 15000 snap back # executing the WORD Find (middle-click in a body) arms the same input — the -# enum IS the dispatch — and Esc abandons it, restoring the tag tail +# enum IS the dispatch — and Esc abandons it. The input is its own line, so an +# abandoned one leaves nothing behind in the tag press middle 8 4 release middle 8 4 stable 700 10000 diff --git a/test/snapshots/tagbottomshort.golden b/test/snapshots/tagbottomshort.golden index a5d53fe2..c11fe4ac 100644 --- a/test/snapshots/tagbottomshort.golden +++ b/test/snapshots/tagbottomshort.golden @@ -21,7 +21,7 @@ | New Tty Find Grep Joincol Delcol | 1 one /ZZ | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del -== snap tag-only grid=80x2 cursor=70,1 +== snap tag-only grid=80x2 cursor=79,1 |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del == snap regrown grid=80x11 cursor=79,2 diff --git a/test/snapshots/tagbottomshort.snap b/test/snapshots/tagbottomshort.snap index 2574df36..58da6a87 100644 --- a/test/snapshots/tagbottomshort.snap +++ b/test/snapshots/tagbottomshort.snap @@ -10,8 +10,8 @@ wait 8000 s.txt stable 700 20000 key space t b stable 700 15000 -# `/` with room to spare: the prompt is cut off the tagline (grid 9) and drawn -# on grid 8, the last body row, with the cursor. +# `/` with room to spare: the prompt is its own line, drawn on grid 8, the last +# body row, with the cursor; the tagline (grid 9) never holds any of it. key / send ZZ stable 600 8000 @@ -27,9 +27,8 @@ resize 4 80 stable 700 10000 snap one-body # the tagline alone. No body row, so nothing of the prompt is drawn anywhere — -# not over the tag, not on the row above the pane. The tagline itself is -# untouched: the marker sits after the builtins, so cutting the tail there -# leaves every column of it exactly as `tag-only` would look unarmed. +# not over the tag, not on the row above the pane, and its caret with it. The +# tagline itself is untouched, exactly as `tag-only` would look unarmed. resize 2 80 stable 700 10000 snap tag-only -- cgit v1.3 From 23f430573efe4f6ef55b0180aa0d742ff4eca1d9 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 00:01:57 -0300 Subject: Make a pane's tag a Text edited with the body's own keys The tag was a fixed buffer with its own one-line editor, a cursor measured across the path, and a hijack of the body's mode while it was typed into. It is now the pane's second Text: its own characters after the computed prefix (path, dirty marker, PDF page), which is never stored in it, so a rename or a dirty marker never moves its cursor. Normal and insert mode are the body's, undo included; `:` moves the keyboard between body and tag, the tag remembers its cursor and starts on Save, and executing a word from it hands the keyboard back. The mouse still sees the prefix: a sweep selects across it and a click on the path drafts a new name. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 2 +- src/Pipe.zig | 6 +- src/Terminal.zig | 63 +--- src/Text.zig | 79 ++++- src/body_layer.zig | 5 +- src/colors.zig | 2 +- src/dump.zig | 2 +- src/edit.zig | 41 ++- src/exec.zig | 7 +- src/look.zig | 3 +- src/mouse.zig | 82 ++++-- src/ninep/pane.zig | 44 ++- src/normal.zig | 20 +- src/panes.zig | 66 ++--- src/pardes.zig | 639 +++++++++++++++++------------------------ test/mode.zig | 31 +- test/panes.zig | 384 +++++++++++++------------ test/pdf.zig | 23 +- test/snapshots/cmdword.golden | 4 +- test/snapshots/cmdword.snap | 24 +- test/snapshots/collapse.golden | 4 +- test/snapshots/collapse.snap | 7 +- test/snapshots/tag.snap | 20 +- test/snapshots/tagalign.snap | 9 +- test/snapshots/tagcmd.snap | 20 +- test/snapshots/tagnav.golden | 43 +-- test/snapshots/tagnav.snap | 136 +++------ test/snapshots/tagpath.golden | 23 +- test/snapshots/tagpath.snap | 28 +- test/snapshots/ttyclick.golden | 4 - test/snapshots/ttyclick.snap | 14 +- 31 files changed, 856 insertions(+), 979 deletions(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index bf4bf08c..2bf9f57d 100644 --- a/src/File.zig +++ b/src/File.zig @@ -1129,7 +1129,7 @@ pub fn drawGutter(p: *Pardes, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, bod const goff = pane.scroll(); const gcur = Terminal.gridCursor(pane); const gcrow = if (pane.body.cur_pinned) pane.body.cur_row else @as(i32, gcur.y) + goff; - const typing_body = !pane.tag_edit and (pane.prompt == .none or pane.prompt == .del_side); + const typing_body = pane.focus == .body and (pane.prompt == .none or pane.prompt == .del_side); const cur_line: i32 = if (active and typing_body) gcrow else std.math.minInt(i32); // the body's first row, the way renderPane derives it (Tagbottom) const body_y = p.bodyTop(r); diff --git a/src/Pipe.zig b/src/Pipe.zig index 3e6752a8..4cabfd88 100644 --- a/src/Pipe.zig +++ b/src/Pipe.zig @@ -294,12 +294,12 @@ test "selection pipe prompt submits exact request and Escape cancels" { pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; p.update(.{ .key = .{ .cp = '|' } }); - try std.testing.expect(!pane.tag_edit and pane.prompt == .pipe); + try std.testing.expect(pane.focus == .body and pane.prompt == .pipe); try std.testing.expectEqualStrings(config.pipe_marker, pane.promptText().?); try std.testing.expect(nextPipeEffect(p) == null); p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); p.update(.{ .key = .{ .cp = Key.enter } }); - try std.testing.expect(!pane.tag_edit and pane.prompt != .pipe and pane.input.own == null); + try std.testing.expect(pane.focus == .body and pane.prompt != .pipe and pane.input.own == null); const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; const request = p.pipe.pipeRequest(id) orelse return error.MissingPipeRequest; try std.testing.expectEqualStrings("tr a-z A-Z", request.command); @@ -311,7 +311,7 @@ test "selection pipe prompt submits exact request and Escape cancels" { p.update(.{ .key = .{ .cp = '|' } }); p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expect(!pane.tag_edit and pane.prompt != .pipe); + try std.testing.expect(pane.focus == .body and pane.prompt != .pipe); try std.testing.expectEqualSlices(u8, before, pane.file.?.content); try std.testing.expect(nextPipeEffect(p) == null); } diff --git a/src/Terminal.zig b/src/Terminal.zig index fbe7bfc0..7b5af696 100644 --- a/src/Terminal.zig +++ b/src/Terminal.zig @@ -686,8 +686,7 @@ pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void { const at_bottom = atBottom(pane); if (has_positions) ingestWithPositions(pane, bytes) else ingest(pane, bytes); p.shell_rows.markStale(pane); - const body_mode = if (pane.tag_edit) pane.tag_mode else pane.body.mode; - if (body_mode == .tty and at_bottom) followOutput(pane); + if (pane.body.mode == .tty and at_bottom) followOutput(pane); } const RowPin = struct { pin: ?*ghostty_vt.Pin = null, offset: i32 = 0 }; @@ -2463,64 +2462,22 @@ pub fn padOutputBelowEdits(p: *Pardes, id: usize) void { while (i < pad) : (i += 1) p.emitWrite(id, "\r"); } -/// the snapshot takes ownership of a COPY of the edit buffer's text -pub fn snap(p: *Pardes, pane: *Pane) ?Snapshot { - var ovl: ?EditBuffer = null; - if (pane.ovl) |o| ovl = .{ .row = o.row, .rows = o.rows, .text = p.gpa.dupe(u8, o.text) catch return null }; - return .{ .ovl = ovl, .cur_row = pane.body.cur_row, .cur_col = pane.body.cur_col, .vsel = pane.body.vsel }; -} - -/// undo/redo restores the selection recorded with the snapshot (helix -/// keeps selections in its history transactions) -pub fn restoreSnap(p: *Pardes, pane: *Pane, s: Snapshot) void { - if (pane.ovl) |o| p.gpa.free(o.text); - pane.ovl = s.ovl; - pane.body.cur_row = s.cur_row; - pane.body.cur_col = s.cur_col; - pane.body.cur_pinned = true; - pane.body.vsel = s.vsel; - pane.body.msel.active = false; - pane.ensureCursorVisible(); -} - -fn pushHistory(gpa: std.mem.Allocator, slots: []Snapshot, len: *usize, value: Snapshot) void { - if (len.* == slots.len) { - if (slots[0].ovl) |overlay| gpa.free(overlay.text); - std.mem.copyForwards(Snapshot, slots[0 .. slots.len - 1], slots[1..]); - len.* -= 1; - } - slots[len.*] = value; - len.* += 1; -} - pub fn pushUndo(p: *Pardes, pane: *Pane) void { - const current = pane.ovl orelse EditBuffer{ .rows = 0 }; - if (pane.body.ed_undo_len > 0) { - const top = pane.body.ed_undo[pane.body.ed_undo_len - 1]; - const same = if (top.ovl) |overlay| pane.ovl != null and overlay.row == current.row and - overlay.rows == current.rows and std.mem.eql(u8, overlay.text, current.text) else pane.ovl == null; - if (same) return; - } - const value = snap(p, pane) orelse return; - pushHistory(p.gpa, &pane.body.ed_undo, &pane.body.ed_undo_len, value); - for (pane.body.ed_redo[0..pane.body.ed_redo_len]) |item| if (item.ovl) |overlay| p.gpa.free(overlay.text); - pane.body.ed_redo_len = 0; + pane.body.remember(p.gpa, pane.ovl); } pub fn undo(p: *Pardes, pane: *Pane) void { - if (pane.body.ed_undo_len == 0) return; - const current = snap(p, pane) orelse return; - pushHistory(p.gpa, &pane.body.ed_redo, &pane.body.ed_redo_len, current); - pane.body.ed_undo_len -= 1; - restoreSnap(p, pane, pane.body.ed_undo[pane.body.ed_undo_len]); + const back_to = pane.body.step(p.gpa, pane.ovl, true) orelse return; + if (pane.ovl) |o| p.gpa.free(o.text); + pane.ovl = back_to.ovl; + pane.ensureCursorVisible(); } pub fn redo(p: *Pardes, pane: *Pane) void { - if (pane.body.ed_redo_len == 0) return; - const current = snap(p, pane) orelse return; - pushHistory(p.gpa, &pane.body.ed_undo, &pane.body.ed_undo_len, current); - pane.body.ed_redo_len -= 1; - restoreSnap(p, pane, pane.body.ed_redo[pane.body.ed_redo_len]); + const forward_to = pane.body.step(p.gpa, pane.ovl, false) orelse return; + if (pane.ovl) |o| p.gpa.free(o.text); + pane.ovl = forward_to.ovl; + pane.ensureCursorVisible(); } pub fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: [:0]const u8) void { diff --git a/src/Text.zig b/src/Text.zig index aaa6dc88..3e48a42e 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -1,11 +1,11 @@ //! One editable text, acme's Text (editors/acme/dat.h:171-190, text.c): the //! cursor, the selections and the modal state that edit it, and the undo of -//! an edit buffer. A pane's body is one, and so is the answer typed into a -//! pane's prompt. Where a body's characters come from -- a file's content, a -//! terminal's edit overlay, a PDF's text -- is the window's business -//! (edit.zig's editText and flatSurface), the way acme's Text reads its File; -//! every other text owns its characters. Everything here works on the flat -//! text it is handed. +//! an edit buffer. A pane's body is one, its tag is another, and so is the +//! answer typed into a pane's prompt. Where a body's characters come from -- +//! a file's content, a terminal's edit overlay, a PDF's text -- is the +//! window's business (edit.zig's editText and flatSurface), the way acme's +//! Text reads its File; every other text owns its characters. Everything +//! here works on the flat text it is handed. const std = @import("std"); const panes = @import("panes.zig"); const modal = @import("modal.zig"); @@ -19,7 +19,7 @@ pub const Mode = enum { normal, insert, tty }; /// Which text of its window this is, acme's `what`. It says where the /// characters live and whether moving the cursor scrolls a body. -pub const What = enum { body, input }; +pub const What = enum { body, tag, input }; /// A modal line selection (helix `x`): whole rows [r0, r1], absolute. pub const LineSel = struct { @@ -49,7 +49,8 @@ pub const SelRange = struct { what: What = .body, /// The characters of a text that holds its own (gpa-owned): everything but -/// a body, which reads its pane's. +/// a body, which reads its pane's. A tag nobody has changed has none yet and +/// shows the default its pane's kind starts with. own: ?[]u8 = null, mode: Mode = .normal, cur_pinned: bool = false, @@ -77,12 +78,14 @@ ed_redo_len: usize = 0, pub fn pane(t: *Text) *Pane { return switch (t.what) { .body => @alignCast(@fieldParentPtr("body", t)), + .tag => @alignCast(@fieldParentPtr("tag", t)), .input => @alignCast(@fieldParentPtr("input", t)), }; } /// Bring the cursor into view (acme's textshow). Only a body scrolls to it; -/// a prompt's answer is drawn whole. +/// the tagline follows its caret where it is drawn, and a prompt's answer is +/// drawn whole. pub fn show(t: *Text) void { if (t.what == .body) t.pane().ensureCursorVisible(); } @@ -273,8 +276,8 @@ pub fn multiSelAction(t: *Text, text: []const u8, kind: modal.Normal.Multi, cnt: return setRanges(t, text, out[0..m], &.{}, @min(got.pri, m - 1), expl); } if (kind == .rotate_forward or kind == .rotate_backward) { - const step = cnt % n; - const pri = if (kind == .rotate_forward) (got.pri + step) % n else (got.pri + (n - step)) % n; + const turn = cnt % n; + const pri = if (kind == .rotate_forward) (got.pri + turn) % n else (got.pri + (n - turn)) % n; return setRanges(t, text, rs[0..n], &.{}, pri, expl); } if (kind == .merge) { @@ -510,6 +513,8 @@ pub fn visualMove( /// Ctrl-d/u: scroll half a page AND move the cursor by the same rows pub fn halfPageMove(t: *Text, text: []const u8, range: modal.Selection, down: bool) void { + // a view to move through is a body's; a tag or an answer is all shown + if (t.what != .body) return; const half: i32 = @max(1, @divTrunc(@as(i32, t.pane().rows), 2)); t.pane().scrollBy(if (down) half else -half); verticalMove(t, text, range, down, @intCast(half)); @@ -518,6 +523,8 @@ pub fn halfPageMove(t: *Text, text: []const u8, range: modal.Selection, down: bo /// helix `scroll` without cursor sync (Ctrl-f/b, PgUp/PgDn, zj/zk): shift /// the view, then snap a fallen-out cursor to the near scrolloff edge, col 0 pub fn scrollViewMove(t: *Text, text: []const u8, range: modal.Selection, delta: i32) void { + // a view to move through is a body's; a tag or an answer is all shown + if (t.what != .body) return; const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, t.pane().rows) - 1, 2)); t.pane().scrollBy(delta); const top = t.pane().scroll(); @@ -540,6 +547,8 @@ pub fn scrollViewMove(t: *Text, text: []const u8, range: modal.Selection, delta: /// gt/gc/gb: view-relative rows, col 0, scrolloff clamped (helix goto_window) pub fn gotoWindow(t: *Text, text: []const u8, range: modal.Selection, which: enum { top, center, bottom }, cnt: usize) void { + // a view to move through is a body's; a tag or an answer is all shown + if (t.what != .body) return; const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, t.pane().rows) - 1, 2)); const top = t.pane().scroll(); const last_row: i32 = @intCast(File.textLineCount(t, text) - 1); @@ -623,3 +632,51 @@ pub fn clampCursor(t: *Text, text: []const u8, row0: i32) void { t.msel.active = false; t.show(); } + +fn pushHistory(gpa: std.mem.Allocator, slots: []Terminal.Snapshot, len: *usize, value: Terminal.Snapshot) void { + if (len.* == slots.len) { + if (slots[0].ovl) |overlay| gpa.free(overlay.text); + std.mem.copyForwards(Terminal.Snapshot, slots[0 .. slots.len - 1], slots[1..]); + len.* -= 1; + } + slots[len.*] = value; + len.* += 1; +} + +/// Record an edit buffer (a terminal's overlay, a tag's own text) as it +/// stands before an edit, once per change of it, and forget what could have +/// been redone. Null is a buffer not made yet. +pub fn remember(t: *Text, gpa: std.mem.Allocator, current: ?Terminal.EditBuffer) void { + if (t.ed_undo_len > 0) { + const top = t.ed_undo[t.ed_undo_len - 1]; + const same = if (top.ovl) |overlay| if (current) |now| overlay.row == now.row and + overlay.rows == now.rows and std.mem.eql(u8, overlay.text, now.text) else false else current == null; + if (same) return; + } + const copy: ?Terminal.EditBuffer = if (current) |now| .{ .row = now.row, .rows = now.rows, .text = gpa.dupe(u8, now.text) catch return } else null; + pushHistory(gpa, &t.ed_undo, &t.ed_undo_len, .{ .ovl = copy, .cur_row = t.cur_row, .cur_col = t.cur_col, .vsel = t.vsel }); + for (t.ed_redo[0..t.ed_redo_len]) |item| if (item.ovl) |overlay| gpa.free(overlay.text); + t.ed_redo_len = 0; +} + +/// Undo (back) or redo one edit of an edit buffer: `current` goes on the +/// other history and the state to return to comes back, its cursor and +/// selection already restored here. The caller installs its buffer, which +/// it then owns. Null when there is nothing to step to. +pub fn step(t: *Text, gpa: std.mem.Allocator, current: ?Terminal.EditBuffer, back: bool) ?Terminal.Snapshot { + const from, const from_len, const to, const to_len = if (back) + .{ &t.ed_undo, &t.ed_undo_len, &t.ed_redo, &t.ed_redo_len } + else + .{ &t.ed_redo, &t.ed_redo_len, &t.ed_undo, &t.ed_undo_len }; + if (from_len.* == 0) return null; + const copy: ?Terminal.EditBuffer = if (current) |now| .{ .row = now.row, .rows = now.rows, .text = gpa.dupe(u8, now.text) catch return null } else null; + pushHistory(gpa, to, to_len, .{ .ovl = copy, .cur_row = t.cur_row, .cur_col = t.cur_col, .vsel = t.vsel }); + from_len.* -= 1; + const back_to = from[from_len.*]; + t.cur_row = back_to.cur_row; + t.cur_col = back_to.cur_col; + t.cur_pinned = true; + t.vsel = back_to.vsel; + t.msel.active = false; + return back_to; +} diff --git a/src/body_layer.zig b/src/body_layer.zig index 1f210220..e85e10f1 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -363,6 +363,9 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id for (pane.sel, 0..) |sl, b| { if (sl.state == .none) continue; if (sl.state == .done and b != 0) continue; + // A select sweep over the tag is the tag's selection, painted there + // in the tag's own selection colours. + if (b == pardes.sel_slot and @min(sl.r0, sl.r1) < BOX_H) continue; paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, sl, sel_btn[b], th.sel_fg); } // modal line selection (helix `x`): whole body rows, normal mode only @@ -461,7 +464,7 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id // cursor: tracks the shell cursor until pinned by a click or a key // (the tag's or a prompt's cursor wins while that is being typed into) - if (active and !pane.tag_edit and (pane.prompt == .none or pane.prompt == .del_side)) { + if (active and pane.focus == .body and (pane.prompt == .none or pane.prompt == .del_side)) { if (pane.body.mode != .tty) { const cur = panes.Terminal.gridCursor(pane); const goff = panes.Terminal.gridOffset(pane); diff --git a/src/colors.zig b/src/colors.zig index 741187c6..f92f67b1 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -602,7 +602,7 @@ test "line numbers stay quiet without a current-line tag background" { const moved = try p.render(p.scratch.allocator()); try std.testing.expect(!moved.at(x, y).style.bold); try std.testing.expect(moved.at(x, y + 1).style.bold); - p.enterTagEdit(pane, -1); + p.enterTag(pane); const tag_edit = try p.render(p.scratch.allocator()); try std.testing.expect(!tag_edit.at(x, y + 1).style.bold); } diff --git a/src/dump.zig b/src/dump.zig index 2fb9ce80..7112e1f0 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -621,7 +621,7 @@ pub fn dumpState(p: *Pardes) !void { try pardes.panes.Image.dumpPane(p, arena, pane, tag, body, scroll, iv.path, iv.raw) else try pardes.panes.Terminal.dumpPane(pane, arena, tag, body, scroll); - dp.tag_tail = if (pane.tag_init) pane.tagSlice() else null; + dp.tag_tail = pane.tag.own; dump_panes[panes_len] = dp; panes_len += 1; } diff --git a/src/edit.zig b/src/edit.zig index 5249a64c..02e138e8 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -96,18 +96,12 @@ pub fn applyPaste(p: *Pardes, bytes: []const u8) void { if (normal.selRegexArmed(pane)) |a| normal.applySelRegex(p, pane, a.pat, a.split); return; } - if (pane.tag_edit) { - const text = p.tagText(p.scratch.allocator(), pane) catch return; - const range: @TypeOf(Pardes.tagSelBounds(pane)) = if (pane.tag_sel) Pardes.tagSelBounds(pane) else .{ .lo = pane.tag_col, .hi = pane.tag_col }; - const hi = if (pane.tag_sel) modal.nextGrapheme(text, range.hi) else range.hi; - _ = p.replaceTagText(pane, range.lo, hi, bytes); - return; - } - if (pane.isTerminal() and pane.body.mode == .tty) return typeToTty(p, id, pane, bytes); + const t = if (pane.focus == .tag) &pane.tag else &pane.body; + if (t.what == .body and pane.isTerminal() and pane.body.mode == .tty) return typeToTty(p, id, pane, bytes); switch (if (req) |r| r.mode else .after) { - .after => pasteText(p, &pane.body, bytes, false, 1), - .before => pasteText(p, &pane.body, bytes, true, 1), - .replace => replaceWithText(p, &pane.body, bytes), + .after => pasteText(p, t, bytes, false, 1), + .before => pasteText(p, t, bytes, true, 1), + .replace => replaceWithText(p, t, bytes), } } @@ -301,7 +295,7 @@ pub fn exitInsert(p: *Pardes, t: *Text) void { pub fn paneCursorLines(p: *Pardes, t: *Text) ![]const []const u8 { const arena = p.scratch.allocator(); if (t.what != .body) { - const text = t.own orelse ""; + const text = try flatSurface(p, t); const lines = try arena.alloc([]const u8, std.mem.count(u8, text, "\n") + 1); var it = std.mem.splitScalar(u8, text, '\n'); for (lines) |*line| line.* = it.next().?; @@ -346,6 +340,7 @@ pub fn pinPaneCursor(p: *Pardes, t: *Text) void { } pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { + if (t.what == .tag) return Pardes.curTail(t.pane()); if (t.what != .body) return t.own orelse ""; const pane = t.pane(); if (pane.file) |f| return f.content; @@ -367,6 +362,10 @@ pub fn paneWrapWidth(p: *const Pardes, t: *Text) usize { /// Route shared edit operations to the characters `t` edits: its own, or /// for a body its file's content or its terminal's overlay. fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText { + // A tag nobody has changed shows its default; the first edit makes that + // default its own text. + if (t.what == .tag and t.own == null) + t.own = p.gpa.dupe(u8, Pardes.defaultTail(t.pane())) catch return null; if (t.what != .body) return .{ .text = t.own orelse &.{}, .row0 = 0 }; const pane = t.pane(); if (pane.file) |f| return .{ .text = f.content, .row0 = 0 }; @@ -1544,14 +1543,19 @@ pub fn surroundReplace(p: *Pardes, t: *Text, from: u21, to: u21) void { pub fn pushUndo(p: *Pardes, t: *Text) void { // one keystroke, one undo step — even when it edited at ten cursors. if (p.multi_on and !p.multi_first) return; - // a prompt's answer is typed once and gone; it keeps no history - if (t.what != .body) return; + switch (t.what) { + .body => {}, + .tag => return t.remember(p.gpa, if (t.own) |own| .{ .text = own } else null), + // a prompt's answer is typed once and gone; it keeps no history + .input => return, + } const pane = t.pane(); if (pane.file != null) return panes.File.pushUndo(p, pane); panes.Terminal.pushUndo(p, pane); } pub fn doUndo(p: *Pardes, t: *Text) void { + if (t.what == .tag) return stepOwn(p, t, true); if (t.what != .body) return; const pane = t.pane(); if (pane.file != null) return panes.File.undo(p, pane); @@ -1559,12 +1563,21 @@ pub fn doUndo(p: *Pardes, t: *Text) void { } pub fn doRedo(p: *Pardes, t: *Text) void { + if (t.what == .tag) return stepOwn(p, t, false); if (t.what != .body) return; const pane = t.pane(); if (pane.file != null) return panes.File.redo(p, pane); panes.Terminal.redo(p, pane); } +/// Undo or redo an edit of a text's own characters; stepping back past its +/// first edit gives a tag its default again. +fn stepOwn(p: *Pardes, t: *Text, back: bool) void { + const to = t.step(p.gpa, if (t.own) |own| .{ .text = own } else null, back) orelse return; + if (t.own) |own| p.gpa.free(own); + t.own = if (to.ovl) |buffer| buffer.text else null; +} + const PointerTextSelection = struct { sel: Pane.Sel, on_tag: bool, diff --git a/src/exec.zig b/src/exec.zig index a2dbac7c..82b3da4a 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -260,8 +260,9 @@ pub fn saveTo(p: *Pardes, id: usize, path: []const u8) void { f.output = null; // an ordinary file pane from here on f.watch_after_save = true; pane.clearCwd(); - pane.tag_init = false; // re-derive the tag as a plain file - pane.tag_tail_len = 0; + // re-derive the tag as a plain file's + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = null; p.emit(.{ .save_file = .{ .pane = @intCast(id) } }); return; } @@ -351,7 +352,7 @@ pub fn replaceStillborn(p: *Pardes) void { const out = file.output orelse return; if (out.from != .cmd or out.from.cmd != .New) return; if (file.revision != 0 or file.content.len != 0) return; - if (old.tag_init and !std.mem.eql(u8, old.tagSlice(), Pardes.defaultTail(old))) return; + if (old.tag.own) |own| if (!std.mem.eql(u8, own, Pardes.defaultTail(old))) return; const was_active = p.active == old_id; layout.compute(p); // the joiner may have no rect yet; absorb snaps to rows p.removePane(old_id, new_id) catch |err| return p.reportError(old_id, "close", err); diff --git a/src/look.zig b/src/look.zig index efc3f312..6f9f8c6a 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1150,8 +1150,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand: []const u8) void { const found = resolveLookTarget(p, id, txt, &realbuf); switch (found) { .none => { - const bmode = if (pane.tag_edit) pane.tag_mode else pane.body.mode; - if (pane.image != null or bmode == .tty) return; + if (pane.image != null or pane.body.mode == .tty) return; runSearch(p, id, trimmed, .text, .cursor) catch |err| { p.reportError(id, "search", err); return; diff --git a/src/mouse.zig b/src/mouse.zig index 5f77634b..ae047c58 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -39,7 +39,6 @@ pub const Drag = union(enum) { /// `grab`: how far into the grip it was pressed, so the column's left /// edge lands at `cur_x - grab`. A release still on the grip moves nothing. column_move: struct { serial: u32, cur_x: u16, grab: u16 = 0 }, - tag: struct { id: usize }, /// chorded: a 1-2/1-3 cut/paste chord fired during this left drag — /// the drag's own release is then inert select: struct { @@ -55,7 +54,7 @@ pub const Drag = union(enum) { fn button(drag: Drag) ?Mouse.Button { return switch (drag) { .none => null, - .border_v, .border_h, .move, .column_move, .tag => config.select_button, + .border_v, .border_h, .move, .column_move => config.select_button, .select => |selection| selection.button, }; } @@ -228,7 +227,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { const previous_tag_hit = p.pointer_tag_hit; p.pointer_tag_hit = if (m.tag_hit) |point| p.reprojectTagHit(point) else null; if (m.tag_hit != null and p.pointer_tag_hit == null and m.kind == .press) return; - if (m.tag_hit == null and (m.kind == .drag or m.kind == .release) and (p.drag == .tag or p.drag == .select or p.header_drag)) { + if (m.tag_hit == null and (m.kind == .drag or m.kind == .release) and (p.drag == .select or p.header_drag)) { if (previous_tag_hit) |previous| { var continued = previous; continued.pixel_x = (@as(f32, @floatFromInt(raw_col)) + 0.5) * @as(f32, @floatFromInt(previous.metrics.body_w)); @@ -236,7 +235,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { p.pointer_tag_hit = continued; } } - if ((m.kind == .drag or m.kind == .release) and (p.drag == .tag or p.drag == .select or p.header_drag)) { + if ((m.kind == .drag or m.kind == .release) and (p.drag == .select or p.header_drag)) { if (previous_tag_hit) |previous| if (p.pointer_tag_hit) |*current| { current.kind = previous.kind; current.id = previous.id; @@ -303,7 +302,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { (m.button == config.select_button or m.button == config.exec_button or m.button == config.look_button)) { if (m.button == config.select_button) if (p.panes[p.active]) |pane| { - if (pane.tag_edit) Pardes.exitTagEdit(pane); + pane.focus = .body; pane.closePrompt(); }; var column: ?usize = null; @@ -439,7 +438,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { const r = p.rects[id]; const pane = p.panes[id] orelse return; if (id != p.active) if (p.panes[p.active]) |previous| { - if (previous.tag_edit) Pardes.exitTagEdit(previous); + previous.focus = .body; previous.closePrompt(); }; const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; @@ -448,20 +447,29 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { // gutter scrollbar: a left click scrolls UP to that row p.active = id; pane.scrollBy(-(@as(i32, mrow) - @as(i32, body_y))); - } else if (mrow >= tag_y and mrow < tag_y + BOX_H) { - if (mcol < r.x + TAG_TEXT_INSET) return; - p.active = id; - pane.closePrompt(); - p.enterTagEdit(pane, if (tagColumn(p, .pane, id, p.pointer_tag_hit, false)) |value| @as(i32, value) else @as(i32, mcol) - @as(i32, r.x + TAG_TEXT_INSET)); - pane.tag_anchor = pane.tag_col; - p.drag = .{ .tag = .{ .id = id } }; } else { + const on_tag = mrow >= tag_y and mrow < tag_y + BOX_H; + if (on_tag and mcol < r.x + TAG_TEXT_INSET) return; p.active = id; - if (pane.tag_edit) Pardes.exitTagEdit(pane); pane.closePrompt(); const pointed = edit.pointerTextSelection(p, id, mcol, mrow, m.body_hit, p.pointer_tag_hit) orelse return; pane.clearPointerSelection(sel_slot); pane.sel[sel_slot] = pointed.sel; + // A clicked tag is typed straight into, from where it was + // clicked; `:` is the door to its normal mode. + pane.focus = if (on_tag) .tag else .body; + if (on_tag) { + // a count typed before the click was meant for the body + pane.body.normal.clear(); + pane.tag.mode = .insert; + pane.tag.normal.clear(); + pane.tag.vsel.active = false; + pane.tag.msel.active = false; + pane.tag.nsel = 0; + pane.tag.cur_pinned = true; + pane.tag.cur_row = 0; + pane.tag.cur_col = @intCast(p.tagOffsetAt(pane, @intCast(@max(0, pointed.sel.c0))) orelse 0); + } p.drag = .{ .select = .{ .id = id, .button = config.select_button, @@ -472,7 +480,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { config.select_button, mcol, mrow, - false, + pointed.on_tag, ), } }; } @@ -617,13 +625,6 @@ pub fn dragUpdate(p: *Pardes, mcol: u16, mrow: u16, body_hit: ?Mouse.BodyHit) vo panes.Pdf.pointerUpdate(&s.pdf, p, pane, mcol, mrow); } }, - .tag => |d| { - const pane = p.panes[d.id] orelse return; - const c = if (tagColumn(p, .pane, d.id, p.pointer_tag_hit, true)) |value| @as(i32, value) else @as(i32, mcol) - @as(i32, p.rects[d.id].x + TAG_TEXT_INSET); - const text = p.tagText(p.scratch.allocator(), pane) catch return; - pane.tag_col = @intCast(@min(text.len, panes.File.rawAtDisplay(text, @as(usize, @intCast(@max(0, c))) + pane.tag_scroll))); - pane.tag_sel = pane.tag_col != pane.tag_anchor; - }, .none => {}, } } @@ -816,6 +817,16 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { const sl = pane.sel[sel_slot]; const dragged = sl.c0 != sl.c1 or sl.r0 != sl.r1; if (!dragged) pane.sel[sel_slot].state = .none; + if (sl.r0 < BOX_H) { + // On the tag the caret goes where the button came up. A + // click on the path, if it can be renamed, drafts a name. + const at = p.tagOffsetAt(pane, @intCast(@max(0, sl.c1))); + if (at) |col| { + pane.tag.cur_row = 0; + pane.tag.cur_col = @intCast(col); + } else if (!dragged) p.draftName(pane, @intCast(@max(0, sl.c1))); + return; + } if (dragged) edit.capturePointerSelection(p, pane, sel_slot) catch {}; if (dragged and pane.body.mode == .tty) mirrorTtySelection(p, pane); const body_vis = sl.r1 - @as(i32, BOX_H); @@ -869,7 +880,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { } const txt = operand.text; const cmd = if (s.button == config.look_button) config.look_cmd else config.exec_cmd; - if (clk.r0 < BOX_H and s.button == config.exec_button and pane.tag_name_len != null) { + if (clk.r0 < BOX_H and s.button == config.exec_button and pane.prompt == .name) { const prefix_width = panes.File.displayWidth(p.tagPrefix(pane) catch return); const on_name = @as(usize, @intCast(@max(0, clk.c0))) < prefix_width; if (!p.commitTagName(pane)) return; @@ -895,7 +906,6 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { }); } }, - .tag => {}, // dragUpdate already left the tag cursor + selection set .none => {}, } } @@ -913,6 +923,30 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { if (cut and pv.selection_text.len > 0) edit.setYank(p, pv.selection_text); return; }; + if (@min(pane.sel[sel_slot].r0, pane.sel[sel_slot].r1) < BOX_H) { + // A sweep over the tag cuts from and pastes into the tag's own text; + // the part of it over the prefix is not the tag's to cut. + const t = &pane.tag; + if (!s.chorded) { + s.chorded = true; + const sl = pane.sel[sel_slot]; + pane.sel[sel_slot].state = .none; + const from = p.tagOffsetAt(pane, @intCast(@max(0, @min(sl.c0, sl.c1)))) orelse 0; + const to = p.tagOffsetAt(pane, @intCast(@max(0, @max(sl.c0, sl.c1)))) orelse 0; + t.cur_row = 0; + t.cur_col = @intCast(to); + t.cur_pinned = true; + t.vsel = .{ .active = from != to, .row = 0, .col = @intCast(from), .explicit = false }; + t.msel.active = false; + t.nsel = 0; + } + if (cut) { + if (t.vsel.active) edit.normalDelete(p, t, true); + } else if (t.vsel.active) { + edit.normalReplaceYank(p, t); + } else edit.pasteText(p, t, p.yank orelse return, true, 1); + return; + } if (pane.body.mode == .tty) { if (!s.chorded) { s.chorded = true; diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 7e9cf7e7..282ae473 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -15,6 +15,7 @@ const addressing = @import("addr.zig"); const ctl = @import("ctl.zig"); const pty = @import("pty.zig"); const screen = @import("screen.zig"); +const limits = @import("../memory.zig").limits; const Pardes = pardes.Pardes; const Pane = pardes.Pane; @@ -384,7 +385,7 @@ pub fn write(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply return switch (file) { .name => writeName(p, req, id, pane), .body => writeBody(p, req, id, pane), - .tag => writeTag(p, req, pane), + .tag => writeTag(req, pane), .ctl => ctl.writePane(p, req, pane), .addr, .dot, .limit => writeRange(req, pane, file), .data, .xdata => writeData(p, req, pane), @@ -417,15 +418,15 @@ fn writeBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { return .{ .tag = req.tag, .written = @intCast(take) }; } -fn writeTag(p: *Pardes, req: Req, pane: *Pane) Reply { +fn writeTag(req: Req, pane: *Pane) Reply { if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; - p.seedTail(pane); - const room = pane.tag_tail.len - pane.tag_tail_len; + // The tag's own text grows by what is written, newlines and all: a tag + // is a text like any other (acme's tag file appends the same way). + const had = Pardes.curTail(pane).len; + const room = limits.max_tag_tail -| had; if (room == 0) return Reply.fail(req.tag, E.NOSPC); const take = wholeUtf8(req.data[0..@min(req.data.len, room)]); - @memcpy(pane.tag_tail[pane.tag_tail_len..][0..take], req.data[0..take]); - pane.tag_tail_len += take; - pane.tag_init = true; + pane.appendTag(req.data[0..take]) catch return Reply.fail(req.tag, E.NOMEM); return .{ .tag = req.tag, .written = @intCast(take) }; } @@ -553,8 +554,8 @@ pub fn nameBuffer(p: *Pardes, id: usize, full: []const u8, preserve_tag: bool) ! f.output = null; pane.clearCwd(); if (!preserve_tag) { - pane.tag_init = false; - pane.tag_tail_len = 0; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = null; } f.saved_revision = f.revision -% 1; f.watch_after_save = fs.localPath(full) != null; @@ -606,8 +607,13 @@ pub fn truncate(p: *Pardes, pane: *Pane, file: PaneFile) tree.Status { setDot(pane, .{}); }, .tag => { - pane.tag_tail_len = 0; - pane.tag_init = true; + const empty = p.gpa.alloc(u8, 0) catch return .err; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = empty; + pane.tag.cur_row = 0; + pane.tag.cur_col = 0; + pane.tag.vsel.active = false; + pane.tag.nsel = 0; }, .addr => pf.addr = .{}, .limit => pf.limit = null, @@ -740,12 +746,20 @@ test "tag reads the whole tag and writes append to the editable tail" { const before = rd(p, node, 0, 4096).bytes.len; const w = wr(p, node, " Mine"); try testing.expectEqual(@as(u32, 5), w.reply.written); - try testing.expect(std.mem.endsWith(u8, pane.tag_tail[0..pane.tag_tail_len], " Mine")); + try testing.expect(std.mem.endsWith(u8, Pardes.curTail(pane), " Mine")); const after = rd(p, node, 0, 4096); try testing.expectEqual(before + 5, after.bytes.len); try testing.expect(std.mem.endsWith(u8, after.bytes, " Mine")); - pane.tag_tail_len = pane.tag_tail.len; + // A tag is a text like the body: a newline written to it stays one, and + // the tag reads back taller by it. + try testing.expectEqual(@as(u32, 10), wr(p, node, "\nNext Line").reply.written); + try testing.expect(std.mem.endsWith(u8, Pardes.curTail(pane), " Mine\nNext Line")); + try testing.expect(std.mem.endsWith(u8, rd(p, node, 0, 4096).bytes, " Mine\nNext Line")); + + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = try p.gpa.alloc(u8, limits.max_tag_tail); + @memset(pane.tag.own.?, 'x'); try testing.expectEqual(E.NOSPC, wr(p, node, "x").errno()); } @@ -873,10 +887,10 @@ test "truncating the tag clears its editable tail" { const pane = p.panes[0].?; const tag = Node.of(pane.serial, .tag); _ = wr(p, tag, " Mine"); - try testing.expect(pane.tag_tail_len > 0); + try testing.expect(Pardes.curTail(pane).len > 0); const cleared = call(p, .{ .tag = 1, .op = .setattr, .node = tag, .truncate = true }); try testing.expectEqual(Status.ok, cleared.reply.status); - try testing.expectEqual(@as(usize, 0), pane.tag_tail_len); + try testing.expectEqualStrings("", pane.tag.own.?); try testing.expect(std.mem.indexOf(u8, rd(p, tag, 0, 4096).bytes, " Mine") == null); } diff --git a/src/normal.zig b/src/normal.zig index a77f27a7..e4fa075d 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -257,7 +257,7 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { if (p.multi_stop) { p.multi_stop = false; const pn = p.panes[id] orelse return; - if (pn.serial == serial) pn.body.nsel = 0; + if (pn.serial == serial) t.nsel = 0; return; } const text = edit.flatSurface(p, t) catch return; @@ -285,7 +285,7 @@ pub fn handleNormal(p: *Pardes, t: *Text, key: Key) void { fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void { const pane = t.pane(); - const raw_selection = pane.rawPointerText(pane.sel[sel_slot]) != null; + const raw_selection = t.what == .body and pane.rawPointerText(pane.sel[sel_slot]) != null; const before = .{ t.cur_row, t.cur_col, t.vsel, t.msel, t.select, t.nsel, t.mode }; defer if (raw_selection and !std.meta.eql(before, .{ t.cur_row, t.cur_col, t.vsel, t.msel, t.select, t.nsel, t.mode })) { pane.clearPointerSelection(sel_slot); @@ -334,7 +334,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void .view_center => return t.gotoWindow(text, range, .center, go.count), .view_bottom => return t.gotoWindow(text, range, .bottom, go.count), }, - .view => |view| switch (view) { + .view => |view| if (t.what == .body) switch (view) { .top => { pane.scrollBy(t.cur_row - pane.scroll()); pane.ensureCursorVisible(); @@ -545,10 +545,11 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void p.leader_on = true; p.leader_n = 0; }, - .command_line => { - p.enterTagEdit(pane, -1); - if (pane.tag_edit) t.mode = .normal; - }, + // `:` is the one key a tag and a body do not share: it moves the + // keyboard between them. + .command_line => if (t.what == .tag) { + pane.focus = .body; + } else p.enterTag(pane), .pipe_selection => |how| return p.startPrompt(pane, .{ .pipe = how }), .search => return p.startPrompt(pane, .{ .search = config.search_marker }), .search_step => |direction| return look.lookWalk( @@ -590,10 +591,7 @@ pub fn handlePdfNormal(p: *Pardes, pane: *Pane, key: Key) void { p.leader_on = true; p.leader_n = 0; }, - .command_line => { - p.enterTagEdit(pane, -1); - if (pane.tag_edit) pane.body.mode = .normal; - }, + .command_line => p.enterTag(pane), .search => p.startPrompt(pane, .{ .search = config.search_marker }), .search_forward => look.lookWalk(p, 1), .search_backward => look.lookWalk(p, -1), diff --git a/src/panes.zig b/src/panes.zig index c26065ca..720f655f 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -69,9 +69,14 @@ pub const Pane = struct { /// Del from the keyboard with open panes both above and below: which /// one takes the rows. Nothing is typed; one key answers. del_side, + /// A new name for the file, drafted in place of the path on the + /// tagline after a click there; Enter commits it, as a buffer name + /// and never a disk rename. + name, }; pub const Cwd = union(enum) { none, inherited: *Pane, owned: []u8 }; + pub const Focus = enum { body, tag }; terminal: ?*Terminal.State = null, gpa: std.mem.Allocator, serial: u32 = 0, @@ -97,8 +102,9 @@ pub const Pane = struct { pdf: PdfSlot = if (Pdf.enabled) null else {}, prompt: Prompt = .none, /// The answer to an open prompt: its marker and what is typed after it, - /// edited in insert mode and shown on the notice band. It is its own text - /// so a prompt never touches the tag. + /// edited in insert mode and shown on the notice band, or a name draft + /// shown on the tagline in place of the path. It is its own text so a + /// prompt never touches the tag. input: Text = .{ .what = .input }, search_pane: ?usize = null, search_row: ?usize = null, @@ -107,23 +113,12 @@ pub const Pane = struct { nsel_snap: u8 = 0, sel_snap_pri: u8 = 0, sel_snap_expl: bool = false, - /// the editable tag tail: a bounded one-line command buffer. Input that - /// does not fit is refused atomically. - tag_tail: [limits.max_tag_tail]u8 = undefined, - tag_tail_len: usize = 0, - tag_init: bool = false, - tag_edit: bool = false, - tag_sel: bool = false, - /// the body mode a tag edit hijacked (tags are always insert); terminals - /// restore it on exit so clicking the tag never changes the pane's mode - tag_mode: Text.Mode = .normal, - tag_col: u16 = 0, - tag_saved_col: ?u16 = null, - tag_anchor: u16 = 0, - /// Filename edits are staged separately from the live buffer identity. - /// Enter commits the name; leaving tag editing discards the draft. - tag_name: [limits.host_path_cap]u8 = undefined, - tag_name_len: ?u16 = null, + /// The tag: what the user keeps after the computed prefix (the path, the + /// dirty marker, a PDF's page), its cursor, selections and undo. The + /// prefix is never stored in it, so it never moves the tag's cursor. + tag: Text = .{ .what = .tag }, + /// Which of the pane's texts the keyboard types into. + focus: Focus = .body, /// Display columns hidden to reveal the tag caret; tag addresses stay whole. tag_scroll: u16 = 0, cwd: Cwd = .none, @@ -297,9 +292,15 @@ pub const Pane = struct { return null; } - pub fn tagSlice(p: *const Pane) []const u8 { - return p.tag_tail[0..p.tag_tail_len]; + /// Add `text` to the end of the tag's own text, which starts out as the + /// default a pane of its kind shows. + pub fn appendTag(pane: *Pane, text: []const u8) !void { + const had = pane.tag.own orelse pardes.Pardes.defaultTail(pane); + const grown = try std.mem.concat(pane.gpa, u8, &.{ had, text }); + if (pane.tag.own) |old| pane.gpa.free(old); + pane.tag.own = grown; } + /// Close an open prompt, answered or not. Its answer goes with it, and an /// s/S preview keeps whatever it last previewed. pub fn closePrompt(pane: *Pane) void { @@ -313,33 +314,12 @@ pub const Pane = struct { /// painter of the band reads. pub fn promptText(p: *const Pane) ?[]const u8 { return switch (p.prompt) { - .none => null, + .none, .name => null, .del_side => config.del_question, else => p.input.own orelse "", }; } - pub fn appendTag(p: *Pane, text: []const u8) bool { - if (text.len > p.tag_tail.len - p.tag_tail_len) return false; - @memcpy(p.tag_tail[p.tag_tail_len..][0..text.len], text); - p.tag_tail_len += text.len; - return true; - } - - pub fn insertTagByte(p: *Pane, at: usize, byte: u8) bool { - if (at > p.tag_tail_len or p.tag_tail_len == p.tag_tail.len) return false; - std.mem.copyBackwards(u8, p.tag_tail[at + 1 .. p.tag_tail_len + 1], p.tag_tail[at..p.tag_tail_len]); - p.tag_tail[at] = byte; - p.tag_tail_len += 1; - return true; - } - - pub fn removeTagByte(p: *Pane, at: usize) void { - if (at >= p.tag_tail_len) return; - std.mem.copyForwards(u8, p.tag_tail[at .. p.tag_tail_len - 1], p.tag_tail[at + 1 .. p.tag_tail_len]); - p.tag_tail_len -= 1; - } - pub fn cwdSlice(p: *const Pane) []const u8 { return switch (p.cwd) { .none => "", diff --git a/src/pardes.zig b/src/pardes.zig index a29973e7..ce7c7065 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -687,9 +687,8 @@ test "pane-tag Exec prefers Tty and argument builtins before shell fallback" { // Argument-taking builtins use the same gesture path: a tag sweep is the // complete command line, and Theme consumes its tail without a PTY write. - pane.tag_tail_len = 0; - try std.testing.expect(pane.appendTag(" Theme dark")); - pane.tag_init = true; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = try p.gpa.dupe(u8, " Theme dark"); p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = tag_x + 1, .row = tag_y } }); p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .drag, .col = tag_x + 10, .row = tag_y } }); p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = tag_x + 10, .row = tag_y } }); @@ -707,8 +706,8 @@ test "pane-tag Exec prefers Tty and argument builtins before shell fallback" { // A word absent from the builtin vocabulary takes the fallback, including // the terminating carriage return expected by the shell prompt. - pane.tag_tail_len = 0; - try std.testing.expect(pane.appendTag(" DefinitelyNotABuiltin")); + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = try p.gpa.dupe(u8, " DefinitelyNotABuiltin"); p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = tag_x + 1, .row = tag_y } }); p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = tag_x + 1, .row = tag_y } }); var sent: [256]u8 = undefined; @@ -743,20 +742,20 @@ test "Collapse builtin keeps content and restores the pane from its default tag" try std.testing.expectEqual(revision, pane.file.?.revision); try std.testing.expectEqualStrings("keep this text\n", pane.file.?.content); try std.testing.expect((try p.render(p.scratch.allocator())).cursor == null); - p.enterTagEdit(pane, -1); + p.enterTag(pane); const tag_cursor = (try p.render(p.scratch.allocator())).cursor orelse return error.MissingTagCursor; try std.testing.expectEqual(p.rects[0].y, tag_cursor.y); - Pardes.exitTagEdit(pane); + pane.focus = .body; try std.testing.expect(p.executeBuiltinLine(0, "Collapse")); p.sync(); try std.testing.expect(!pane.collapsed); try std.testing.expectEqual(height, p.rects[0].h); // Unedited defaults from the preceding version gain the new command. - pane.tag_init = false; - pane.tag_tail_len = 0; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = null; p.restoreTailAt(pane, pre_collapse_file_pane_tail, "", .file); - try std.testing.expect(!pane.tag_init); + try std.testing.expect(pane.tag.own == null); try std.testing.expectEqualStrings(file_pane_tail, Pardes.curTail(pane)); } @@ -859,8 +858,8 @@ test "TreeContext command and custom tag survive a workspace round trip" { try std.testing.expect(pane.file.?.tree_context); try std.testing.expect(p.executeBuiltinLine(0, "TreeContext invalid")); try std.testing.expect(pane.file.?.tree_context); - try std.testing.expect(pane.appendTag(" Save Keep Del")); - pane.tag_init = true; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = try p.gpa.dupe(u8, " Save Keep Del"); try dump.dumpState(p); const restored = try dump.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); defer restored.deinit(); @@ -874,22 +873,23 @@ test "Togglettymode builtin and keyboard chord share mode transitions including defer p.deinit(); const pane = p.panes[0].?; try std.testing.expect(std.mem.indexOf(u8, Pardes.curTail(pane), " Mode ") != null); - p.seedTail(pane); - try std.testing.expect(pane.appendTag(" Togglettymode")); + try pane.appendTag(" Togglettymode"); try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); try std.testing.expect(p.executeBuiltinLine(0, "Togglettymode")); try std.testing.expectEqual(Text.Mode.normal, pane.body.mode); p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); - p.enterTagEdit(pane, -1); - try std.testing.expectEqual(Text.Mode.insert, pane.body.mode); + // The tag has its own mode: the body keeps tty while the tag is typed into. + p.enterTag(pane); + try std.testing.expect(pane.focus == .tag); + try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); try std.testing.expect(p.executeBuiltinLine(0, "Togglettymode")); try std.testing.expectEqual(Text.Mode.normal, pane.body.mode); - try std.testing.expect(!pane.tag_edit); - p.enterTagEdit(pane, -1); + try std.testing.expect(pane.focus == .body); + p.enterTag(pane); p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.focus == .body); p.acknowledgePanelPresentation(&.{}); const tag = try p.tagText(p.scratch.allocator(), pane); @@ -974,10 +974,8 @@ test "compact tag commands stay beside their own prefix across layout changes" { try std.testing.expectEqualStrings(above_tag, try p.tagText(p.scratch.allocator(), above)); p.update(.{ .resize = .{ .cols = 100, .rows = 30 } }); while (p.nextEffect()) |_| {} - - p.seedTail(below); - try std.testing.expectEqualStrings(tail, below.tagSlice()); - try std.testing.expect(below.appendTag(" lots and lots of typing out here")); + try std.testing.expectEqualStrings(tail, Pardes.curTail(below)); + try below.appendTag(" lots and lots of typing out here"); try std.testing.expectEqual(above_tag.len, (try p.tagText(p.scratch.allocator(), above)).len); p.update(.{ .resize = .{ .cols = 100, .rows = 2 } }); @@ -997,14 +995,14 @@ test "legacy default tag tails upgrade while custom tails remain owned" { legacy_pane_tail, }); p.restoreTail(terminal, terminal_old); - try std.testing.expect(!terminal.tag_init); + try std.testing.expect(terminal.tag.own == null); try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); const terminal_previous = try std.fmt.allocPrint(p.scratch.allocator(), "{s} New Del", .{ try p.tagPrefix(terminal), }); p.restoreTail(terminal, terminal_previous); - try std.testing.expect(!terminal.tag_init); + try std.testing.expect(terminal.tag.own == null); try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); const terminal_prefilter = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{ @@ -1012,60 +1010,60 @@ test "legacy default tag tails upgrade while custom tails remain owned" { prev_terminal_pane_tail, }); p.restoreTail(terminal, terminal_prefilter); - try std.testing.expect(!terminal.tag_init); + try std.testing.expect(terminal.tag.own == null); try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); for ([_][]const u8{ pre_mode_terminal_pane_tail, pre_tty_first_terminal_pane_tail, pre_collapse_terminal_pane_tail }) |old_tail| { const old = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{ try p.tagPrefix(terminal), old_tail }); p.restoreTail(terminal, old); - try std.testing.expect(!terminal.tag_init); + try std.testing.expect(terminal.tag.own == null); try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); } const custom_mode = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s} Keep", .{ try p.tagPrefix(terminal), pre_mode_terminal_pane_tail }); p.restoreTail(terminal, custom_mode); - try std.testing.expect(terminal.tag_init); + try std.testing.expect(terminal.tag.own != null); try std.testing.expectEqualStrings(pre_mode_terminal_pane_tail ++ " Keep", Pardes.curTail(terminal)); - terminal.tag_tail_len = 0; - terminal.tag_init = false; + if (terminal.tag.own) |own| p.gpa.free(own); + terminal.tag.own = null; const terminal_custom = try std.fmt.allocPrint(p.scratch.allocator(), "{s} Keep Del", .{ try p.tagPrefix(terminal), }); p.restoreTail(terminal, terminal_custom); - try std.testing.expect(terminal.tag_init); + try std.testing.expect(terminal.tag.own != null); try std.testing.expectEqualStrings(" Keep Del", Pardes.curTail(terminal)); - terminal.tag_tail_len = 0; - terminal.tag_init = false; + if (terminal.tag.own) |own| p.gpa.free(own); + terminal.tag.own = null; p.restoreDumpTail(terminal, .{ .kind = .terminal, .tag = "TTY /historical/cwd Keep Del", .body = "", .terminal = .{ .cwd = "/historical/cwd" }, }); - try std.testing.expect(terminal.tag_init); + try std.testing.expect(terminal.tag.own != null); try std.testing.expectEqualStrings(" Keep Del", Pardes.curTail(terminal)); - terminal.tag_tail_len = 0; - terminal.tag_init = false; + if (terminal.tag.own) |own| p.gpa.free(own); + terminal.tag.own = null; p.restoreDumpTail(terminal, .{ .kind = .terminal, .tag = "TTY /historical/cwd New Del", .body = "", .terminal = .{ .cwd = "/historical/cwd" }, }); - try std.testing.expect(!terminal.tag_init); + try std.testing.expect(terminal.tag.own == null); try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); // This happens to be the historical FILE default, but on a terminal it is // user-owned text and must not be swallowed by migration. - terminal.tag_tail_len = 0; - terminal.tag_init = false; + if (terminal.tag.own) |own| p.gpa.free(own); + terminal.tag.own = null; const terminal_fileish = try std.fmt.allocPrint(p.scratch.allocator(), "{s} Save Del", .{ try p.tagPrefix(terminal), }); p.restoreTail(terminal, terminal_fileish); - try std.testing.expect(terminal.tag_init); + try std.testing.expect(terminal.tag.own != null); try std.testing.expectEqualStrings(" Save Del", Pardes.curTail(terminal)); // A savable file has a distinct old default. Save remains first after the @@ -1076,25 +1074,25 @@ test "legacy default tag tails upgrade while custom tails remain owned" { legacy_file_pane_tail, }); p.restoreTail(file, file_old); - try std.testing.expect(!file.tag_init); + try std.testing.expect(file.tag.own == null); try std.testing.expectEqualStrings(" Save Tty Collapse Del", Pardes.curTail(file)); const file_custom = try std.fmt.allocPrint(p.scratch.allocator(), "{s} Save Mine Del", .{ try p.tagPrefix(file), }); p.restoreTail(file, file_custom); - try std.testing.expect(file.tag_init); + try std.testing.expect(file.tag.own != null); try std.testing.expectEqualStrings(" Save Mine Del", Pardes.curTail(file)); // Conversely the generic pane's current default is a custom edit on a // savable file. Legacy recognition is scoped to the source pane class. - file.tag_tail_len = 0; - file.tag_init = false; + if (file.tag.own) |own| p.gpa.free(own); + file.tag.own = null; const file_generic = try std.fmt.allocPrint(p.scratch.allocator(), "{s} New Del", .{ try p.tagPrefix(file), }); p.restoreTail(file, file_generic); - try std.testing.expect(file.tag_init); + try std.testing.expect(file.tag.own != null); try std.testing.expectEqualStrings(" New Del", Pardes.curTail(file)); const image_doc = try panes.Image.create(p, 1, "/tmp/legacy image.ppm", &.{}); @@ -1105,8 +1103,8 @@ test "legacy default tag tails upgrade while custom tails remain owned" { .body = "", .image = .{ .path = "/tmp/legacy image.ppm" }, }); - try std.testing.expect(image_doc.tag_init); - try std.testing.expectEqualStrings(" Keep Del", image_doc.tagSlice()); + try std.testing.expect(image_doc.tag.own != null); + try std.testing.expectEqualStrings(" Keep Del", Pardes.curTail(image_doc)); } test "Joincol folds the active column into its right neighbor, keeping its panes" { @@ -1247,11 +1245,11 @@ test "pane defaults keep creation of scratch panes in column tags" { try std.testing.expectEqualStrings("New Tty Find Grep Joincol Delcol", p.columnTag(0)); const terminal = p.panes[0].?; p.restoreTailAt(terminal, pre_column_terminal_pane_tail, "", .terminal); - try std.testing.expect(!terminal.tag_init); + try std.testing.expect(terminal.tag.own == null); try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); const file = try p.setTestFile("unchanged\n"); p.restoreTailAt(file, pre_column_file_pane_tail, "", .file); - try std.testing.expect(!file.tag_init); + try std.testing.expect(file.tag.own == null); try std.testing.expectEqualStrings(file_pane_tail, Pardes.curTail(file)); } @@ -1398,8 +1396,8 @@ test "image dump restores source bytes renderer choices and exact custom tail" { pane.image.?.glyph_art = true; pane.image.?.pmode = .terminal; pane.image.?.ascii = false; - try std.testing.expect(pane.appendTag(" Keep Del")); - pane.tag_init = true; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = try p.gpa.dupe(u8, " Keep Del"); try dump.dumpState(p); var first_dump = try dump.readZon(gpa, p.dump_out.?, "image-first-dump"); @@ -1416,8 +1414,8 @@ test "image dump restores source bytes renderer choices and exact custom tail" { try std.testing.expect(restored_pane.image.?.glyph_art); try std.testing.expectEqual(image.PaletteMode.terminal, restored_pane.image.?.pmode); try std.testing.expect(!restored_pane.image.?.ascii); - try std.testing.expect(restored_pane.tag_init); - try std.testing.expectEqualStrings(" Keep Del", restored_pane.tagSlice()); + try std.testing.expect(restored_pane.tag.own != null); + try std.testing.expectEqualStrings(" Keep Del", Pardes.curTail(restored_pane)); try std.testing.expectEqualSlices(u8, source, restored_pane.image.?.raw); try dump.dumpState(restored); @@ -2095,20 +2093,20 @@ test "Save reaches every tagline with text behind it and no other" { pane_tail, }); p.restoreTail(out, dumped); - try std.testing.expect(!out.tag_init); + try std.testing.expect(out.tag.own == null); try std.testing.expectEqualStrings(locations_pane_tail, Pardes.curTail(out)); // A scratch is an output buffer that has worn the FILE tails all along, // so its own older default upgrades from that family too. out.file.?.output = .{ .from = .{ .cmd = std.meta.stringToEnum(Builtin, "New").? } }; - out.tag_tail_len = 0; - out.tag_init = false; + if (out.tag.own) |own| p.gpa.free(own); + out.tag.own = null; const scratch_dumped = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{ try p.tagPrefix(out), prev_file_pane_tail, }); p.restoreTail(out, scratch_dumped); - try std.testing.expect(!out.tag_init); + try std.testing.expect(out.tag.own == null); try std.testing.expectEqualStrings(" Save Tty Collapse Del", Pardes.curTail(out)); // An image's bytes on disk already are what they are: nothing of the @@ -2629,24 +2627,25 @@ test "Unicode display cells map back to body and tag byte cursors" { p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = text_x + 2, .row = body_y } }); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); - // A click in the wide path glyph likewise becomes a byte cursor at the + // A click in the wide path glyph drafts a name with its caret at the // grapheme start; arrow motion then advances by the full UTF-8 cluster. - p.enterTagEdit(pane, 1); - try std.testing.expectEqual(@as(u16, 0), pane.tag_col); - p.tagInsertKey(pane, .{ .cp = Key.right }); - try std.testing.expectEqual(@as(u16, 3), pane.tag_col); - p.tagInsertKey(pane, .{ .cp = Key.right }); - try std.testing.expectEqual(@as(u16, 6), pane.tag_col); - - const before = try gpa.dupe(u8, pane.tagSlice()); + p.draftName(pane, 1); + try std.testing.expectEqual(@as(i32, 0), pane.input.cur_col); + edit.insertKey(p, &pane.input, .{ .cp = Key.right }); + try std.testing.expectEqual(@as(i32, 3), pane.input.cur_col); + edit.insertKey(p, &pane.input, .{ .cp = Key.right }); + try std.testing.expectEqual(@as(i32, 6), pane.input.cur_col); + pane.closePrompt(); + + const before = try gpa.dupe(u8, Pardes.curTail(pane)); defer gpa.free(before); - p.enterTagEdit(pane, -1); - const insertion = pane.tag_col; - p.tagInsertKey(pane, .{ .cp = 'λ', .text = "λ" }); - try std.testing.expectEqual(insertion + 2, pane.tag_col); - p.tagInsertKey(pane, .{ .cp = Key.backspace }); - try std.testing.expectEqual(insertion, pane.tag_col); - try std.testing.expectEqualStrings(before, pane.tagSlice()); + p.enterTag(pane); + const insertion = pane.tag.cur_col; + edit.insertKey(p, &pane.tag, .{ .cp = 'λ', .text = "λ" }); + try std.testing.expectEqual(insertion + 2, pane.tag.cur_col); + edit.insertKey(p, &pane.tag, .{ .cp = Key.backspace }); + try std.testing.expectEqual(insertion, pane.tag.cur_col); + try std.testing.expectEqualStrings(before, Pardes.curTail(pane)); } test "tabbed file aligns syntax cursor and mouse at the nearest insertion gap" { @@ -4110,6 +4109,9 @@ pub const Pardes = struct { if (pane.file) |*file| panes.File.deinit(p, pane, file); if (pane.ovl) |o| p.gpa.free(o.text); if (pane.input.own) |text| p.gpa.free(text); + if (pane.tag.own) |text| p.gpa.free(text); + for (pane.tag.ed_undo[0..pane.tag.ed_undo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); + for (pane.tag.ed_redo[0..pane.tag.ed_redo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); for (pane.body.ed_undo[0..pane.body.ed_undo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); for (pane.body.ed_redo[0..pane.body.ed_redo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); panes.Terminal.deinitEmulator(pane, p.gpa); @@ -4762,7 +4764,7 @@ pub const Pardes = struct { ); if (pane.image) |*state| return panes.Image.tagPrefix(arena, state); if (pane.file) |f| { - const name = if (pane.tag_name_len) |len| pane.tag_name[0..len] else f.path; + const name = if (pane.prompt == .name) pane.input.own orelse f.path else f.path; if (panes.Output.fileTraits(f.output).saves and f.revision != f.saved_revision) return std.fmt.allocPrint(arena, "{s}{s}", .{ name, dirty_marker }); return arena.dupe(u8, name); @@ -4770,10 +4772,10 @@ pub const Pardes = struct { return arena.dupe(u8, pane.cwdSlice()); } - /// the editable tail: the user's edited buffer once touched, else defaults - fn curTail(pane: *Pane) []const u8 { - if (pane.tag_init) return pane.tagSlice(); - return defaultTail(pane); + /// The tag's own text: what the user made of it, or until then the + /// default a pane of its kind starts with. + pub fn curTail(pane: *Pane) []const u8 { + return pane.tag.own orelse defaultTail(pane); } pub fn defaultTail(pane: *const Pane) []const u8 { @@ -4793,6 +4795,8 @@ pub const Pardes = struct { return null; } + /// The tag as it is shown, read and pointed at: its computed prefix and + /// its own text after it. pub fn tagText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]u8 { const prefix = try p.tagPrefix(pane); const tail = curTail(pane); @@ -4814,7 +4818,7 @@ pub const Pardes = struct { } var start: usize = 0; const name = if (pane.file) |file| - if (pane.tag_name_len) |len| pane.tag_name[0..len] else file.path + if (pane.prompt == .name) pane.input.own orelse file.path else file.path else if (pane.image) |state| blk: { // Image tags put renderer controls before the path. start = prefix_len -| state.path.len; @@ -4827,88 +4831,76 @@ pub const Pardes = struct { return .{ .lo = start + basename, .hi = start + name.len }; } - pub fn seedTail(_: *Pardes, pane: *Pane) void { - if (pane.tag_init) return; + /// Give the keyboard to the tag in normal mode (`:`), its cursor where + /// the tag last had it. The first time there is nothing to remember, and + /// it starts on Save, so that `:` and the execute key write the file. + pub fn enterTag(p: *Pardes, pane: *Pane) void { + const t = &pane.tag; const tail = curTail(pane); - if (tail.len > pane.tag_tail.len) return; - @memcpy(pane.tag_tail[0..tail.len], tail); - pane.tag_tail_len = tail.len; - pane.tag_init = true; - } - - pub fn enterTagEdit(p: *Pardes, pane: *Pane, col: i32) void { - if (pane.tag_edit) pane.tag_saved_col = pane.tag_col; - const edit0: i32 = @intCast((p.tagPrefix(pane) catch return).len); - p.seedTail(pane); - if (!pane.tag_init) return; - if (!pane.tag_edit) pane.tag_mode = pane.body.mode; - pane.tag_edit = true; - pane.tag_sel = false; - // a one-line tag has no use for normal mode: always insert - pane.body.mode = .insert; - pane.body.normal.clear(); - const end = edit0 + @as(i32, @intCast(pane.tag_tail_len)); - const tail = pane.tagSlice(); - const lead: i32 = @intCast(tail.len - std.mem.trimStart(u8, tail, " ").len); - if (col < 0) { - const text = p.tagText(p.scratch.allocator(), pane) catch return; - if (pane.tag_saved_col) |saved| { - pane.tag_col = @intCast(modal.graphemeStart(text, @min(saved, text.len))); - } else { - pane.tag_col = @intCast(@min(edit0 + lead, end)); - } - if (pane.tag_saved_col == null) if (p.paneIdOf(pane)) |id| { + if (!t.cur_pinned) { + var words = std.mem.tokenizeAny(u8, tail, " \t\n"); + const at = while (words.next()) |word| { + if (std.mem.eql(u8, word, "Save")) break @intFromPtr(word.ptr) - @intFromPtr(tail.ptr); + } else tail.len - std.mem.trimStart(u8, tail, " ").len; + const cursor = modal.positionAt(tail, @min(at, tail.len)); + t.cur_row = @intCast(cursor.row); + t.cur_col = @intCast(cursor.col); + t.cur_pinned = true; + // Reveal the suffix together with its commands, not merely the + // first command letter at the viewport's far right edge. + if (p.paneIdOf(pane)) |id| { + const tag = p.tagText(p.scratch.allocator(), pane) catch return; + const line = tag[0 .. std.mem.indexOfScalar(u8, tag, '\n') orelse tag.len]; const width = p.tagCapacity(p.rects[id].w -| TAG_TEXT_INSET); - // Reveal the suffix together with its commands, not merely the - // first command letter at the viewport's far right edge. - pane.tag_scroll = @intCast(panes.File.displayWidth(text) + 1 -| width); - }; - } else { - const text = p.tagText(p.scratch.allocator(), pane) catch return; - pane.tag_col = @intCast(@min(text.len, panes.File.rawAtDisplay(text, @as(usize, @intCast(col)) + pane.tag_scroll))); - } - } - - pub fn exitTagEdit(pane: *Pane) void { - if (pane.tag_edit) pane.tag_saved_col = pane.tag_col; - if (pane.isTerminal()) { - if (pane.tag_edit) pane.body.mode = pane.tag_mode; - } else pane.body.mode = .normal; - pane.tag_edit = false; - pane.tag_sel = false; - pane.tag_name_len = null; - pane.tag_scroll = 0; - } - - pub fn tagSelBounds(pane: *Pane) struct { lo: usize, hi: usize } { - const a: usize = pane.tag_anchor; - const c: usize = pane.tag_col; - return .{ .lo = @min(a, c), .hi = @max(a, c) }; - } - - fn tagChordText(p: *Pardes, pane: *Pane) ?[]const u8 { - const text = p.tagText(p.scratch.allocator(), pane) catch return null; - if (pane.tag_sel) { - const b = tagSelBounds(pane); - const hi = modal.nextGrapheme(text, b.hi); - return if (hi > b.lo) text[b.lo..hi] else null; + pane.tag_scroll = @intCast(panes.File.displayWidth(line) + 1 -| width); + } } - const b = config.wordBounds(text, @min(@as(usize, pane.tag_col), text.len)); - return if (b.hi > b.lo) text[b.lo..b.hi] else null; + // The text may have changed since (a 9P write, a rename), so the + // remembered cursor is pulled back inside it. It is the cursor that + // is remembered, not a selection. + const rows = modal.cursorLineCount(tail); + t.cur_row = @intCast(@min(@as(usize, @intCast(@max(0, t.cur_row))), rows - 1)); + const line = modal.lineSlice(tail, @intCast(t.cur_row)); + t.cur_col = @intCast(modal.graphemeStart(line, @min(line.len, @as(usize, @intCast(@max(0, t.cur_col)))))); + t.vsel.active = false; + t.msel.active = false; + t.nsel = 0; + t.select = false; + t.append_at = null; + t.sticky_col = -1; + t.mode = .normal; + t.normal.clear(); + pane.focus = .tag; + } + + /// Where display column `col` of the tagline (tag scroll included) lands + /// in the tag's own text, or null when it is on the prefix. + pub fn tagOffsetAt(p: *Pardes, pane: *Pane, col: usize) ?usize { + const prefix = p.tagPrefix(pane) catch return null; + const width = panes.File.displayWidth(prefix); + if (col < width) return null; + const tail = curTail(pane); + const line = tail[0 .. std.mem.indexOfScalar(u8, tail, '\n') orelse tail.len]; + return modal.graphemeStart(line, panes.File.rawAtDisplay(line, col - width)); } - fn tagNameEnd(pane: *const Pane) ?usize { - const f = pane.file orelse return null; - if (!panes.Output.fileTraits(f.output).saves or f.path.len > pane.tag_name.len) return null; - return if (pane.tag_name_len) |len| len else f.path.len; + /// Start a name draft for a file that can take one, its caret at display + /// column `col` of the path. Nothing changes until it is typed into. + pub fn draftName(p: *Pardes, pane: *Pane, col: usize) void { + const f = pane.file orelse return; + if (!panes.Output.fileTraits(f.output).saves) return; + const name = p.gpa.dupe(u8, f.path) catch return; + pane.closePrompt(); + pane.prompt = .name; + pane.input = .{ .what = .input, .own = name, .mode = .insert, .cur_pinned = true, .cur_col = @intCast(@min(name.len, panes.File.rawAtDisplay(name, col))) }; } - /// Commit a staged buffer name, never a disk rename or write. Keep the + /// Commit a drafted buffer name, never a disk rename or write. Keep the /// draft visible on failure so the user can correct it or cancel with Esc. pub fn commitTagName(p: *Pardes, pane: *Pane) bool { - const len = pane.tag_name_len orelse return true; + if (pane.prompt != .name) return true; const id = p.paneIdOf(pane) orelse return false; - const name = pane.tag_name[0..len]; + const name = pane.input.own orelse ""; if (name.len == 0 or name[name.len - 1] == '/' or !std.unicode.utf8ValidateSlice(name)) { p.reportError(id, "name", error.InvalidName); return false; @@ -4917,8 +4909,6 @@ pub const Pardes = struct { p.reportError(id, "name", error.InvalidName); return false; }; - const old_prefix = (p.tagPrefix(pane) catch return false).len; - const tail_col = @as(usize, pane.tag_col) -| old_prefix; const full = std.fs.path.resolvePosix(p.scratch.allocator(), &.{ paneDir(pane), name }) catch |err| { p.reportError(id, "name", err); return false; @@ -4927,181 +4917,10 @@ pub const Pardes = struct { p.reportError(id, "name", err); return false; }; - pane.tag_name_len = null; - const prefix = (p.tagPrefix(pane) catch return false).len; - pane.tag_col = @intCast(prefix + @min(tail_col, pane.tag_tail_len)); - pane.tag_sel = false; - return true; - } - - /// Replace one range in the rendered tag. The file name and command tail - /// retain separate identities even when a selection crosses their boundary. - pub fn replaceTagText(p: *Pardes, pane: *Pane, start: usize, finish: usize, input: []const u8) bool { - const prefix_len = (p.tagPrefix(pane) catch return false).len; - const end = prefix_len + pane.tag_tail_len; - const lo = @min(start, end); - const hi = @max(lo, @min(finish, end)); - const name_end = tagNameEnd(pane); - const editing_name = if (name_end) |n| lo <= n else false; - if (!editing_name and lo < prefix_len) return false; - var bytes: [limits.max_tag_tail]u8 = undefined; - var count: usize = 0; - for (input) |byte| { - if (byte == '\n' or byte == '\r') continue; - if (count == bytes.len) return false; - bytes[count] = byte; - count += 1; - } - const tail_lo = lo -| prefix_len; - const tail_hi = hi -| prefix_len; - const tail_insert = if (editing_name) 0 else count; - const tail_len = pane.tag_tail_len - (tail_hi - tail_lo) + tail_insert; - if (tail_len > pane.tag_tail.len) return false; - if (editing_name) { - const n = name_end.?; - const name_hi = @min(hi, n); - const name_len = n - (name_hi - lo) + count; - if (name_len > pane.tag_name.len) return false; - if (pane.tag_name_len == null) @memcpy(pane.tag_name[0..n], pane.file.?.path); - if (count > name_hi - lo) - std.mem.copyBackwards(u8, pane.tag_name[lo + count .. name_len], pane.tag_name[name_hi..n]) - else - std.mem.copyForwards(u8, pane.tag_name[lo + count .. name_len], pane.tag_name[name_hi..n]); - @memcpy(pane.tag_name[lo..][0..count], bytes[0..count]); - pane.tag_name_len = @intCast(name_len); - } - if (tail_insert > tail_hi - tail_lo) - std.mem.copyBackwards(u8, pane.tag_tail[tail_lo + tail_insert .. tail_len], pane.tag_tail[tail_hi..pane.tag_tail_len]) - else - std.mem.copyForwards(u8, pane.tag_tail[tail_lo + tail_insert .. tail_len], pane.tag_tail[tail_hi..pane.tag_tail_len]); - if (!editing_name) @memcpy(pane.tag_tail[tail_lo..][0..count], bytes[0..count]); - pane.tag_tail_len = tail_len; - pane.tag_col = @intCast(lo + count); - pane.tag_sel = false; + pane.closePrompt(); return true; } - fn tagInsertKey(p: *Pardes, pane: *Pane, key: Key) void { - if (hit(key, config.escape)) { - exitTagEdit(pane); // the tag is ALWAYS insert; Esc leaves it - return; - } - // the acme chords on the selection or the word at the cursor - if (hit(key, config.look_key) or hit(key, config.exec_key)) { - if (pane.tag_name_len != null) { - const in_name = pane.tag_col < (p.tagPrefix(pane) catch return).len; - if (!p.commitTagName(pane)) return; - if (hit(key, config.look_key) or in_name) { - exitTagEdit(pane); - return; - } - } - if (p.tagChordText(pane)) |txt| { - pane.tag_sel = false; - exec.runBuiltin(p, if (hit(key, config.look_key)) config.look_cmd else config.exec_cmd, p.active, "", txt); - } - return; - } - const text = p.tagText(p.scratch.allocator(), pane) catch return; - const end = text.len; - if (key.text.len > 0) { - const range: @TypeOf(tagSelBounds(pane)) = if (pane.tag_sel) tagSelBounds(pane) else .{ .lo = pane.tag_col, .hi = pane.tag_col }; - const hi = if (pane.tag_sel) modal.nextGrapheme(text, range.hi) else range.hi; - _ = p.replaceTagText(pane, range.lo, hi, key.text); - return; - } - switch (key.cp) { - Key.backspace, Key.delete => { - if (pane.tag_sel) { - const range = tagSelBounds(pane); - _ = p.replaceTagText(pane, range.lo, modal.nextGrapheme(text, range.hi), ""); - } else if (key.cp == Key.backspace and pane.tag_col > 0) { - _ = p.replaceTagText(pane, modal.prevGrapheme(text, pane.tag_col), pane.tag_col, ""); - } else if (key.cp == Key.delete and pane.tag_col < end) { - _ = p.replaceTagText(pane, pane.tag_col, modal.nextGrapheme(text, pane.tag_col), ""); - } - }, - Key.left => if (pane.tag_col > 0) { - pane.tag_col = @intCast(modal.prevGrapheme(text, pane.tag_col)); - }, - Key.right => if (pane.tag_col < end) { - pane.tag_col = @intCast(modal.nextGrapheme(text, pane.tag_col)); - }, - Key.home => pane.tag_col = 0, - Key.end => pane.tag_col = @intCast(end), - else => {}, - } - } - - /// write a helix range back onto the tag cursor + selection: the rendered - /// tag's one-line mirror of setPaneRange. - fn setTagRange(pane: *Pane, text: []const u8, r: modal.Selection) void { - const lo = @min(r.anchor, r.head); - const hi = @max(r.anchor, r.head); - pane.tag_col = @intCast(modal.selectionCursor(text, r)); - pane.tag_sel = modal.nextGrapheme(text, lo) < hi; // one grapheme IS the block cursor - if (pane.tag_sel) pane.tag_anchor = @intCast(if (r.head > r.anchor) lo else modal.prevGrapheme(text, hi)); - } - - fn tagNormalKey(p: *Pardes, pane: *Pane, key: Key) void { - const text = p.tagText(p.scratch.allocator(), pane) catch return; - const cur: usize = @min(@as(usize, pane.tag_col), text.len); - // Esc abandons the command line: back to the body, tail kept as text - if (hit(key, config.escape) or hit(key, &.{.{ .cp = 'j' }})) return exitTagEdit(pane); - if (hit(key, config.look_key) or hit(key, config.exec_key)) { - const cmd = if (hit(key, config.look_key)) config.look_cmd else config.exec_cmd; - const txt = p.tagChordText(pane) orelse return; - const id = p.active; - const body_mode = pane.tag_mode; - exitTagEdit(pane); // leave the tag FIRST: Del frees the pane - pane.body.mode = body_mode; - exec.runBuiltin(p, cmd, id, "", txt); - return; - } - if (hit(key, config.tag_yank)) { - if (p.tagChordText(pane)) |txt| edit.setClipboard(p, txt); - return; - } - if (hit(key, config.insert) or hit(key, config.append) or - hit(key, config.insert_line_start) or hit(key, config.insert_line_end)) - { - const edit0: usize = if (tagNameEnd(pane) != null) 0 else (p.tagPrefix(pane) catch return).len; - pane.tag_col = @intCast(@max(edit0, if (hit(key, config.append)) - modal.nextGrapheme(text, cur) - else if (hit(key, config.insert_line_start)) - 0 - else if (hit(key, config.insert_line_end)) - text.len - else - cur)); - pane.tag_sel = false; - pane.body.mode = .insert; - return; - } - const dir: ?Builtin = for (config.window_keys) |wk| { - var letter = wk.letter; - letter.cp = std.ascii.toUpper(@intCast(letter.cp)); - if (hit(key, &.{letter})) break wk.cmd; - } else null; - if (dir) |d| { - const from = p.active; - exec.runBuiltin(p, d, from, "", null); - if (p.active == from) { - if (d == .Up) { - exitTagEdit(pane); - p.enterHeader(if (p.columnBarHeight() > 0) (layout.findPane(p, from) orelse return).col else null); - } - return; - } - const dest = p.panes[p.active] orelse return; - exitTagEdit(pane); // the pane we left is fully out of its tag... - p.enterTagEdit(dest, -1); - if (dest.tag_edit) dest.body.mode = .normal; - return; - } - if (lineMotion(text, cur, key)) |r| setTagRange(pane, text, r); - } - fn lineMotion(text: []const u8, cur: usize, key: Key) ?modal.Selection { const target: ?usize = if (hit(key, config.line_move_left)) modal.prevGrapheme(text, cur) @@ -5243,8 +5062,7 @@ pub const Pardes = struct { const pane = p.panes[d].?; p.exitHeader(); p.active = d; - p.enterTagEdit(pane, -1); - if (pane.tag_edit) pane.body.mode = .normal; + p.enterTag(pane); return; } if (hit(key, config.topbar_up)) { @@ -5268,12 +5086,11 @@ pub const Pardes = struct { pub fn cycleMode(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; if (pane.file == null and !pane.isTerminal()) return; - const previous = if (pane.tag_edit) pane.tag_mode else pane.body.mode; + const previous = pane.body.mode; p.active = id; p.exitHeader(); - if (pane.tag_edit) exitTagEdit(pane); + pane.focus = .body; pane.closePrompt(); - pane.body.mode = previous; switch (previous) { .tty => { pane.body.mode = .normal; @@ -5293,7 +5110,7 @@ pub const Pardes = struct { if (!pane.isTerminal()) return; p.active = id; p.exitHeader(); - if (pane.tag_edit) exitTagEdit(pane); + pane.focus = .body; pane.closePrompt(); if (pane.body.mode == .tty) { pane.body.mode = .normal; @@ -5314,7 +5131,7 @@ pub const Pardes = struct { } if (p.topbar_col != null) return p.topbarKey(key); const pane = p.panes[p.active] orelse return; - if (pane.isTerminal() and pane.body.mode == .tty and !pane.tag_edit) { + if (pane.isTerminal() and pane.body.mode == .tty and pane.focus == .body and pane.prompt == .none) { p.leader_on = false; p.ctrl_w_pending = false; if (key.ctrl and !key.alt and key.cp == p.opts.tty_toggle) @@ -5352,7 +5169,8 @@ pub const Pardes = struct { } // insert mode owns Ctrl-w (delete word backward, helix); the focus // prefix applies outside raw tty mode - if (hit(key, config.window_prefix) and pane.body.mode != .insert and pane.prompt == .none) { + const t = if (pane.focus == .tag) &pane.tag else &pane.body; + if (hit(key, config.window_prefix) and t.mode != .insert and pane.prompt == .none) { p.ctrl_w_pending = true; return; } @@ -5385,6 +5203,21 @@ pub const Pardes = struct { if (pane.isTerminal() and tty_toggle) { return p.toggleTty(p.active); } + if (pane.prompt == .name) { + // Enter or the execute key commits the draft and the keyboard + // goes back to the body; Esc drops it. + if (hit(key, config.look_key) or hit(key, config.exec_key)) { + if (p.commitTagName(pane)) pane.focus = .body; + return; + } + if (hit(key, config.escape)) { + pane.closePrompt(); + pane.focus = .body; + return; + } + edit.handleInsert(p, &pane.input, key); + return; + } if (pane.prompt != .none) { if (hit(key, config.search_submit) or hit(key, config.escape)) { const submit = hit(key, config.search_submit); @@ -5395,7 +5228,7 @@ pub const Pardes = struct { look.submitSearch(p, p.active) else if (normal.selRegexArmed(pane)) |_| normal.applySelRegex(p, pane, "", false), - .none, .del_side => unreachable, + .none, .del_side, .name => unreachable, } pane.closePrompt(); pane.body.mode = .normal; @@ -5406,12 +5239,27 @@ pub const Pardes = struct { if (normal.selRegexArmed(pane)) |a| normal.applySelRegex(p, pane, a.pat, a.split); return; } - if (pane.tag_edit) { - if (pane.body.mode == .normal) p.tagNormalKey(pane, key) else p.tagInsertKey(pane, key); - return; - } - if (pane.body.mode == .normal and (hit(key, config.look_key) or hit(key, config.exec_key))) { + if (t.mode == .normal and (hit(key, config.look_key) or hit(key, config.exec_key))) { const cmd = if (hit(key, config.look_key)) config.look_cmd else config.exec_cmd; + if (pane.focus == .tag) { + // An explicit selection, else the word under the cursor in the + // tag as it is shown: the prefix is part of what a word is. + const tag = p.tagText(p.scratch.allocator(), pane) catch return; + const tail = curTail(pane); + const range = t.primaryRange(tail, 0); + const lo = @min(range.anchor, range.head); + const hi = @max(range.anchor, range.head); + const txt = if ((t.vsel.active and t.vsel.explicit) or t.msel.active) + tail[lo..hi] + else word: { + const b = config.wordBounds(tag, tag.len - tail.len + modal.selectionCursor(tail, range)); + break :word tag[b.lo..b.hi]; + }; + // Out of the tag FIRST: Del frees the pane. + pane.focus = .body; + if (txt.len > 0) exec.runBuiltin(p, cmd, p.active, "", txt); + return; + } edit.pinPaneCursor(p, &pane.body); const explicit = (p.native_images and pane.hasPdfSelection()) or (pane.body.vsel.active and pane.body.vsel.explicit) or pane.body.msel.active; @@ -5430,14 +5278,12 @@ pub const Pardes = struct { exec.runBuiltin(p, cmd, p.active, "", word); return; } - if (pane.body.mode == .normal and pane.hasPdf()) return normal.handlePdfNormal(p, pane, key); - switch (pane.body.mode) { - .normal => { - normal.handleNormal(p, &pane.body, key); - }, + if (t.mode == .normal and t.what == .body and pane.hasPdf()) return normal.handlePdfNormal(p, pane, key); + switch (t.mode) { + .normal => normal.handleNormal(p, t, key), .insert => { - if (hit(key, config.escape)) return edit.exitInsert(p, &pane.body); - edit.handleInsert(p, &pane.body, key); + if (hit(key, config.escape)) return edit.exitInsert(p, t); + edit.handleInsert(p, t, key); }, .tty => panes.Terminal.forwardKey(p, p.active, key), } @@ -5507,7 +5353,7 @@ pub const Pardes = struct { const dir = if (request == .save) paneDir(pane) else ""; const slash: []const u8 = if (request == .save and (dir.len == 0 or dir[dir.len - 1] != '/')) "/" else ""; const answer = std.mem.concat(p.gpa, u8, &.{ marker, dir, slash }) catch return; - if (pane.tag_edit) exitTagEdit(pane); + pane.focus = .body; // Not closePrompt: an s/S snapshot was taken for this very prompt. if (pane.input.own) |old| p.gpa.free(old); pane.prompt = switch (request) { @@ -5806,8 +5652,7 @@ pub const Pardes = struct { pub fn restoreDumpTail(p: *Pardes, pane: *Pane, src: dump.Pane) void { if (src.tag_tail) |tail| { - if (!pane.appendTag(tail)) return; - pane.tag_init = true; + pane.tag.own = p.gpa.dupe(u8, tail) catch return; return; } const tail_class = tailClass(pane); @@ -5855,7 +5700,7 @@ pub const Pardes = struct { } fn restoreTailAt( - _: *Pardes, + p: *Pardes, pane: *Pane, saved_tag: []const u8, pfx: []const u8, @@ -5886,8 +5731,7 @@ pub const Pardes = struct { }; for (defaults) |default| if (std.mem.eql(u8, said, std.mem.trimStart(u8, default, " "))) return; - if (!pane.appendTag(rest)) return; - pane.tag_init = true; + pane.tag.own = p.gpa.dupe(u8, rest) catch return; } /// Close a pane; its rows go to `to`, or where layout.absorbVWeight @@ -6053,8 +5897,18 @@ pub const Pardes = struct { p.trackJump(); for (&p.panes, 0..) |*slot, id| { const pane = slot.* orelse continue; - if (pane.tag_edit and (id != p.active or p.topbar_col != null)) - exitTagEdit(pane); + // The keyboard is on one pane, or on a header: a tag it has left + // hands it back to its body, and a name drafted there is dropped. + if (id != p.active or p.topbar_col != null) { + pane.focus = .body; + if (pane.prompt == .name) pane.closePrompt(); + } + // A sweep over the tag is the tag's while it has the keyboard. + const swept = pane.sel[sel_slot]; + if (pane.focus == .body and swept.state == .done and @min(swept.r0, swept.r1) < BOX_H) { + pane.clearPointerSelection(sel_slot); + pane.sel[sel_slot].state = .none; + } if (comptime terminal_panes) if (pane.terminal) |state| { var off: u16 = 0; while (off < state.reply_len) { @@ -6430,7 +6284,7 @@ pub const Pardes = struct { s.set(d.cur_x, placement.row, "▌", .{ .fg = .{ .rgb = chrome.lineno } }); } }, - .none, .select, .tag => if (p.pointer_inside) { + .none, .select => if (p.pointer_inside) { // hover hints on a pane's own trailing edge var c: usize = 0; while (c + 1 < p.ncol) : (c += 1) { @@ -6801,8 +6655,7 @@ pub const Pardes = struct { .font_role = .tagline, }; s.fill(r.x, tag_y, config.GUTTER, BOX_H, box_style); - const box_mode = if (pane.tag_edit) pane.tag_mode else pane.body.mode; - s.set(r.x, tag_y, switch (box_mode) { + s.set(r.x, tag_y, switch (pane.body.mode) { .normal => config.tag_normal, .insert => config.tag_insert, .tty => config.tag_tty, @@ -6856,9 +6709,24 @@ pub const Pardes = struct { .bg = .{ .rgb = tag_bg }, .font_role = .tagline, }); - const tag = try p.tagText(arena, pane); - if (active and pane.tag_edit) { - const caret = panes.File.rawDisplayCol(tag, pane.tag_col); + const whole = try p.tagText(arena, pane); + const tail = curTail(pane); + const prefix_len = whole.len - tail.len; + // The tagline shows the tag's first line: its prefix and the first + // line of its own text. + const tag = whole[0 .. std.mem.indexOfScalar(u8, whole, '\n') orelse whole.len]; + // The keyboard's caret on it, as a byte offset: in its own text when + // the tag has the keyboard, in the path while a name is drafted. + const caret_at: ?usize = if (!active) + null + else if (pane.prompt == .name) + @min(tag.len, @as(usize, @intCast(@max(0, pane.input.cur_col)))) + else if (pane.focus == .tag and pane.tag.cur_row == 0) + @min(tag.len, prefix_len + @as(usize, @intCast(@max(0, pane.tag.cur_col)))) + else + null; + if (caret_at) |at| { + const caret = panes.File.rawDisplayCol(tag, at); var scroll: usize = pane.tag_scroll; if (caret < scroll) scroll = caret; if (caret >= scroll + capacity) scroll = caret - capacity + 1; @@ -6869,10 +6737,10 @@ pub const Pardes = struct { scroll = panes.File.rawDisplayCol(tag, raw); } pane.tag_scroll = @intCast(scroll); - } else pane.tag_scroll = 0; + } else if (pane.focus != .tag) pane.tag_scroll = 0; const tag_start = panes.File.rawAtDisplay(tag, pane.tag_scroll); _ = s.print(tx, tag_y, tw, tag[tag_start..], tag_style); - if (tagTintRange(pane, tag, tag.len - curTail(pane).len)) |name| { + if (tagTintRange(pane, tag, prefix_len)) |name| { const lo = @max(name.lo, tag_start); const hi = @min(name.hi, tag.len); if (lo < hi) { @@ -6889,23 +6757,31 @@ pub const Pardes = struct { body_layer.paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, sel, preview_bg, null); }; } - if (pane.tag_edit and pane.tag_sel) { - const b = tagSelBounds(pane); - var col = panes.File.rawDisplayCol(tag, b.lo) -| pane.tag_scroll; - const hi = modal.nextGrapheme(tag, b.hi); - const end = panes.File.rawDisplayCol(tag, hi); - while (col + pane.tag_scroll < end and col < tw) : (col += 1) { - const cell = s.at(tx + @as(u16, @intCast(col)), tag_y); - cell.default = false; - cell.style.bg = .{ .rgb = th.sel_bg }; - cell.style.fg = .{ .rgb = th.sel_fg }; + // The tag's own selections, while it has the keyboard. A range of one + // grapheme is the block cursor, not a selection. + if (pane.focus == .tag) { + var ranges: [Text.max_selections]modal.Selection = undefined; + const got = pane.tag.ranges(tail, 0, &ranges); + const shown = tag.len - prefix_len; + for (ranges[0..got.n]) |range| { + const lo = @min(range.anchor, range.head); + const hi = @max(range.anchor, range.head); + if (modal.nextGrapheme(tail, lo) >= hi or lo >= shown) continue; + var col = panes.File.rawDisplayCol(tag, prefix_len + lo) -| pane.tag_scroll; + const end = panes.File.rawDisplayCol(tag, prefix_len + @min(hi, shown)); + while (col + pane.tag_scroll < end and col < tw) : (col += 1) { + const cell = s.at(tx + @as(u16, @intCast(col)), tag_y); + cell.default = false; + cell.style.bg = .{ .rgb = th.sel_bg }; + cell.style.fg = .{ .rgb = th.sel_fg }; + } } } - // cursor while editing the tag: byte offset mapped to its display cell - if (active and pane.tag_edit) { - // bar while typing, block for `:` normal mode (same rule as a body) - const col = panes.File.rawDisplayCol(tag, pane.tag_col) -| pane.tag_scroll; - if (col < tw) s.cursor = .{ .x = tx + @as(u16, @intCast(col)), .y = tag_y, .bar = pane.body.mode == .insert }; + // the caret: bar while typing, block in normal mode (same rule as a body) + if (caret_at) |at| { + const col = panes.File.rawDisplayCol(tag, at) -| pane.tag_scroll; + const mode = if (pane.prompt == .name) pane.input.mode else pane.tag.mode; + if (col < tw) s.cursor = .{ .x = tx + @as(u16, @intCast(col)), .y = tag_y, .bar = mode == .insert }; } for (pane.sel, 0..) |selection, button| { @@ -7034,10 +6910,10 @@ test "raw terminal cursor obeys visibility without hiding modal and tag cursors" const modal_cursor = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; try std.testing.expectEqual(rect.x + config.GUTTER + 1, modal_cursor.x); try std.testing.expectEqual(body_y, modal_cursor.y); - p.enterTagEdit(pane, 0); + p.enterTag(pane); const tag_cursor = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; try std.testing.expectEqual(if (p.settings.tag_bottom) rect.y + rect.h - BOX_H else rect.y, tag_cursor.y); - Pardes.exitTagEdit(pane); + pane.focus = .body; pane.body.mode = .tty; try std.testing.expect((try p.render(frame.allocator())).cursor == null); @@ -7193,7 +7069,7 @@ test "a prompt is typed on its own line in the notice band and leaves the tag ro p.update(.{ .key = .{ .cp = '/' } }); p.update(.{ .key = .{ .cp = 't', .text = "tw" } }); p.update(.{ .key = .{ .cp = Key.left } }); - try std.testing.expect(pane.prompt == .search and !pane.tag_edit); + try std.testing.expect(pane.prompt == .search and pane.focus == .body); try std.testing.expectEqualStrings(config.search_marker ++ "tw", pane.promptText().?); _ = frame.reset(.retain_capacity); _ = try p.render(frame.allocator()); @@ -7243,8 +7119,7 @@ test "a stillborn pane gives its column to the first pane that joins it" { try std.testing.expect(p.executeBuiltinLine(shell, "Newcol")); const tagged = p.active; p.sync(); - p.seedTail(p.panes[tagged].?); - try std.testing.expect(p.panes[tagged].?.appendTag(" make")); + try p.panes[tagged].?.appendTag(" make"); try std.testing.expect(p.executeBuiltinLine(tagged, "Tty")); p.update(.tick); try std.testing.expect(p.panes[tagged] != null); diff --git a/test/mode.zig b/test/mode.zig index 19d59699..c429ea72 100644 --- a/test/mode.zig +++ b/test/mode.zig @@ -6,7 +6,7 @@ const Pardes = pardes.Pardes; fn mode(p: *Pardes, id: usize, expected: panes.Text.Mode) !void { try std.testing.expect(p.executeBuiltinLine(id, "Mode")); try std.testing.expectEqual(expected, p.panes[id].?.body.mode); - try std.testing.expect(!p.panes[id].?.tag_edit); + try std.testing.expect(p.panes[id].?.focus == .body); } fn clickModeTag(p: *Pardes) !void { @@ -17,13 +17,12 @@ fn clickModeTag(p: *Pardes) !void { const row = if (p.settings.tag_bottom) rect.y + rect.h - pardes.BOX_H else rect.y; for ([_]pardes.Mouse.Kind{ .press, .release }) |kind| p.update(.{ .mouse = .{ .button = .left, .kind = kind, .col = rect.x + pardes.TAG_TEXT_INSET + @as(u16, @intCast(col)), .row = row } }); - try std.testing.expect(pane.tag_edit); + try std.testing.expect(pane.focus == .tag); } -fn customTag(pane: *pardes.Pane, text: []const u8) void { - @memcpy(pane.tag_tail[0..text.len], text); - pane.tag_tail_len = text.len; - pane.tag_init = true; +fn customTag(pane: *pardes.Pane, text: []const u8) !void { + if (pane.tag.own) |own| pane.gpa.free(own); + pane.tag.own = try pane.gpa.dupe(u8, text); } test "Mode cycles terminal modes and keeps legacy toggle and custom tags" { @@ -37,14 +36,18 @@ test "Mode cycles terminal modes and keeps legacy toggle and custom tags" { try std.testing.expect(std.mem.indexOf(u8, try p.tagText(p.scratch.allocator(), pane), " Mode") != null); try mode(p, 0, .normal); try mode(p, 0, .insert); + // A clicked tag is typed into; its execute key is a normal-mode key, as + // a body's is, and the body keeps its own mode meanwhile. try clickModeTag(p); - try std.testing.expectEqual(panes.Text.Mode.insert, pane.tag_mode); + try std.testing.expectEqual(panes.Text.Mode.insert, pane.tag.mode); + try std.testing.expectEqual(panes.Text.Mode.insert, pane.body.mode); + p.update(.{ .key = .{ .cp = pardes.Key.escape } }); p.update(.{ .key = .{ .cp = pardes.Key.tab } }); try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.focus == .body); while (p.nextEffect()) |effect| try std.testing.expect(effect != .write); - customTag(pane, " Togglettymode Keep"); + try customTag(pane, " Togglettymode Keep"); try mode(p, 0, .normal); try mode(p, 0, .insert); try std.testing.expect(p.executeBuiltinLine(0, "Togglettymode")); @@ -53,7 +56,7 @@ test "Mode cycles terminal modes and keeps legacy toggle and custom tags" { try std.testing.expectEqual(panes.Text.Mode.normal, pane.body.mode); p.update(.{ .key = .{ .cp = 'b', .ctrl = true } }); try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); - try std.testing.expectEqualStrings(" Togglettymode Keep", pane.tag_tail[0..pane.tag_tail_len]); + try std.testing.expectEqualStrings(" Togglettymode Keep", pane.tag.own.?); } test "Mode from actual tag Exec preserves parked file and output insert transactions" { @@ -65,17 +68,17 @@ test "Mode from actual tag Exec preserves parked file and output insert transact const pane = try p.setTestFile("ab\n"); if (output) pane.file.?.output = .{ .from = .search }; try std.testing.expect(std.mem.indexOf(u8, try p.tagText(p.scratch.allocator(), pane), " Mode") == null); - customTag(pane, " Mode"); + try customTag(pane, " Mode"); try mode(p, 0, .insert); p.update(.{ .key = .{ .cp = '界', .text = "界" } }); p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); try std.testing.expectEqualStrings("界xab\n", pane.file.?.content); try clickModeTag(p); - try std.testing.expectEqual(panes.Text.Mode.insert, pane.tag_mode); - if (normal_tag) pane.body.mode = .normal; + try std.testing.expectEqual(panes.Text.Mode.insert, pane.body.mode); + if (normal_tag) pane.tag.mode = .normal else p.update(.{ .key = .{ .cp = pardes.Key.escape } }); p.update(.{ .key = .{ .cp = pardes.Key.tab } }); try std.testing.expectEqual(panes.Text.Mode.normal, pane.body.mode); - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.focus == .body); try std.testing.expect(pane.body.append_at == null); p.update(.{ .key = .{ .cp = 'u' } }); try std.testing.expectEqualStrings("ab\n", pane.file.?.content); diff --git a/test/panes.zig b/test/panes.zig index f1adafee..a391dba2 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -12,6 +12,17 @@ const image = pardes.image; const syntax = pardes.syntax; const filesystem = pardes.filesystem; +/// The tag's caret as a byte offset into the tag as it is shown, prefix +/// included. +fn tagCaret(p: *Pardes, pane: *Pane) !usize { + return (try p.tagPrefix(pane)).len + @as(usize, @intCast(pane.tag.cur_col)); +} + +fn setTag(pane: *Pane, text: []const u8) !void { + if (pane.tag.own) |own| pane.gpa.free(own); + pane.tag.own = try pane.gpa.dupe(u8, text); +} + const TagLayerTests = struct { const Kind = @FieldType(pardes.TagLayer, "kind"); fn findLayer(p: *Pardes, kind: Kind, id: usize) !*pardes.TagLayer { @@ -36,10 +47,7 @@ const TagLayerTests = struct { p.row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 5, .tagline_h = 10 }; p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, "/x"); - const tail = " " ++ "a" ** 38 ++ "\t界 END"; - @memcpy(pane.tag_tail[0..tail.len], tail); - pane.tag_tail_len = tail.len; - pane.tag_init = true; + try setTag(pane, " " ++ "a" ** 38 ++ "\t界 END"); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); _ = try p.render(frame.allocator()); @@ -55,11 +63,11 @@ const TagLayerTests = struct { var stale = mouse(layer, x, .press); stale.tag_hit.?.serial +%= 1; p.update(.{ .mouse = stale }); - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.focus == .body); p.update(.{ .mouse = mouse(layer, x, .press) }); p.update(.{ .mouse = mouse(layer, x, .release) }); - try std.testing.expect(pane.tag_edit); - try std.testing.expectEqual(@as(u16, @intCast(at)), pane.tag_col); + try std.testing.expect(pane.focus == .tag); + try std.testing.expectEqual(at, try tagCaret(p, pane)); p.update(.{ .key = .{ .cp = 'X', .text = "X" } }); _ = try p.render(frame.allocator()); const edited = try p.tagText(frame.allocator(), pane); @@ -91,7 +99,7 @@ const TagLayerTests = struct { event.row = @intFromFloat(painted_y); p.update(.{ .mouse = event }); } - try std.testing.expectEqual(@as(u16, @intCast(at)), pane.tag_col); + try std.testing.expectEqual(at, try tagCaret(p, pane)); } } @@ -119,19 +127,17 @@ const TagLayerTests = struct { try std.testing.expectEqualStrings(" ", p.surface.at(layer.viewport.x - 1, layer.viewport.y).grapheme()); p.update(.{ .mouse = mouse(layer, edge - 0.1, .press) }); try std.testing.expect(p.drag != .move); - try std.testing.expect(!p.panes[second].?.tag_edit); + try std.testing.expect(p.panes[second].?.focus == .body); p.update(.{ .mouse = mouse(layer, edge - 0.1, .release) }); p.update(.{ .mouse = mouse(layer, edge + 0.1, .press) }); p.update(.{ .mouse = mouse(layer, edge + 0.1, .release) }); try std.testing.expectEqual(second, p.active); - try std.testing.expect(p.panes[second].?.tag_edit); - try std.testing.expectEqual(@as(u16, 0), p.panes[second].?.tag_col); + // The first cell of the tag is its path: a click there drafts a name. + try std.testing.expect(p.panes[second].?.prompt == .name); + try std.testing.expectEqual(@as(i32, 0), p.panes[second].?.input.cur_col); p.update(.{ .key = .{ .cp = Key.escape } }); const left = p.panes[0].?; - const tail = " " ++ "a" ** 110; - @memcpy(left.tag_tail[0..tail.len], tail); - left.tag_tail_len = tail.len; - left.tag_init = true; + try setTag(left, " " ++ "a" ** 110); _ = try p.render(frame.allocator()); const left_layer = try findLayer(p, .pane, 0); const left_text = try p.tagText(frame.allocator(), left); @@ -142,8 +148,8 @@ const TagLayerTests = struct { p.update(.{ .mouse = mouse(layer, beyond_x, .release) }); try std.testing.expectEqual(@as(usize, 0), p.active); const end_col = left_layer.capacity(p.row_metrics) - 1; - try std.testing.expectEqual(@as(u16, @intCast(panes.File.rawAtDisplay(left_text, end_col))), left.tag_col); - try std.testing.expect(left.tag_sel); + try std.testing.expectEqual(panes.File.rawAtDisplay(left_text, end_col), try tagCaret(p, left)); + try std.testing.expect(left.sel[0].state == .done and left.sel[0].r0 == 0); p.update(.{ .key = .{ .cp = Key.escape } }); const long = "a" ** 60 ++ "界END"; try std.testing.expect(p.global_tag.set(long)); @@ -167,12 +173,12 @@ const TagNavigationTests = struct { p.update(.{ .key = .{ .cp = cp } }); } - fn enterNormal(p: *Pardes) *Pane { - key(p, ':'); - return p.panes[p.active].?; + fn window(p: *Pardes, letter: u21) void { + p.update(.{ .key = .{ .cp = 'w', .ctrl = true } }); + key(p, letter); } - test "tag navigation retains each pane cursor and mouse placement overrides memory" { + test "a tag remembers its cursor, starts on Save, and a click moves it" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 20 }); defer p.deinit(); const first = try p.setTestFile("body\n"); @@ -183,65 +189,97 @@ const TagNavigationTests = struct { try std.testing.expect(layout.splitColumn(p, second_id, second_id, false)); p.update(.tick); p.active = 0; + // Nothing to remember yet: `:` lands on Save, in normal mode. key(p, ':'); + try std.testing.expect(first.focus == .tag and first.tag.mode == .normal); + const tail = Pardes.curTail(first); + try std.testing.expectEqualStrings("Save", tail[@intCast(first.tag.cur_col)..][0..4]); key(p, Key.home); for (0..3) |_| key(p, Key.right); - const first_col = first.tag_col; - key(p, Key.escape); + try std.testing.expectEqual(@as(i32, 3), first.tag.cur_col); + // `:` in the tag's normal mode is the way back to the body. + key(p, ':'); + try std.testing.expect(first.focus == .body); p.active = second_id; key(p, ':'); key(p, Key.home); for (0..5) |_| key(p, Key.right); - const second_col = second.tag_col; - key(p, Key.escape); + key(p, ':'); p.active = 0; key(p, ':'); - try std.testing.expectEqual(first_col, first.tag_col); - key(p, Key.escape); + try std.testing.expectEqual(@as(i32, 3), first.tag.cur_col); + key(p, ':'); p.active = second_id; key(p, ':'); - try std.testing.expectEqual(second_col, second.tag_col); - key(p, Key.escape); + try std.testing.expectEqual(@as(i32, 5), second.tag.cur_col); + key(p, ':'); var frame = std.heap.ArenaAllocator.init(p.gpa); defer frame.deinit(); _ = try p.render(frame.allocator()); const rect = p.rects[0]; const y = if (p.settings.tag_bottom) rect.y + rect.h - pardes.BOX_H else rect.y; - ClickCursorTests.click(p, .left, rect.x + pardes.TAG_TEXT_INSET + 6, y); + const prefix: u16 = @intCast(panes.File.displayWidth(try p.tagPrefix(first))); + ClickCursorTests.click(p, .left, rect.x + pardes.TAG_TEXT_INSET + prefix + 6, y); try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expectEqual(@as(u16, 6), first.tag_col); + try std.testing.expect(first.focus == .tag and first.tag.mode == .insert); + try std.testing.expectEqual(@as(i32, 6), first.tag.cur_col); key(p, Key.escape); + key(p, ':'); p.startPrompt(first, .{ .search = config.search_marker }); key(p, Key.escape); key(p, ':'); - try std.testing.expectEqual(@as(u16, 6), first.tag_col); - key(p, Key.escape); + try std.testing.expectEqual(@as(i32, 6), first.tag.cur_col); + key(p, ':'); try std.testing.expectEqualStrings("body\n", first.file.?.content); } - test "tag navigation clamps remembered columns to renamed graphemes and shorter tags" { + test "executing a word from the tag runs it and gives the keyboard back to the body" { + for ([_]u21{ Key.tab, Key.enter }) |chord| { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 20 }); + defer p.deinit(); + const pane = try p.setTestFile("body\n"); + p.update(.{ .key = .{ .cp = 'i' } }); + p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); + p.update(.{ .key = .{ .cp = Key.escape } }); + while (p.nextEffect()) |_| {} + // `:` lands on Save; the execute key runs it, the look key looks + // it up. Either way the tag lets go of the keyboard first. + key(p, ':'); + try std.testing.expect(pane.focus == .tag); + key(p, chord); + try std.testing.expect(pane.focus == .body); + try std.testing.expectEqual(.normal, pane.body.mode); + var saved = false; + while (p.nextEffect()) |effect| { + if (effect == .save_file) saved = true; + } + try std.testing.expectEqual(chord == Key.tab, saved); + // ...and the tag still knows where it was. + key(p, ':'); + try std.testing.expectEqualStrings("Save", Pardes.curTail(pane)[@intCast(pane.tag.cur_col)..][0..4]); + } + } + + test "a renamed path never moves the tag's cursor and a shorter tag pulls it back" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 14 }); defer p.deinit(); const pane = try p.setTestFile("body\n"); key(p, ':'); key(p, Key.home); for (0..3) |_| key(p, Key.right); - key(p, Key.escape); + key(p, ':'); p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, "/界.zig"); key(p, ':'); - try std.testing.expectEqual(@as(u16, 1), pane.tag_col); - key(p, Key.end); - key(p, Key.escape); - p.gpa.free(pane.file.?.path); - pane.file.?.path = try p.gpa.dupe(u8, "/é"); - pane.tag_tail_len = 0; + try std.testing.expectEqual(@as(i32, 3), pane.tag.cur_col); + key(p, ':'); + try setTag(pane, "é"); key(p, ':'); - try std.testing.expectEqual(@as(u16, 3), pane.tag_col); + try std.testing.expectEqual(@as(i32, 2), pane.tag.cur_col); try std.testing.expectEqualStrings("body\n", pane.file.?.content); } - test "tag navigation J and K restore cursors in stacked panes" { + test "window keys move between panes from a tag and each tag keeps its cursor" { for ([_]bool{ false, true }) |bottom| { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -253,88 +291,67 @@ const TagNavigationTests = struct { const second = p.panes[second_id].?; p.update(.tick); p.active = 0; - _ = enterNormal(p); + key(p, ':'); key(p, Key.home); key(p, 'l'); key(p, 'l'); - key(p, 'J'); + window(p, 'j'); try std.testing.expectEqual(second_id, p.active); - try std.testing.expect(!first.tag_edit and second.tag_edit); + try std.testing.expect(first.focus == .body and second.focus == .body); + key(p, ':'); key(p, Key.home); for (0..4) |_| key(p, 'l'); - key(p, 'K'); + window(p, 'k'); try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expectEqual(@as(u16, 2), first.tag_col); - key(p, 'J'); - try std.testing.expectEqual(second_id, p.active); - try std.testing.expectEqual(@as(u16, 4), second.tag_col); + try std.testing.expect(second.focus == .body); + key(p, ':'); + try std.testing.expectEqual(@as(i32, 2), first.tag.cur_col); + window(p, 'j'); + key(p, ':'); + try std.testing.expectEqual(@as(i32, 4), second.tag.cur_col); } } - test "tag navigation uses uppercase pane and header keys while lowercase stays local" { + test "a tag's normal mode is the body's: motions stay in the tag and insert types into it" { for ([_]bool{ false, true }) |bottom| { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 20 }); defer p.deinit(); _ = try p.setTestFile("body\n"); p.presentation.enabled = false; p.settings.tag_bottom = bottom; - p.settings.column_tags = true; try std.testing.expect(p.executeBuiltinLine(0, "New")); const right = p.active; try std.testing.expect(layout.splitColumn(p, right, right, false)); p.update(.tick); p.active = 0; - const pane = enterNormal(p); + key(p, ':'); + const pane = p.panes[0].?; key(p, Key.home); key(p, 'l'); - try std.testing.expectEqual(@as(u16, 1), pane.tag_col); + try std.testing.expectEqual(@as(i32, 1), pane.tag.cur_col); key(p, 'h'); key(p, 'k'); - try std.testing.expectEqual(@as(u16, 0), pane.tag_col); + key(p, 'j'); + try std.testing.expectEqual(@as(i32, 0), pane.tag.cur_col); try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expect(pane.tag_edit and p.topbar_col == null); - key(p, 'L'); + try std.testing.expect(pane.focus == .tag and p.topbar_col == null); + window(p, 'l'); try std.testing.expectEqual(right, p.active); - try std.testing.expect(!pane.tag_edit and p.panes[right].?.tag_edit); - key(p, 'H'); + try std.testing.expect(pane.focus == .body and p.panes[right].?.focus == .body); + window(p, 'h'); try std.testing.expectEqual(@as(usize, 0), p.active); - key(p, 'K'); - try std.testing.expect(p.topbar_col != null and p.header_column != null); - try std.testing.expect(!pane.tag_edit); - key(p, 'l'); - const column_cursor = p.topbar_col.?; - key(p, 'K'); - try std.testing.expect(p.topbar_col != null and p.header_column == null); - key(p, 'l'); - key(p, 'l'); - const workspace_cursor = p.topbar_col.?; - key(p, 'J'); - try std.testing.expect(p.topbar_col != null and p.header_column != null); - try std.testing.expectEqual(column_cursor, p.topbar_col.?); - key(p, 'K'); - try std.testing.expectEqual(workspace_cursor, p.topbar_col.?); - key(p, 'J'); - key(p, 'J'); - try std.testing.expect(p.topbar_col == null and pane.tag_edit); - key(p, 'j'); - try std.testing.expect(!pane.tag_edit and p.topbar_col == null); - try std.testing.expectEqual(@as(usize, 0), p.active); - _ = enterNormal(p); - key(p, 'K'); - key(p, 'j'); - try std.testing.expect(p.topbar_col == null and !pane.tag_edit); key(p, ':'); key(p, 'i'); key(p, Key.end); - const before = pane.tag_tail_len; - try std.testing.expect(pane.tag_edit and pane.body.mode == .insert); - for ("hjklHJKL") |letter| { + const before = Pardes.curTail(pane).len; + try std.testing.expect(pane.focus == .tag and pane.tag.mode == .insert and pane.body.mode == .normal); + for ("hjklHJKL:") |letter| { const text = [_]u8{letter}; p.update(.{ .key = .{ .cp = letter, .text = &text } }); - try std.testing.expect(pane.tag_edit and pane.body.mode == .insert); + try std.testing.expect(pane.focus == .tag and pane.tag.mode == .insert); } - try std.testing.expectEqualStrings("hjklHJKL", pane.tag_tail[before..pane.tag_tail_len]); - try std.testing.expect(pane.tag_edit and pane.body.mode == .insert and p.topbar_col == null); + try std.testing.expectEqualStrings("hjklHJKL:", Pardes.curTail(pane)[before..]); + try std.testing.expectEqualStrings("body\n", pane.file.?.content); try std.testing.expectEqual(@as(usize, 0), p.active); } } @@ -1151,32 +1168,26 @@ const TagNameTintTests = struct { } } - test "tag filename tint follows scrolled Unicode staged names and yields to selection" { + test "tag filename tint follows scrolled Unicode drafted names and yields to selection" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 38, .rows = 14 }); defer p.deinit(); const pane = try p.setTestFile("body\n"); - const old = pane.file.?.path.len; configure(p); defer p.custom_theme = null; - p.update(.{ .key = .{ .cp = ':' } }); - p.update(.{ .key = .{ .cp = 'i' } }); - pane.tag_anchor = 0; - pane.tag_col = @intCast(old - 1); - pane.tag_sel = true; const name = "/a/very/long/directory/that/extends/past/the/tag/界e\u{301}name-with-a-long-tail.zig"; - p.update(.{ .paste = name }); - try std.testing.expectEqualStrings(name, pane.tag_name[0..pane.tag_name_len.?]); - pane.tag_col = @intCast(std.mem.indexOf(u8, name, "界").?); - pane.tag_sel = false; + p.draftName(pane, 0); + redraft(pane, name); + pane.input.cur_col = @intCast(std.mem.indexOf(u8, name, "界").?); try std.testing.expect((try check(p, 0, name)) > 0); try std.testing.expect(pane.tag_scroll > 0); - pane.tag_anchor = pane.tag_col; - pane.tag_sel = true; + // A sweep over the wide glyph wears the selection over the tint. + const col: i32 = @intCast(panes.File.rawDisplayCol(name, @intCast(pane.input.cur_col))); + pane.sel[0] = .{ .state = .done, .c0 = col, .c1 = col + 1, .r0 = 0, .r1 = 0 }; pane.tag_scroll += 4; // bring both cells of the selected wide glyph into view var arena = std.heap.ArenaAllocator.init(p.gpa); defer arena.deinit(); const surface = try p.render(arena.allocator()); - const x = p.rects[0].x + pardes.TAG_TEXT_INSET + @as(u16, @intCast(panes.File.rawDisplayCol(name, pane.tag_col) - pane.tag_scroll)); + const x = p.rects[0].x + pardes.TAG_TEXT_INSET + @as(u16, @intCast(col - pane.tag_scroll)); const y = if (p.settings.tag_bottom) p.rects[0].y + p.rects[0].h - pardes.BOX_H else p.rects[0].y; try std.testing.expectEqual(pardes.Color{ .rgb = p.theme().sel_fg }, surface.at(x, y).style.fg); try std.testing.expectEqual(pardes.Color{ .rgb = p.theme().sel_fg }, surface.at(x + 1, y).style.fg); @@ -1208,32 +1219,46 @@ const TagNameTintTests = struct { } }; -test "pane filename edits stage commit and cancel without changing body or command tail" { +/// Replace a name draft's text, the caret after it, as clearing it and +/// typing would. +fn redraft(pane: *Pane, name: []const u8) void { + if (pane.input.own) |own| pane.gpa.free(own); + pane.input.own = pane.gpa.dupe(u8, name) catch unreachable; + pane.input.cur_col = @intCast(name.len); +} + +/// Click the tagline at the end of the path: a name draft, caret there. +fn clickPathEnd(p: *Pardes, pane: *Pane) void { + const rect = p.rects[p.active]; + const y = if (p.settings.tag_bottom) rect.y + rect.h - pardes.BOX_H else rect.y; + const x = rect.x + pardes.TAG_TEXT_INSET + @as(u16, @intCast(panes.File.displayWidth(pane.file.?.path) - 1)); + ClickCursorTests.click(p, .left, x, y); + std.debug.assert(pane.prompt == .name); + pane.input.cur_col = @intCast(pane.input.own.?.len); +} + +test "pane filename drafts commit and cancel without changing body or command tail" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 70, .rows = 12 }); defer p.deinit(); const pane = try p.setTestFile("original body\n"); const original = try p.gpa.dupe(u8, pane.file.?.path); defer p.gpa.free(original); - p.seedTail(pane); - try std.testing.expect(pane.appendTag(" SyntaxBold")); - const tail = try p.gpa.dupe(u8, pane.tagSlice()); + try pane.appendTag(" SyntaxBold"); + const tail = try p.gpa.dupe(u8, Pardes.curTail(pane)); defer p.gpa.free(tail); for ([_]bool{ false, true }) |commit| { - p.update(.{ .key = .{ .cp = ':' } }); - p.update(.{ .key = .{ .cp = 'i' } }); - pane.tag_anchor = 0; - pane.tag_col = @intCast(original.len - 1); - pane.tag_sel = true; + clickPathEnd(p, pane); + p.update(.{ .key = .{ .cp = 'u', .ctrl = true } }); p.update(.{ .paste = "/new name.zig" }); try std.testing.expectEqualStrings(original, pane.file.?.path); - try std.testing.expectEqualStrings("/new name.zig", pane.tag_name[0..pane.tag_name_len.?]); - try std.testing.expectEqualStrings(tail, pane.tagSlice()); + try std.testing.expectEqualStrings("/new name.zig", pane.input.own.?); + try std.testing.expectEqualStrings(tail, Pardes.curTail(pane)); try std.testing.expectEqualStrings("original body\n", pane.file.?.content); p.update(.{ .key = .{ .cp = if (commit) Key.enter else Key.escape } }); - try std.testing.expect(!pane.tag_edit); - try std.testing.expect(pane.tag_name_len == null); + try std.testing.expect(pane.focus == .body); + try std.testing.expect(pane.prompt == .none); try std.testing.expectEqualStrings(if (commit) "/new name.zig" else original, pane.file.?.path); - try std.testing.expectEqualStrings(tail, pane.tagSlice()); + try std.testing.expectEqualStrings(tail, Pardes.curTail(pane)); while (p.nextEffect()) |effect| try std.testing.expect(std.meta.activeTag(effect) != .save_file); } try std.testing.expect(pane.file.?.revision != pane.file.?.saved_revision); @@ -1243,27 +1268,21 @@ test "pane filename grapheme edits and invalid empty commits preserve the buffer const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("untouched\n"); - p.update(.{ .key = .{ .cp = ':' } }); - p.update(.{ .key = .{ .cp = 'i' } }); - pane.tag_anchor = 0; - pane.tag_col = @intCast(pane.file.?.path.len - 1); - pane.tag_sel = true; + clickPathEnd(p, pane); + p.update(.{ .key = .{ .cp = 'u', .ctrl = true } }); p.update(.{ .paste = "/café界" }); p.update(.{ .key = .{ .cp = Key.backspace } }); - try std.testing.expectEqualStrings("/café", pane.tag_name[0..pane.tag_name_len.?]); + try std.testing.expectEqualStrings("/café", pane.input.own.?); p.update(.{ .key = .{ .cp = Key.backspace } }); - try std.testing.expectEqualStrings("/caf", pane.tag_name[0..pane.tag_name_len.?]); - pane.tag_anchor = 0; - pane.tag_col = 3; - pane.tag_sel = true; - p.update(.{ .key = .{ .cp = Key.delete } }); - try std.testing.expectEqual(@as(u16, 0), pane.tag_name_len.?); + try std.testing.expectEqualStrings("/caf", pane.input.own.?); + p.update(.{ .key = .{ .cp = 'u', .ctrl = true } }); + try std.testing.expectEqualStrings("", pane.input.own.?); p.update(.{ .key = .{ .cp = Key.enter } }); - try std.testing.expect(pane.tag_edit); + try std.testing.expect(pane.prompt == .name); try std.testing.expectEqualStrings("/test.txt", pane.file.?.path); try std.testing.expectEqualStrings("untouched\n", pane.file.?.content); p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expect(pane.tag_name_len == null); + try std.testing.expect(pane.prompt == .none); } test "leaving a pane or entering a header cancels an uncommitted filename" { @@ -1273,11 +1292,10 @@ test "leaving a pane or entering a header cancels an uncommitted filename" { for ([_]bool{ false, true }) |header| { p.active = 0; p.topbar_col = null; - p.update(.{ .key = .{ .cp = ':' } }); - p.update(.{ .key = .{ .cp = 'i' } }); - p.update(.{ .key = .{ .cp = Key.home } }); + p.update(.tick); + clickPathEnd(p, pane); p.update(.{ .paste = "/draft" }); - try std.testing.expect(pane.tag_name_len != null); + try std.testing.expect(pane.prompt == .name); if (header) { p.topbar_col = 0; p.update(.tick); @@ -1285,21 +1303,18 @@ test "leaving a pane or entering a header cancels an uncommitted filename" { try std.testing.expect(p.executeBuiltinLine(0, "New")); p.update(.tick); } - try std.testing.expect(pane.tag_name_len == null); - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.prompt == .none); + try std.testing.expect(pane.focus == .body); try std.testing.expectEqualStrings("/test.txt", pane.file.?.path); } } -test "middle clicking Save commits the staged filename before issuing a save" { +test "middle clicking Save commits the drafted filename before issuing a save" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 70, .rows = 12 }); defer p.deinit(); const pane = try p.setTestFile("untouched\n"); - p.update(.{ .key = .{ .cp = ':' } }); - p.update(.{ .key = .{ .cp = 'i' } }); - pane.tag_anchor = 0; - pane.tag_col = @intCast(pane.file.?.path.len - 1); - pane.tag_sel = true; + clickPathEnd(p, pane); + p.update(.{ .key = .{ .cp = 'u', .ctrl = true } }); p.update(.{ .paste = "/renamed.txt" }); var arena = std.heap.ArenaAllocator.init(p.gpa); defer arena.deinit(); @@ -1312,7 +1327,7 @@ test "middle clicking Save commits the staged filename before issuing a save" { p.update(.{ .mouse = .{ .col = x, .row = y, .button = config.exec_button, .kind = .press } }); p.update(.{ .mouse = .{ .col = x, .row = y, .button = config.exec_button, .kind = .release } }); try std.testing.expectEqualStrings("/renamed.txt", pane.file.?.path); - try std.testing.expect(pane.tag_name_len == null); + try std.testing.expect(pane.prompt == .none); try std.testing.expectEqualStrings("untouched\n", pane.file.?.content); var saves: usize = 0; while (p.nextEffect()) |effect| if (effect == .save_file) { @@ -1322,24 +1337,19 @@ test "middle clicking Save commits the staged filename before issuing a save" { try std.testing.expectEqual(@as(usize, 1), saves); } -test "oversized filename paste refuses atomically across a selected tag boundary" { +test "an oversized drafted name is refused at commit and the draft stays to correct" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("untouched\n"); - p.update(.{ .key = .{ .cp = ':' } }); - p.update(.{ .key = .{ .cp = 'i' } }); - const before = try p.tagText(p.gpa, pane); - defer p.gpa.free(before); - pane.tag_anchor = 0; - pane.tag_col = @intCast(before.len - 1); - pane.tag_sel = true; - const excess = try p.gpa.alloc(u8, pane.tag_name.len + 1); + clickPathEnd(p, pane); + const excess = try p.gpa.alloc(u8, 5000); defer p.gpa.free(excess); @memset(excess, 'x'); + excess[0] = '/'; p.update(.{ .paste = excess }); - try std.testing.expect(pane.tag_name_len == null); - try std.testing.expect(pane.tag_sel); - try std.testing.expectEqualStrings(before, try p.tagText(p.scratch.allocator(), pane)); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(pane.prompt == .name); + try std.testing.expectEqualStrings("/test.txt", pane.file.?.path); try std.testing.expectEqualStrings("untouched\n", pane.file.?.content); } @@ -1349,16 +1359,17 @@ test "paste into pane commands and prompts never inserts into the body" { const pane = try p.setTestFile("one two one\n"); p.update(.{ .key = .{ .cp = ':' } }); p.update(.{ .key = .{ .cp = 'A' } }); - p.update(.{ .paste = " Custom\r\nCommand" }); - try std.testing.expect(std.mem.endsWith(u8, pane.tagSlice(), " CustomCommand")); + // A tag takes a paste as a body does, newline and all. + p.update(.{ .paste = " Custom\nCommand" }); + try std.testing.expect(std.mem.indexOf(u8, Pardes.curTail(pane), " Custom\nCommand") != null); p.update(.{ .key = .{ .cp = Key.escape } }); p.startPrompt(pane, .{ .search = config.search_marker }); p.update(.{ .paste = "t\r\nwo" }); try std.testing.expectEqualStrings(config.search_marker ++ "two", pane.promptText().?); - try std.testing.expect(std.mem.endsWith(u8, pane.tagSlice(), " CustomCommand")); + try std.testing.expect(std.mem.indexOf(u8, Pardes.curTail(pane), " Custom\nCommand") != null); try std.testing.expectEqualStrings("one two one\n", pane.file.?.content); p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expect(std.mem.endsWith(u8, pane.tagSlice(), " CustomCommand")); + try std.testing.expect(std.mem.indexOf(u8, Pardes.curTail(pane), " Custom\nCommand") != null); } test "long pane tags reveal commands and map visible clicks to whole tag addresses" { @@ -1367,8 +1378,7 @@ test "long pane tags reveal commands and map visible clicks to whole tag address const pane = try p.setTestFile("body\n"); p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, "/an/especially/deep/project/path/with/a/long/component/filename.zig"); - p.seedTail(pane); - try std.testing.expect(pane.appendTag(" SyntaxBold")); + try pane.appendTag(" SyntaxBold"); p.update(.{ .key = .{ .cp = ':' } }); p.update(.{ .key = .{ .cp = 'A' } }); var arena = std.heap.ArenaAllocator.init(p.gpa); @@ -1549,7 +1559,13 @@ test "terminal edits and undo survive partial history clearing and whole-screen pane.body.cur_pinned = true; pane.body.vsel = .{ .active = true, .row = row, .col = 1 }; panes.Terminal.pushUndo(p, pane); - pane.body.ed_redo[0] = panes.Terminal.snap(p, pane) orelse return error.SnapshotFailed; + const overlay = pane.ovl.?; + pane.body.ed_redo[0] = .{ + .ovl = .{ .row = overlay.row, .rows = overlay.rows, .text = try gpa.dupe(u8, overlay.text) }, + .cur_row = pane.body.cur_row, + .cur_col = pane.body.cur_col, + .vsel = pane.body.vsel, + }; pane.body.ed_redo_len = 1; if (action == .hidden_undo) { gpa.free(pane.ovl.?.text); @@ -1663,9 +1679,7 @@ test "a prompt's entry and cancellation leave the tag, the body and its cursor a try pane.setOwnedCwd("/dír space"); const tail = " keep"; for (cases) |case| { - @memcpy(pane.tag_tail[0..tail.len], tail); - pane.tag_tail_len = tail.len; - pane.tag_init = true; + try setTag(pane, tail); pane.body.cur_row = 1; pane.body.cur_col = 2; pane.body.cur_pinned = true; @@ -1677,17 +1691,17 @@ test "a prompt's entry and cancellation leave the tag, the body and its cursor a p.startPrompt(pane, .{ .search = config.search_marker }); } // The answer is typed into the prompt's own line, never the tag. - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.focus == .body); try std.testing.expectEqual(.insert, pane.input.mode); try std.testing.expectEqualStrings(case.marker, pane.promptText().?); try std.testing.expectEqual(@as(i32, @intCast(case.marker.len)), pane.input.cur_col); - try std.testing.expectEqualStrings(tail, pane.tag_tail[0..pane.tag_tail_len]); + try std.testing.expectEqualStrings(tail, pane.tag.own.?); try std.testing.expectEqualDeep(modal.Normal.State{}, pane.body.normal); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expect(pane.prompt == .none); try std.testing.expect(pane.input.own == null); try std.testing.expectEqual(.normal, pane.body.mode); - try std.testing.expectEqualStrings(tail, pane.tag_tail[0..pane.tag_tail_len]); + try std.testing.expectEqualStrings(tail, pane.tag.own.?); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); try std.testing.expectEqual(@as(i32, 2), pane.body.cur_col); try std.testing.expectEqualStrings("one\ntwo\n", pane.file.?.content); @@ -1698,9 +1712,10 @@ test "a prompt opens whatever the tag already holds" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("one\n"); - @memset(&pane.tag_tail, 'x'); - pane.tag_tail_len = pane.tag_tail.len; - pane.tag_init = true; + const full = try p.gpa.alloc(u8, pardes.memory.limits.max_tag_tail); + defer p.gpa.free(full); + @memset(full, 'x'); + try setTag(pane, full); for (0..3) |case| { switch (case) { 0 => p.startPrompt(pane, .{ .search = config.search_marker }), @@ -1708,8 +1723,7 @@ test "a prompt opens whatever the tag already holds" { else => p.update(.{ .key = .{ .cp = '|' } }), } try std.testing.expect(pane.prompt != .none); - try std.testing.expectEqual(pane.tag_tail.len, pane.tag_tail_len); - for (pane.tag_tail) |byte| try std.testing.expectEqual(@as(u8, 'x'), byte); + try std.testing.expectEqualStrings(full, pane.tag.own.?); p.update(.{ .key = .{ .cp = Key.escape } }); } } @@ -1723,8 +1737,8 @@ test "generated output refuses every pipe prompt before seeding the tag" { for ([_]Key{ .{ .cp = '|' }, .{ .cp = '|', .alt = true }, .{ .cp = '!' }, .{ .cp = '!', .alt = true } }) |key| { p.update(.{ .key = key }); try std.testing.expect(pane.prompt == .none); - try std.testing.expect(!pane.tag_init); - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.tag.own == null); + try std.testing.expect(pane.focus == .body); try std.testing.expectEqualStrings("generated\n", pane.file.?.content); } } @@ -1798,7 +1812,7 @@ test "a prompt that cannot be opened leaves the open one as it was" { try std.testing.expect(pane.prompt == .search); try std.testing.expectEqualStrings(config.search_marker ++ "prior", pane.promptText().?); try std.testing.expectEqualDeep(previous_normal, pane.body.normal); - try std.testing.expect(!pane.tag_init and !pane.tag_edit); + try std.testing.expect(pane.tag.own == null and pane.focus == .body); } } @@ -1830,7 +1844,7 @@ test "a prompt opens with one allocation" { const before = failing.alloc_index; p.startPrompt(pane, request); try std.testing.expectEqual(before + 1, failing.alloc_index); - try std.testing.expect(!pane.tag_edit and pane.input.mode == .insert); + try std.testing.expect(pane.focus == .body and pane.input.mode == .insert); } } @@ -4080,14 +4094,18 @@ test "cancelled normal gestures leave no count or subprefix after mouse and focu const rect = p.rects[0]; const tag_y = if (p.settings.tag_bottom) rect.y + rect.h - pardes.BOX_H else rect.y; const body_y = p.bodyTop(rect); - const x = rect.x + config.GUTTER + @as(u16, @intCast(panes.File.gutterWidth(pane))) + 3; + const x = if (gesture == .tag) + rect.x + pardes.TAG_TEXT_INSET + @as(u16, @intCast(panes.File.displayWidth(try p.tagPrefix(pane)))) + 3 + else + rect.x + config.GUTTER + @as(u16, @intCast(panes.File.gutterWidth(pane))) + 3; const y = if (gesture == .tag) tag_y else body_y; p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = x, .row = y } }); p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = x, .row = y } }); if (gesture == .tag) { - try std.testing.expect(pane.tag_edit); + try std.testing.expect(pane.focus == .tag); p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expect(!pane.tag_edit); + p.update(.{ .key = .{ .cp = ':' } }); + try std.testing.expect(pane.focus == .body); } }, .focus, .last => { diff --git a/test/pdf.zig b/test/pdf.zig index 5bc271d4..745ecb1a 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -309,8 +309,8 @@ test "PDF dump fallback remains a byte-preserving file" { try std.testing.expect(!hasPdf(pane)); try std.testing.expectEqualStrings(path, pane.file.?.path); try std.testing.expectEqualSlices(u8, source, pane.file.?.content); - try std.testing.expect(pane.tag_init); - try std.testing.expectEqualStrings(" Keep Del", pane.tag_tail[0..pane.tag_tail_len]); + try std.testing.expect(pane.tag.own != null); + try std.testing.expectEqualStrings(" Keep Del", pane.tag.own.?); } test "PdfSections Look follows the exact owning PDF, not an equal path" { @@ -918,9 +918,8 @@ test "MuPDF pane renders, navigates, searches, and round-trips its page" { try std.testing.expectEqual(PdfTintMode.full, pane.pdf.?.tint); pane.pdf.?.fit = .height; const custom_tail = " Keep Del"; - @memcpy(pane.tag_tail[0..custom_tail.len], custom_tail); - pane.tag_tail_len = custom_tail.len; - pane.tag_init = true; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = try p.gpa.dupe(u8, custom_tail); try pardes.dump.dumpState(p); const restored = try pardes.dump.initFromDump(gpa, .{}, p.dump_out.?); defer restored.deinit(); @@ -929,10 +928,10 @@ test "MuPDF pane renders, navigates, searches, and round-trips its page" { try std.testing.expectEqual(PdfFitMode.width, restored.panes[0].?.pdf.?.fit); try std.testing.expectEqual(PdfTintMode.filtered, restored.panes[0].?.pdf.?.tint); const restored_pane = restored.panes[0].?; - try std.testing.expect(restored_pane.tag_init); + try std.testing.expect(restored_pane.tag.own != null); try std.testing.expectEqualStrings( custom_tail, - restored_pane.tag_tail[0..restored_pane.tag_tail_len], + restored_pane.tag.own.?, ); } @@ -1100,20 +1099,20 @@ test "PDF normal adapter consumes unsupported actions and navigates page fallbac try std.testing.expectEqual(@as(u32, 0), pane.body.normal.count); try std.testing.expectEqual(.none, pane.body.normal.prefix); try std.testing.expect(!pane.body.vsel.active and !pane.body.msel.active and pane.body.nsel == 0); - try std.testing.expect(!pane.tag_edit); + try std.testing.expect(pane.focus == .body); // Cross-pane BODY-NORMAL actions keep their established shared paths. p.update(.{ .key = .{ .cp = ':' } }); - try std.testing.expect(pane.tag_edit); + try std.testing.expect(pane.focus == .tag); try std.testing.expectEqual(Mode.normal, pane.body.mode); - p.update(.{ .key = .{ .cp = Key.escape } }); - try std.testing.expect(!pane.tag_edit); + p.update(.{ .key = .{ .cp = ':' } }); + try std.testing.expect(pane.focus == .body); p.update(.{ .key = .{ .cp = ' ' } }); try std.testing.expect(p.leader_on); p.update(.{ .key = .{ .cp = '!' } }); try std.testing.expect(!p.leader_on); p.update(.{ .key = .{ .cp = '/' } }); - try std.testing.expect(pane.prompt == .search and !pane.tag_edit); + try std.testing.expect(pane.prompt == .search and pane.focus == .body); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expect(pane.prompt == .none); } diff --git a/test/snapshots/cmdword.golden b/test/snapshots/cmdword.golden index e6f470fa..f099464f 100644 --- a/test/snapshots/cmdword.golden +++ b/test/snapshots/cmdword.golden @@ -16,9 +16,9 @@ == snap nested grid=120x31 cursor=4,24 |22: ls |23: cmds.txt p.txt zzmark.txt -== snap execword grid=120x31 cursor=69,17 +== snap execword grid=120x31 cursor=4,24 |17: /tmp/pardes-snap/cmdword/cwd Tty Save Mode Filter Collapse Del Exec -== snap tagcmd grid=120x31 cursor=83,17 +== snap tagcmd grid=120x31 cursor=4,24 |17: /tmp/pardes-snap/cmdword/cwd Tty Save Mode Filter Collapse Del Exec @`echo ZZ''T` |24: echo ZZ''T |25: ZZT diff --git a/test/snapshots/cmdword.snap b/test/snapshots/cmdword.snap index eb0e0ea6..361e37ba 100644 --- a/test/snapshots/cmdword.snap +++ b/test/snapshots/cmdword.snap @@ -57,25 +57,31 @@ wait 10000 zzmark.txt stable 700 15000 snap nested # the same syntax typed into a TAG — the other place the expansion has to know -# about backticks (tagChordText). The look above left the shell focused, so `:` -# opens ITS tag; `i` then End walks to the end of the tail, and the chord runs -# the word under the cursor exactly as the body's does. +# about backticks. The look above left the shell focused, so `:` opens ITS +# tag; `A` appends at the end of it, Esc and `h` put the normal-mode cursor on +# the last character typed, and the execute key runs the word under it +# exactly as the body's does. key : -key i -key end +key A key space text Exec -key left +key esc +settle 100 +key h key tab stable 700 8000 # ...except that word is `Exec` ITSELF, with nothing to execute. This is the # case that must not hang a re-entrant dispatcher: it runs out of argument -# immediately and does nothing at all. +# immediately and does nothing at all. Executing gave the keyboard back to the +# body, and `:` finds the tag's cursor where it was left. snap execword -key end +key : +key A key space text @`echo ZZ''T` -key left +key esc +settle 100 +key h key tab wait 10000 ZZT stable 700 15000 diff --git a/test/snapshots/collapse.golden b/test/snapshots/collapse.golden index 18d24d6b..eaf9bbc3 100644 --- a/test/snapshots/collapse.golden +++ b/test/snapshots/collapse.golden @@ -68,8 +68,8 @@ |3: |4: |5: -== 9p tab-collapsed-cursor grid=160x25 cursor=51,2,bar -== snap tab-restored grid=160x25 cursor=51,2 +== 9p tab-collapsed-cursor grid=160x25 cursor=none +== snap tab-restored grid=160x25 cursor=7,3 |3: 1 KEEP-FIRST Collapse |4: 2 KEEP-SECOND |5: 3 KEEP-THIRD diff --git a/test/snapshots/collapse.snap b/test/snapshots/collapse.snap index 64f6bdb8..83872855 100644 --- a/test/snapshots/collapse.snap +++ b/test/snapshots/collapse.snap @@ -1,5 +1,6 @@ # A default pane-tag command collapses to one row and restores the body. -# Exercise real middle clicks twice, then tag editing's Tab execution twice. +# Exercise real middle clicks twice, then the tag's own execute key twice: a +# click types into the tag, Esc is its normal mode, and Tab executes there. file kept.txt KEEP-FIRST\nKEEP-SECOND\nKEEP-THIRD start 25 160 kept.txt wait 8000 KEEP-THIRD @@ -19,12 +20,16 @@ stable 500 8000 snap middle-restored press left @Collapse 3 release left @Collapse 3 +key esc +settle 100 key tab stable 500 8000 snap tab-collapsed snap9p tab-collapsed-cursor press left @Collapse 3 release left @Collapse 3 +key esc +settle 100 key tab wait 8000 KEEP-THIRD stable 500 8000 diff --git a/test/snapshots/tag.snap b/test/snapshots/tag.snap index a545ff9f..4faf6062 100644 --- a/test/snapshots/tag.snap +++ b/test/snapshots/tag.snap @@ -1,7 +1,8 @@ -# a CLICKED tag is insert mode: type straight in (no 'i'; `:` is the normal- -# mode door, see tagcmd); backspace edits; Esc leaves back to the body; Enter -# looks the word at the cursor (Tab executes it). Multi-word execution from -# the tag stays the mouse's job (middle-drag), like anywhere else. +# a CLICKED tag is typed straight into (no 'i'; `:` is the normal-mode door, +# see tagcmd); backspace edits; Esc drops to the tag's normal mode, which is +# the body's normal mode, and `:` there hands the keyboard back to the body; +# Enter looks the word at the cursor (Tab executes it). Multi-word execution +# from the tag stays the mouse's job (middle-drag), like anywhere else. file t.txt ZZLOOKED start 31 150 -n 3 wait 8000 t.txt @@ -29,16 +30,21 @@ snap tag-del send .txt stable 600 8000 stable 400 5000 -# Esc: out of the tag, body back in normal mode, typed tail stays as text +# Esc: the tag's normal mode; `:` then gives the keyboard back to the body, +# which is in normal mode, and the typed text stays key esc settle 100 +key : stable 400 5000 snap tag-exit -# re-enter the tag and look the typed word: Enter opens t.txt as a file pane. -# Click the inserted word itself; filename, separator and commands are compact. +# re-enter the tag and look the typed word: Enter in normal mode opens t.txt +# as a file pane. Click the inserted word itself; filename, separator and +# commands are compact. press left @t.txt 3 release left @t.txt 3 stable 400 5000 +key esc +settle 100 key enter wait 10000 ZZLOOKED stable 700 15000 diff --git a/test/snapshots/tagalign.snap b/test/snapshots/tagalign.snap index 9df22f57..a77415d9 100644 --- a/test/snapshots/tagalign.snap +++ b/test/snapshots/tagalign.snap @@ -22,9 +22,14 @@ press left 12 3 release left 12 3 stable 400 5000 snap clicked -# End reveals the complete command suffix; a scrolled Del still executes. +# The click was on the path, so it drafted a name; Esc drops the draft. `:` +# then `A` puts the caret after the tag's end, which reveals the complete +# command suffix; a scrolled Del still executes. resize 31 70 -key end +key esc +settle 100 +key : +key A stable 400 5000 snap revealed press middle @Del 3 diff --git a/test/snapshots/tagcmd.snap b/test/snapshots/tagcmd.snap index 305ed521..0e9047fb 100644 --- a/test/snapshots/tagcmd.snap +++ b/test/snapshots/tagcmd.snap @@ -1,11 +1,12 @@ # `:` — vim's command line with acme's vocabulary. It focuses the pane's OWN # tag in NORMAL mode (block cursor; the layout box shows the pane's BODY mode, -# which for this file pane is normal either way), parked at the tail's -# START — always the start, so `:w` is the same two keystrokes every time. -# Motions walk the tag's words (w selects the "Save" span, exactly like a body -# word motion), the execute chord runs the one under the cursor and hands the -# body back in normal mode — same keys as the body, so Tab by default (see -# config.look_key/exec_key). Esc backs out instead, leaving the tail as it was. +# which for this file pane is normal either way). The tag remembers where its +# cursor was; the first time there is nothing to remember and it starts on +# Save. The tag's normal mode is the body's: w selects the "Save" span exactly +# as a body word motion does, and the execute key runs the word under the +# cursor and hands the body back — same keys as the body, so Tab by default +# (see config.look_key/exec_key). `:` again backs out instead, leaving the tag +# as it was. lines c.txt 6 start 31 100 c.txt wait 8000 Newcol Joincol @@ -18,7 +19,7 @@ key esc settle 100 stable 400 5000 snap edited -# `:` -> the tag, in normal mode, cursor on the tail's first cell +# `:` -> the tag, in normal mode, cursor on Save key : stable 400 5000 snap colon @@ -32,10 +33,9 @@ stable 600 8000 stable 400 5000 snap saved snapfile written /tmp/pardes-snap/tagcmd/cwd/c.txt -# `:` then Esc: back to the body with the tail untouched, nothing run +# `:` then `:`: back to the body with the tag untouched, nothing run key : stable 400 5000 -key esc -settle 100 +key : stable 400 5000 snap escaped diff --git a/test/snapshots/tagnav.golden b/test/snapshots/tagnav.golden index 52915940..3fdba9f2 100644 --- a/test/snapshots/tagnav.golden +++ b/test/snapshots/tagnav.golden @@ -22,39 +22,20 @@ == snap colon grid=100x31 cursor=28,2 |2: es-snap/tagnav/cwd/w.txt Save Tty Collapse Del /tmp/pardes-snap/tagnav/cwd Tty Save Mode Filte |18: ls -== snap right-tag grid=100x31 cursor=29,2 -== snap left-tag grid=100x31 cursor=28,2 -== snap down-tag grid=100x31 cursor=7,3 +== snap word grid=100x31 cursor=32,2 +== snap in-tag grid=100x31 cursor=34,2 +== snap right grid=100x31 cursor=54,5 |2: /tmp/pardes-snap/tagnav/cwd/w.txt Save Tty Coll /tmp/pardes-snap/tagnav/cwd Tty Save Mode Filte -== snap up-tag grid=100x31 cursor=7,3 -== snap column-tag grid=100x31 cursor=7,3 -== snap up-edge grid=100x31 cursor=7,3 -== snap topbar-word grid=100x31 cursor=11,3 -== snap topbar-graphemes grid=100x31 cursor=7,4 -== snap column-down grid=100x31 cursor=7,5 -== snap back-down grid=100x31 cursor=7,5 -== snap arrows-still-motion grid=100x31 cursor=9,5 -== snap back-to-body grid=100x31 cursor=4,20 -|3: 1 alpha Last ls +|3: 1 alpha Right ls +== snap right-tag grid=100x31 cursor=70,2 +|2: /tmp/pardes-snap/tagnav/cwd/w.txt Save Tty Coll p/tagnav/cwd Tty Save Mode Filter Collapse Del +|3: 1 alpha ls +== snap left-tag grid=100x31 cursor=43,2 +|2: /tmp/pardes-snap/tagnav/cwd/w.txt Save Tty Coll /tmp/pardes-snap/tagnav/cwd Tty Save Mode Filte +== snap back-to-body grid=100x31 cursor=7,3 == snap tty-on grid=100x31 cursor=54,5 |2: /tmp/pardes-snap/tagnav/cwd/w.txt Save Tty Coll$ /tmp/pardes-snap/tagnav/cwd Tty Save Mode Filte |3: 1 alpha $ ls |5: 3 gamma $ -== snap tty-tag grid=100x31 cursor=57,5 -|5: 3 gamma $ h:l -== snap tty-restored grid=100x31 cursor=4,20 -|3: 1 alpha $ ls Last -== snap topbar-dollar grid=100x31 cursor=48,17 -|3: 1 alpha $ ls -|17: p/tagnav/cwd Tty Save Mode Filter Collapse Del -== snap topbar-dump-word grid=100x31 cursor=25,17 -== snap topbar-exec grid=100x31 cursor=4,20 -|17: /tmp/pardes-snap/tagnav/cwd Tty Save Mode Filte -|29: /tmp/pardes-snap/tagnav/cwd/+Search Save Tty Co -|30: 1 -== snap topbar-restore-word grid=100x31 cursor=49,17 -|17: p/pardes-snap/tagnav/cwd Tty Save Mode Filter C -== snap topbar-restored grid=100x31 cursor=4,20 -|17: /tmp/pardes-snap/tagnav/cwd Tty Save Mode Filte -|27: /tmp/pardes-snap/tagnav/cwd/+Search Save Tty Co -|28: 1 +== snap tty-tag grid=100x31 cursor=90,2 +== snap tty-restored grid=100x31 cursor=54,5 diff --git a/test/snapshots/tagnav.snap b/test/snapshots/tagnav.snap index c375e644..eed808de 100644 --- a/test/snapshots/tagnav.snap +++ b/test/snapshots/tagnav.snap @@ -1,25 +1,22 @@ -# h/j/k/l ON A TAGLINE move focus BETWEEN taglines. A tag is a place in the -# LAYOUT, not just a line of text, so the four letters walk the layout and land -# on the neighbour's TAG (top row of the window), still in normal mode — you -# walk the taglines and never drop through a body. They run the SAME -# Left/Down/Up/Right builtins `SPC w h/j/k/l` and `Ctrl-w h/j/k/l` run: one -# focusDir, three routes to it. The ARROWS keep the in-tag grapheme motion, so -# no capability was traded away. +# A tag's normal mode is the body's: h/l/w move in the tag's own text, and +# moving between panes is the window keys' job from a tag as from a body -- +# there are no tag-only hops. `:` is the one key a tag and a body do not +# share: from the body it focuses the pane's own tag, from the tag it hands the +# keyboard back to the body. Each tag remembers its cursor; the first time +# there is nothing to remember and it starts on Save. # # Evidence is the `cursor=` header (the ACTIVE pane's cursor, which while a tag # is focused sits on THAT pane's tag row) plus each pane's layout box, which -# carries its BODY mode as one character: `•` normal, `^` insert, `$` tty. A -# tag edit parks the body mode rather than overwriting it, so the box keeps -# saying what the pane we left will be when we hop back off its tagline. +# carries its BODY mode as one character: ` ` normal, `^` insert, `$` tty. The +# tag has a mode of its own, so the box never changes while a tag is used. file w.txt alpha\nbeta\ngamma start 31 100 w.txt wait 8000 Newcol Joincol wait 8000 w.txt stable 700 20000 -# A FILE boots alone now, so the shell this script calls "the launch shell" is -# opened here: Alt-n opens it and focuses it, Alt-c puts it in a column of its -# own on the right, SPC w h comes back to the file. (`New`/`Newcol` open an -# empty +New scratch now, not a shell.) +# A FILE boots alone, so the launch shell is opened here: Alt-n opens it and +# focuses it, Alt-c puts it in a column of its own on the right, SPC w h comes +# back to the file. key a-n key a-c stable 700 15000 @@ -32,110 +29,51 @@ stable 700 15000 key space w k stable 400 5000 snap start -# `:` -> the file's OWN tagline, normal mode, parked at the tail's start +# `:` -> the file's OWN tagline, normal mode, on Save key : stable 400 5000 snap colon -# l -> right, onto the launch shell's TAGLINE (not its body) -key l -stable 400 5000 -snap right-tag -# h -> back left onto the file's tagline -key h -stable 400 5000 -snap left-tag -# j -> down onto the tagline of the shell under the file -key j -stable 400 5000 -snap down-tag -# k -> back up onto the file's -key k -stable 400 5000 -snap up-tag -# k visits the column tag first, then the workspace tag. Both stay in normal -# navigation mode; neither hop drops into a pane body. -key k -stable 400 5000 -snap column-tag -key k -stable 400 5000 -snap up-edge -# the bar speaks the tag's own one-line vocabulary: w to the next word start +# w selects in the tag the way it selects in a body key w stable 400 5000 -snap topbar-word -# h/l are plain graphemes up here — row 0 has no window to its left or right to -# walk to — and the arrows still mean what they always did -key l right +snap word +# l is a motion in the tag, not a hop to the next pane +key l l stable 400 5000 -snap topbar-graphemes -# j is the mirror of the k that got you here: back DOWN onto the topmost pane's -# tagline, still in normal mode, so the hop is a round trip -key j +snap in-tag +# the window keys move between panes from a tag as from a body: the tag lets +# go and the neighbour's BODY takes the keyboard +key c-w l +stable 400 5000 +snap right +# `:` there -> that pane's own tag, on its Save the first time +key : stable 400 5000 -snap column-down -key j +snap right-tag +# back left, and `:` finds the file's tag cursor where l left it +key c-w h stable 400 5000 -snap back-down -# the arrows are still in-tag motion: two rights walk two columns of the tail -key right right +key : stable 400 5000 -snap arrows-still-motion -key esc -settle 100 +snap left-tag +# `:` in the tag's normal mode: back to the body +key : stable 400 5000 snap back-to-body -# A TERMINAL MUST NOT LOSE ITS TTY MODE. Put the launch shell in raw tty mode -# (Ctrl-b), come back, then hop onto its tagline and off again: exitTagEdit -# restores the body mode the tag hijacked, and its box reads `$` throughout — -# during the hop too, because the box shows the PARKED mode, not the tag's. +# A TERMINAL KEEPS ITS TTY MODE. Put the launch shell in raw tty mode (Ctrl-b), +# click its tagline and come back: its box reads `$` throughout, because the +# tag's mode is the tag's own. key c-w l stable 400 5000 key c-b stable 700 15000 snap tty-on -key c-w h -stable 400 5000 -key : -key l +press left @Mode 3 +release left @Mode 3 stable 400 5000 snap tty-tag key esc settle 100 -stable 400 5000 -snap tty-restored -# Enter/Tab on the BAR runs the word under the cursor through the very dispatch -# a middle click on it uses, and leaves the bar FIRST — `Kill` lives up here, so -# a builtin that frees the session must never return into a focused topbar (the -# same hazard the pane-tag chord has with `Del`). `$` proves the destructive -# word is exactly last; four long-word steps back land on `Dump`, the visible -# non-destructive action used here. It grows a `Restore ` word, which is -# also the case where the line gets longer than the column you were parked on. -key c-w h -stable 400 5000 -key : -key k k -stable 400 5000 -key $ -stable 400 5000 -snap topbar-dollar -key B B B B -stable 400 5000 -snap topbar-dump-word -key enter -stable 700 15000 -snap topbar-exec -# THE DELETION HAZARD, from the bar itself: `Restore` frees every pane and -# swaps the core out from under the caller. Walk back onto the word the Dump -# just grew — B twice off the tail, because the LONG word motions are the ones -# that step over a path in one go — and run it. The bar drops focus BEFORE the -# builtin, so nothing reaches for state the swap already freed. key : -key k k stable 400 5000 -key $ B B -stable 400 5000 -snap topbar-restore-word -key enter -stable 900 15000 -snap topbar-restored +snap tty-restored diff --git a/test/snapshots/tagpath.golden b/test/snapshots/tagpath.golden index 1b798445..2ba1a2e6 100644 --- a/test/snapshots/tagpath.golden +++ b/test/snapshots/tagpath.golden @@ -8,12 +8,12 @@ | 4 line 4 | 5 == snap colon grid=100x31 cursor=38,2 -== snap col0 grid=100x31 cursor=3,2 -== snap sel-path grid=100x31 cursor=36,2 -== style sel-path grid=100x31 +== snap col0 grid=100x31 cursor=37,2 +== snap drag-cross grid=100x31 cursor=41,2 +== style drag-cross grid=100x31 |0: 0-70 #b2c3b8,#1d2824, 71-99 d,#1d2824, |1: 0-1 #ffffff,#887455, 2-2 d,#26362d, 3-34 #becfc4,#26362d, 35-99 d,#26362d, -|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-36 #f5f7ee,#3c614a, 37-58 #becfc4,#26362d, 59-99 d,#26362d, +|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-10 #becfc4,#26362d, 11-41 #f5f7ee,#3c614a, 42-58 #becfc4,#26362d, 59-99 d,#26362d, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-99 d,#0d1410, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-99 d,#0d1410, |5: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-99 d,#0d1410, @@ -42,16 +42,9 @@ |28: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, |29: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, |30: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-99 d,#0d1410, -== snap yanked-path grid=100x31 cursor=41,3 -|2: /tmp/pardes-snap/tagpath/cwd/c.txt * Save Tty Collapse Del -|3: 1 l/tmp/pardes-snap/tagpath/cwd/c.txtine 1 -== snap drag-cross grid=100x31 cursor=41,2 -== style drag-cross grid=100x31 -|2: 0-1 #000000,#add38a, 2-2 d,#26362d, 3-10 #becfc4,#26362d, 11-41 #f5f7ee,#3c614a, 42-60 #becfc4,#26362d, 61-99 d,#26362d, -|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-46 #e5eee5,#0d1410, 47-99 d,#0d1410, == snap name-draft grid=100x31 cursor=11,2 -|2: /renamed/tmp/pardes-snap/tagpath/cwd/c.txt * Save Tty Collapse Del -== snap name-cancelled grid=100x31 cursor=41,3 -|2: /tmp/pardes-snap/tagpath/cwd/c.txt * Save Tty Collapse Del -== snap name-committed grid=100x31 cursor=41,3 +|2: /renamed/tmp/pardes-snap/tagpath/cwd/c.txt Save Tty Collapse Del +== snap name-cancelled grid=100x31 cursor=7,3 +|2: /tmp/pardes-snap/tagpath/cwd/c.txt Save Tty Collapse Del +== snap name-committed grid=100x31 cursor=7,3 |2: /renamed/tmp/pardes-snap/tagpath/cwd/c.txt * Save Tty Collapse Del diff --git a/test/snapshots/tagpath.snap b/test/snapshots/tagpath.snap index cf431fa1..b9ef80e6 100644 --- a/test/snapshots/tagpath.snap +++ b/test/snapshots/tagpath.snap @@ -1,5 +1,8 @@ -# Filename drafts share the selectable tag coordinate space with commands. -# Escape cancels; Enter changes buffer identity, never renames a disk file. +# The path is part of the tag's text for the mouse -- a sweep selects across +# the path and the commands after it -- but never for the keyboard: the tag's +# cursor lives in its own text, so `0` goes to the start of that, not of the +# path. A click on the path drafts a new name there instead. Escape cancels; +# Enter changes buffer identity, never renames a disk file. lines c.txt 4 start 31 100 c.txt wait 8000 Newcol Joincol @@ -12,16 +15,6 @@ snap colon key 0 stable 400 5000 snap col0 -key E -stable 400 5000 -snap sel-path -snapstyle sel-path -key y -key esc -settle 100 -key p -stable 400 5000 -snap yanked-path # Sweep across the path / command boundary without injected padding. press left 12 3 drag left 30 3 @@ -33,17 +26,18 @@ snapstyle drag-cross key esc settle 100 key : -key 0 -key i +stable 400 5000 +# a click on the path is a name draft, the caret where it was clicked +press left 4 3 +release left 4 3 text /renamed stable 400 5000 snap name-draft key esc stable 400 5000 snap name-cancelled -key : -key 0 -key i +press left 4 3 +release left 4 3 text /renamed key enter stable 400 5000 diff --git a/test/snapshots/ttyclick.golden b/test/snapshots/ttyclick.golden index 719e3955..14344371 100644 --- a/test/snapshots/ttyclick.golden +++ b/test/snapshots/ttyclick.golden @@ -20,11 +20,7 @@ | ls | probe.txt == snap tty-tagedit grid=100x31 cursor=33,2 -|3: ls ls -|5: == snap tty-tagexit grid=100x31 cursor=4,5 -|3: $ ls ls -|5: $ == snap ins-bodyclick grid=100x31 cursor=11,4 |2: ^ /tmp/pardes-snap/ttyclick/cwd Tty Save Mode Fil /tmp/pardes-snap/ttyclick/cwd Tty Save Mode Fil |3: ls ls diff --git a/test/snapshots/ttyclick.snap b/test/snapshots/ttyclick.snap index 89ed5300..c125a231 100644 --- a/test/snapshots/ttyclick.snap +++ b/test/snapshots/ttyclick.snap @@ -1,7 +1,7 @@ # clicks in a shell pane never change its mode: a body click in raw tty -# keeps tty (before: the press dropped it to normal), a tag-edit round trip -# restores the mode it hijacked, and an insert-mode body click re-pins the -# cursor but stays insert. File panes keep the old behavior (click -> normal). +# keeps tty (before: the press dropped it to normal), a round trip through the +# tag leaves it alone (the tag has a mode of its own), and an insert-mode body +# click re-pins the cursor but stays insert. File panes keep the old behavior (click -> normal). # The mode is the character in each pane's layout box: `•` normal, `^` insert, # `$` tty. file probe.txt marker @@ -15,14 +15,16 @@ press left 10 5 release left 10 5 stable 400 5000 snap tty-bodyclick -# tag edit from tty: the box still reads `$` while the tag is being edited (the -# body mode is PARKED, which is the invariant), and Esc hands it back — a bug -# that lost it would show `•` in one snap or the other +# tag edit from tty: the box still reads `$` while the tag is typed into (the +# tag's mode is its own), and Esc then `:` hands the keyboard back — a bug +# that lost the body's mode would show `•` in one snap or the other press left @Tty 3 release left @Tty 3 stable 400 5000 snap tty-tagedit key esc +settle 100 +key : stable 400 5000 snap tty-tagexit # out of tty, into insert: a body click moves the cursor but keeps INS -- cgit v1.3 From 42748f92b77367db415c8b4d0f2e537a9e1ddde7 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 00:13:11 -0300 Subject: Make the column and workspace tags Texts with the pane tag's keys The headers had their own one-line editor with its own keys: Enter always executed, h/l and J/K moved between headers and panes, Ctrl-c/x/v cut and pasted, and TagLine refused a newline that 9P accepted. They are now Texts like a pane's tag, with no prefix and a default until edited, so normal and insert mode, undo and the look and execute keys are the body's. Moving between them is the window keys' job: Up from a pane with nothing above it reaches its column's tag and then the workspace's, Down comes back, and Left and Right walk the column tags. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 1 + src/Text.zig | 19 +- src/builtins.zig | 37 +++- src/config.zig | 9 - src/dump.zig | 12 +- src/edit.zig | 45 +++-- src/gui/gui.zig | 5 +- src/layout.zig | 29 +-- src/mouse.zig | 44 ++-- src/normal.zig | 23 ++- src/pardes.zig | 471 ++++++++++++++++++------------------------- src/tag_line.zig | 42 ---- test/column_drag.zig | 22 +- test/panes.zig | 12 +- test/snapshots/tagnav.golden | 24 +++ test/snapshots/tagnav.snap | 43 ++++ 16 files changed, 426 insertions(+), 412 deletions(-) delete mode 100644 src/tag_line.zig (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index 2bf9f57d..22e3c434 100644 --- a/src/File.zig +++ b/src/File.zig @@ -654,6 +654,7 @@ pub fn cursorLines(arena: std.mem.Allocator, pane: *Pane, f: *State) ![]const [] /// Use the file's line index only when `text` is its complete live content. /// Edit-buffer fragments and other temporary text retain modal's scan path. fn contentIndex(t: *Text, text: []const u8) ?[]const usize { + if (t.what != .body) return null; const pane = t.pane(); const f = if (pane.file) |*file| file else return null; if (text.ptr != f.content.ptr or text.len != f.content.len) return null; diff --git a/src/Text.zig b/src/Text.zig index 3e48a42e..d4b6d048 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -1,7 +1,8 @@ //! One editable text, acme's Text (editors/acme/dat.h:171-190, text.c): the //! cursor, the selections and the modal state that edit it, and the undo of -//! an edit buffer. A pane's body is one, its tag is another, and so is the -//! answer typed into a pane's prompt. Where a body's characters come from -- +//! an edit buffer. A pane's body is one, its tag is another, and so are the +//! answer typed into a pane's prompt and the tags of the columns and the +//! workspace. Where a body's characters come from -- //! a file's content, a terminal's edit overlay, a PDF's text -- is the //! window's business (edit.zig's editText and flatSurface), the way acme's //! Text reads its File; every other text owns its characters. Everything @@ -19,7 +20,7 @@ pub const Mode = enum { normal, insert, tty }; /// Which text of its window this is, acme's `what`. It says where the /// characters live and whether moving the cursor scrolls a body. -pub const What = enum { body, tag, input }; +pub const What = enum { body, tag, input, column, workspace }; /// A modal line selection (helix `x`): whole rows [r0, r1], absolute. pub const LineSel = struct { @@ -74,15 +75,25 @@ ed_undo_len: usize = 0, ed_redo: [Terminal.history_max]Terminal.Snapshot = undefined, ed_redo_len: usize = 0, -/// The window this text belongs to (acme's t->w). +/// The window this text belongs to (acme's t->w). A column's or the +/// workspace's tag belongs to no pane; nothing asks it for one. pub fn pane(t: *Text) *Pane { return switch (t.what) { .body => @alignCast(@fieldParentPtr("body", t)), .tag => @alignCast(@fieldParentPtr("tag", t)), .input => @alignCast(@fieldParentPtr("input", t)), + .column, .workspace => unreachable, }; } +/// Free what a text owns: its characters and the buffers its undo keeps. +pub fn deinit(t: *Text, gpa: std.mem.Allocator) void { + if (t.own) |own| gpa.free(own); + for (t.ed_undo[0..t.ed_undo_len]) |item| if (item.ovl) |overlay| gpa.free(overlay.text); + for (t.ed_redo[0..t.ed_redo_len]) |item| if (item.ovl) |overlay| gpa.free(overlay.text); + t.* = .{ .what = t.what }; +} + /// Bring the cursor into view (acme's textshow). Only a body scrolls to it; /// the tagline follows its caret where it is drawn, and a prompt's answer is /// drawn whole. diff --git a/src/builtins.zig b/src/builtins.zig index 743573e4..74645376 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -735,27 +735,56 @@ pub const Grep = struct { // ---- the window group ---- +// The headers are above the panes in the same layout: Up from a pane with +// nothing above it reaches its column's tag, then the workspace's, and Down +// comes back the same way. Left and Right walk the column tags. + pub const Left = struct { pub fn run(c: Ctx) void { - layout.focusDir(c.p, c.id, .left); + if (c.p.header_focus) { + if (c.p.header_column) |column| if (column > 0) c.p.enterHeader(column - 1); + return; + } + _ = layout.focusDir(c.p, c.id, .left); } }; pub const Down = struct { pub fn run(c: Ctx) void { - layout.focusDir(c.p, c.id, .down); + if (c.p.header_focus) { + const column = layout.findPane(c.p, c.id); + if (c.p.header_column == null and c.p.columnBarHeight() > 0) + return c.p.enterHeader(if (column) |at| at.col else 0); + // Onto the top pane of the column the header stands over. + const col = c.p.header_column orelse if (column) |at| at.col else return; + c.p.exitHeader(); + if (col < c.p.ncol and c.p.col_n[col] > 0) c.p.active = c.p.col_panes[col][0]; + return; + } + _ = layout.focusDir(c.p, c.id, .down); } }; pub const Up = struct { pub fn run(c: Ctx) void { - layout.focusDir(c.p, c.id, .up); + if (c.p.header_focus) { + if (c.p.header_column != null and c.p.topBarHeight() > 0) c.p.enterHeader(null); + return; + } + if (layout.focusDir(c.p, c.id, .up)) return; + if (c.p.columnBarHeight() > 0) { + if (layout.findPane(c.p, c.id)) |at| c.p.enterHeader(at.col); + } else if (c.p.topBarHeight() > 0) c.p.enterHeader(null); } }; pub const Right = struct { pub fn run(c: Ctx) void { - layout.focusDir(c.p, c.id, .right); + if (c.p.header_focus) { + if (c.p.header_column) |column| if (column + 1 < c.p.ncol) c.p.enterHeader(column + 1); + return; + } + _ = layout.focusDir(c.p, c.id, .right); } }; diff --git a/src/config.zig b/src/config.zig index 38b87011..8c37a7ce 100644 --- a/src/config.zig +++ b/src/config.zig @@ -215,11 +215,6 @@ pub const jump_keys = [_]struct { chord: Chord, cmd: Builtin }{ .{ .chord = .{ .cp = 'i', .ctrl = true }, .cmd = .Forward }, }; -pub const topbar_down: []const Chord = &.{ .{ .cp = 'J' }, .{ .cp = Key.down } }; -pub const topbar_up: []const Chord = &.{ .{ .cp = 'K' }, .{ .cp = Key.up } }; -pub const topbar_left: []const Chord = &.{.{ .cp = 'h' }}; -pub const topbar_right: []const Chord = &.{.{ .cp = 'l' }}; - pub const leave_pane: []const Chord = &.{.{ .cp = Key.escape, .shift = true }}; pub const tty_toggle_default: u21 = 'b'; @@ -255,8 +250,6 @@ pub const tag_insert = "^"; pub const tag_tty = "$"; pub const tag_image = "img"; -pub const tag_yank: []const Chord = &.{.{ .cp = 'y' }}; - pub const command_line: []const Chord = &.{.{ .cp = ':' }}; pub const search: []const Chord = &.{.{ .cp = '/' }}; @@ -458,8 +451,6 @@ pub const line_end: []const Chord = &.{ .{ .cp = '$' }, .{ .cp = Key.end } }; pub const line_first_nonws: []const Chord = &.{.{ .cp = '^' }}; // Bare G does nothing; ge reaches the last line. pub const goto_line: []const Chord = &.{.{ .cp = 'G' }}; -pub const line_move_left: []const Chord = move_left; -pub const line_move_right: []const Chord = move_right; pub const half_page_down: []const Chord = &.{.{ .cp = 'd', .ctrl = true }}; pub const half_page_up: []const Chord = &.{.{ .cp = 'u', .ctrl = true }}; diff --git a/src/dump.zig b/src/dump.zig index 7112e1f0..aeb25a90 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -191,8 +191,10 @@ pub const State = struct { mounts: []const Mount = &.{}, }; +/// A header is a text like any other: it may hold newlines, but not a +/// carriage return or a NUL. fn validateTag(bar: []const u8) !void { - if (bar.len > limits.max_tag_tail or std.mem.indexOfAny(u8, bar, "\r\n\x00") != null or !std.unicode.utf8ValidateSlice(bar)) return error.BadDumpTag; + if (bar.len > limits.max_tag_tail or std.mem.indexOfAny(u8, bar, "\r\x00") != null or !std.unicode.utf8ValidateSlice(bar)) return error.BadDumpTag; } pub fn validate(state: State) !void { @@ -637,7 +639,7 @@ pub fn dumpState(p: *Pardes) !void { }; if (ids_len > 0) { columns[columns_len] = .{ - .tag = if (p.col_tags[c].custom) p.columnTag(c) else null, + .tag = p.col_tags[c].own, .weight = @as(f32, @floatFromInt(p.col_weight[c])) / @as(f32, @floatFromInt(column_weight_unit)), .panes = column_ids[c][0..ids_len], }; @@ -651,7 +653,7 @@ pub fn dumpState(p: *Pardes) !void { .screen = .{ .cols = p.screen_w, .rows = p.screen_h }, .active = slot_to_pane[p.active] orelse 0, .topbar = config.topbar_str, - .topbar_custom = if (p.global_tag.custom) p.global_tag.slice("") else null, + .topbar_custom = p.global_tag.own, .theme = p.theme().name, .locations_config = p.locations_config, .tree_context_tag_style = p.settings.tree_context_tag_style, @@ -788,9 +790,9 @@ fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previo } p.ncol = @min(st.columns.len, MAX_COLS); p.col_serial = @splat(0); - if (st.topbar_custom) |bar| _ = p.global_tag.set(bar); + if (st.topbar_custom) |bar| p.global_tag.own = try p.gpa.dupe(u8, bar); for (st.columns[0..p.ncol], 0..) |col, c| { - if (col.tag) |bar| _ = p.col_tags[c].set(bar); + if (col.tag) |bar| p.col_tags[c].own = try p.gpa.dupe(u8, bar); const scaled = @as(f64, @floatCast(col.weight)) * @as(f64, @floatFromInt(column_weight_unit)); const bounded = @min(scaled, @as(f64, @floatFromInt(max_column_weight))); p.col_weight[c] = @max(1, @as(u64, @intFromFloat(@round(bounded)))); diff --git a/src/edit.zig b/src/edit.zig index 02e138e8..1822db31 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -72,10 +72,9 @@ pub fn typeToTty(p: *Pardes, id: usize, pane: *const Pane, text: []const u8) voi } pub fn applyPaste(p: *Pardes, bytes: []const u8) void { - if (p.topbar_col != null) { + if (p.focusedHeader()) |t| { p.clip_pending = null; - p.headerReplace(bytes); - return; + return pasteInto(p, t, bytes); } const req = p.clip_pending; p.clip_pending = null; @@ -96,15 +95,23 @@ pub fn applyPaste(p: *Pardes, bytes: []const u8) void { if (normal.selRegexArmed(pane)) |a| normal.applySelRegex(p, pane, a.pat, a.split); return; } - const t = if (pane.focus == .tag) &pane.tag else &pane.body; - if (t.what == .body and pane.isTerminal() and pane.body.mode == .tty) return typeToTty(p, id, pane, bytes); + if (pane.focus == .tag) return pasteInto(p, &pane.tag, bytes); + if (pane.isTerminal() and pane.body.mode == .tty) return typeToTty(p, id, pane, bytes); switch (if (req) |r| r.mode else .after) { - .after => pasteText(p, t, bytes, false, 1), - .before => pasteText(p, t, bytes, true, 1), - .replace => replaceWithText(p, t, bytes), + .after => pasteText(p, &pane.body, bytes, false, 1), + .before => pasteText(p, &pane.body, bytes, true, 1), + .replace => replaceWithText(p, &pane.body, bytes), } } +/// A paste into a tag or a header: typed at the caret while it is typed +/// into, after the cursor's cell in normal mode, as a body's paste is. +fn pasteInto(p: *Pardes, t: *Text, bytes: []const u8) void { + if (bytes.len == 0) return; + if (t.mode == .insert) return insertKey(p, t, .{ .cp = bytes[0], .text = bytes }); + pasteText(p, t, bytes, false, 1); +} + pub fn clipYank(p: *Pardes, pane: *Pane, main_only: bool) void { if (comptime pdf_enabled) if (pane.pdf) |pv| { if (pv.selection_text.len > 0) setClipboard(p, pv.selection_text); @@ -340,8 +347,12 @@ pub fn pinPaneCursor(p: *Pardes, t: *Text) void { } pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { - if (t.what == .tag) return Pardes.curTail(t.pane()); - if (t.what != .body) return t.own orelse ""; + switch (t.what) { + .body => {}, + .tag => return Pardes.curTail(t.pane()), + .input => return t.own orelse "", + .column, .workspace => return t.own orelse p.headerDefault(t.what), + } const pane = t.pane(); if (pane.file) |f| return f.content; if (pane.hasPdf()) { @@ -362,10 +373,10 @@ pub fn paneWrapWidth(p: *const Pardes, t: *Text) usize { /// Route shared edit operations to the characters `t` edits: its own, or /// for a body its file's content or its terminal's overlay. fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText { - // A tag nobody has changed shows its default; the first edit makes that - // default its own text. - if (t.what == .tag and t.own == null) - t.own = p.gpa.dupe(u8, Pardes.defaultTail(t.pane())) catch return null; + // A tag or header nobody has changed shows its default; the first edit + // makes that default its own text. + if (t.what != .body and t.what != .input and t.own == null) + t.own = p.gpa.dupe(u8, flatSurface(p, t) catch return null) catch return null; if (t.what != .body) return .{ .text = t.own orelse &.{}, .row0 = 0 }; const pane = t.pane(); if (pane.file) |f| return .{ .text = f.content, .row0 = 0 }; @@ -1545,7 +1556,7 @@ pub fn pushUndo(p: *Pardes, t: *Text) void { if (p.multi_on and !p.multi_first) return; switch (t.what) { .body => {}, - .tag => return t.remember(p.gpa, if (t.own) |own| .{ .text = own } else null), + .tag, .column, .workspace => return t.remember(p.gpa, if (t.own) |own| .{ .text = own } else null), // a prompt's answer is typed once and gone; it keeps no history .input => return, } @@ -1555,7 +1566,7 @@ pub fn pushUndo(p: *Pardes, t: *Text) void { } pub fn doUndo(p: *Pardes, t: *Text) void { - if (t.what == .tag) return stepOwn(p, t, true); + if (t.what == .tag or t.what == .column or t.what == .workspace) return stepOwn(p, t, true); if (t.what != .body) return; const pane = t.pane(); if (pane.file != null) return panes.File.undo(p, pane); @@ -1563,7 +1574,7 @@ pub fn doUndo(p: *Pardes, t: *Text) void { } pub fn doRedo(p: *Pardes, t: *Text) void { - if (t.what == .tag) return stepOwn(p, t, false); + if (t.what == .tag or t.what == .column or t.what == .workspace) return stepOwn(p, t, false); if (t.what != .body) return; const pane = t.pane(); if (pane.file != null) return panes.File.redo(p, pane); diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 97bbc816..dfd528a3 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -7360,7 +7360,7 @@ fn appendWorkspacePet(g: *Gui, core: ?*const pardes.Pardes, surface: *const pard for (surface.cells[0..surface.cols], 0..) |*cell, i| { if (cellCodepoint(cell) != ' ') occupied = i + 1; } - const editing = p.topbar_col != null and p.header_column == null; + const editing = p.header_focus and p.header_column == null; const band_top: f32 = @floatFromInt(taglineBandOffset(0, builder.win_h, g.cell_h, g.tagline_height)); const region = if (occupied >= surface.cols) null else pet.lane( occupied, @@ -7412,8 +7412,7 @@ test "pet overlay stays beyond workspace text and vanishes while its tag is edit try std.testing.expect(x >= 20 * 8 - 0.01); try std.testing.expect(y >= 0 and y < 20); } - core.topbar_col = 0; - core.header_column = null; + core.enterHeader(null); builder.len = 0; appendWorkspacePet(&g, core, &surface, &builder); try std.testing.expectEqual(@as(usize, 0), builder.len); diff --git a/src/layout.zig b/src/layout.zig index 49da0207..54b89081 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -674,7 +674,8 @@ pub const MovePlacement = struct { above_h: u16, }; -pub fn focusDir(p: *Pardes, from: usize, dir: enum { left, right, up, down }) void { +/// Move the keyboard to the nearest pane in `dir`; false when there is none. +pub fn focusDir(p: *Pardes, from: usize, dir: enum { left, right, up, down }) bool { const a = p.rects[from]; var best: ?usize = null; var best_d: i32 = 0; @@ -701,11 +702,11 @@ pub fn focusDir(p: *Pardes, from: usize, dir: enum { left, right, up, down }) vo best_d = d; } } - if (best) |b| { - p.active = b; - // a count typed before the hop was meant for the pane you left - p.panes[b].?.body.normal.clear(); - } + const b = best orelse return false; + p.active = b; + // a count typed before the hop was meant for the pane you left + p.panes[b].?.body.normal.clear(); + return true; } pub fn columnBySerial(p: *const Pardes, serial: u32) ?usize { @@ -935,6 +936,7 @@ pub fn removePane(p: *Pardes, id: usize) void { if (p.col_n[c] == 0) { p.exitHeader(); if (p.ncol > 1) p.col_weight[if (c > 0) c - 1 else c + 1] +|= p.col_weight[c]; + p.col_tags[c].deinit(p.gpa); var j = c; while (j + 1 < p.ncol) : (j += 1) { p.col_panes[j] = p.col_panes[j + 1]; @@ -944,7 +946,7 @@ pub fn removePane(p: *Pardes, id: usize) void { p.col_serial[j] = p.col_serial[j + 1]; } p.ncol -= 1; - p.col_tags[p.ncol] = .{}; + p.col_tags[p.ncol] = .{ .what = .column }; p.col_serial[p.ncol] = 0; } } @@ -958,6 +960,7 @@ pub fn joinCol(p: *Pardes) void { p.col_weight[dst] +|= p.col_weight[c]; for (0..p.col_n[c]) |k| p.col_panes[dst][p.col_n[dst] + k] = p.col_panes[c][k]; p.col_n[dst] += p.col_n[c]; + p.col_tags[c].deinit(p.gpa); var j = c; while (j + 1 < p.ncol) : (j += 1) { p.col_panes[j] = p.col_panes[j + 1]; @@ -967,7 +970,7 @@ pub fn joinCol(p: *Pardes) void { p.col_serial[j] = p.col_serial[j + 1]; } p.ncol -= 1; - p.col_tags[p.ncol] = .{}; + p.col_tags[p.ncol] = .{ .what = .column }; p.col_serial[p.ncol] = 0; } @@ -1017,7 +1020,7 @@ pub fn splitColumn(p: *Pardes, source_id: usize, id: usize, before: bool) bool { p.col_serial[j] = p.col_serial[j - 1]; } p.col_weight[c] = new_weight; - p.col_tags[c] = .{}; + p.col_tags[c] = .{ .what = .column }; p.col_serial[c] = 0; p.col_panes[c][0] = id; p.col_n[c] = 1; @@ -2245,25 +2248,25 @@ test "column reorder moves only crossed state and preserves weights" { p.col_weight[c] = c * 13 + 7; p.col_serial[c] = @intCast(c + 10); p.col_panes[c][0] = c; - p.col_tags[c].saved_col = @intCast(c + 20); + p.col_tags[c].cur_col = @intCast(c + 20); } compute(p); const original_weights = p.col_weight; const outer_x = p.col_x[0]; const outer_w = p.col_w[0]; + p.header_focus = true; p.header_column = 1; - p.topbar_col = 23; p.header_scroll = 9; reorderColumn(p, 1, 3); try std.testing.expectEqual(original_weights[1], p.col_weight[3]); try std.testing.expectEqual(original_weights[2], p.col_weight[1]); try std.testing.expectEqual(@as(u32, 11), p.col_serial[3]); try std.testing.expectEqual(@as(?usize, 3), p.header_column); - try std.testing.expectEqual(@as(?u16, 23), p.topbar_col); + try std.testing.expectEqual(@as(i32, 21), p.focusedHeader().?.cur_col); try std.testing.expectEqual(@as(usize, 9), p.header_scroll); try std.testing.expectEqual(outer_x, p.col_x[0]); try std.testing.expectEqual(outer_w, p.col_w[0]); reorderColumn(p, 3, 1); try std.testing.expectEqualSlices(u64, original_weights[0..4], p.col_weight[0..4]); - try std.testing.expectEqual(@as(?u16, 21), p.col_tags[1].saved_col); + try std.testing.expectEqual(@as(i32, 21), p.col_tags[1].cur_col); } diff --git a/src/mouse.zig b/src/mouse.zig index ae047c58..343051b0 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -292,9 +292,17 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { } } if (p.header_drag and m.button == config.select_button and (m.kind == .drag or m.kind == .release)) { + const t = p.focusedHeader() orelse { + p.header_drag = false; + return; + }; const x = if (p.header_column) |c| p.col_x[c] + TAG_TEXT_INSET else 0; - const bar = p.headerText(); - p.topbar_col = @intCast(@min(bar.len, panes.File.rawAtDisplay(bar, (tagColumn(p, if (p.header_column != null) .column else .workspace, p.header_column orelse 0, p.pointer_tag_hit, p.header_drag) orelse (mcol -| x)) + p.header_scroll))); + const bar = modal.lineSlice(edit.flatSurface(p, t) catch return, 0); + const at = @min(bar.len, panes.File.rawAtDisplay(bar, (tagColumn(p, if (p.header_column != null) .column else .workspace, p.header_column orelse 0, p.pointer_tag_hit, p.header_drag) orelse (mcol -| x)) + p.header_scroll)); + // the anchor stays where the press put it + t.cur_row = 0; + t.cur_col = @intCast(at); + t.vsel.active = t.vsel.col != t.cur_col; if (m.kind == .release) p.header_drag = false; return; } @@ -318,25 +326,25 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { }; if (column == null or mcol < x) return; } - if (p.header_column != column) { - p.rememberHeader(); - p.topbar_col = null; - p.header_anchor = null; - p.header_scroll = 0; - } - p.header_column = column; - const bar = p.headerText(); - const at = @min(bar.len, panes.File.rawAtDisplay(bar, (tagColumn(p, if (p.header_column != null) .column else .workspace, p.header_column orelse 0, p.pointer_tag_hit, p.header_drag) orelse (mcol -| x)) + p.header_scroll)); + const t = if (column) |c| &p.col_tags[c] else &p.global_tag; + const focused = p.header_focus and p.header_column == column; + const bar = modal.lineSlice(edit.flatSurface(p, t) catch return, 0); + const scroll = if (focused) p.header_scroll else 0; + const at = @min(bar.len, panes.File.rawAtDisplay(bar, (tagColumn(p, if (column != null) .column else .workspace, column orelse 0, p.pointer_tag_hit, p.header_drag) orelse (mcol -| x)) + scroll)); if (m.button == config.select_button) { - p.topbar_col = @intCast(at); - p.header_anchor = @intCast(at); - p.header_insert = true; + // A clicked header is typed straight into, as a clicked tag is. + if (!focused) p.enterHeader(column); + t.mode = .insert; + t.cur_row = 0; + t.cur_col = @intCast(at); + t.vsel = .{ .active = false, .row = 0, .col = @intCast(at) }; p.header_drag = true; } else { - const selected = if (p.topbar_col) |cur| blk: { - const a = p.header_anchor orelse cur; - break :blk if (at >= @min(a, cur) and at < @max(a, cur)) bar[@min(a, cur)..@max(a, cur)] else wordAtCol(bar, at); - } else wordAtCol(bar, at); + const span = if (focused) Pardes.headerSelection(t, bar) else null; + const selected = if (span) |sp| + (if (at >= sp.lo and at < sp.hi) bar[sp.lo..sp.hi] else wordAtCol(bar, at)) + else + wordAtCol(bar, at); const word = p.scratch.allocator().dupe(u8, selected) catch return; p.exitHeader(); if (word.len > 0) { diff --git a/src/normal.zig b/src/normal.zig index e4fa075d..630f7689 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -173,7 +173,9 @@ const Replay = union(enum) { pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { const id = p.active; - const serial = t.pane().serial; + // a header belongs to no pane and cannot go away under the replay + const owner: ?*Pane = if (t.what == .column or t.what == .workspace) null else t.pane(); + const serial = if (owner) |pane| pane.serial else 0; // the whole selection in text coordinates, document order. t.sels // is already ordered, so this only slots the primary into place. var list: [Text.max_selections]Text.SelRange = undefined; @@ -256,8 +258,11 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { p.multi_first = false; if (p.multi_stop) { p.multi_stop = false; - const pn = p.panes[id] orelse return; - if (pn.serial == serial) t.nsel = 0; + if (owner != null) { + const pn = p.panes[id] orelse return; + if (pn.serial != serial) return; + } + t.nsel = 0; return; } const text = edit.flatSurface(p, t) catch return; @@ -284,7 +289,9 @@ pub fn handleNormal(p: *Pardes, t: *Text, key: Key) void { } fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void { - const pane = t.pane(); + // What reaches past the text -- a builtin, a search, a language query -- + // acts for the pane the text belongs to; a header's is the active one. + const pane = if (t.what == .column or t.what == .workspace) p.panes[p.active] orelse return else t.pane(); const raw_selection = t.what == .body and pane.rawPointerText(pane.sel[sel_slot]) != null; const before = .{ t.cur_row, t.cur_col, t.vsel, t.msel, t.select, t.nsel, t.mode }; defer if (raw_selection and !std.meta.eql(before, .{ t.cur_row, t.cur_col, t.vsel, t.msel, t.select, t.nsel, t.mode })) { @@ -547,9 +554,11 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void }, // `:` is the one key a tag and a body do not share: it moves the // keyboard between them. - .command_line => if (t.what == .tag) { - pane.focus = .body; - } else p.enterTag(pane), + .command_line => switch (t.what) { + .tag => pane.focus = .body, + .column, .workspace => p.exitHeader(), + .body, .input => p.enterTag(pane), + }, .pipe_selection => |how| return p.startPrompt(pane, .{ .pipe = how }), .search => return p.startPrompt(pane, .{ .search = config.search_marker }), .search_step => |direction| return look.lookWalk( diff --git a/src/pardes.zig b/src/pardes.zig index ce7c7065..60c41f50 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -258,7 +258,6 @@ const max_column_weight = layout.max_column_weight; pub const MAX_JUMPS = 64; pub const TOPBAR_H: u16 = 1; pub const COLBAR_H: u16 = 1; -pub const TagLine = @import("tag_line.zig").Line; pub const BOX_H: u16 = 1; pub const TAG_GAP: u16 = 1; pub const TAG_TEXT_INSET: u16 = config.GUTTER + TAG_GAP; @@ -2702,17 +2701,19 @@ test "tabbed file aligns syntax cursor and mouse at the nearest insertion gap" { try std.testing.expect(look.expandedSel(p, pane, .{ .state = .dragging, .c0 = separator, .c1 = separator, .r0 = BOX_H, .r1 = BOX_H }) == null); } -test "editable workspace and column tags replace selections and persist" { +test "editable workspace and column tags are typed into and persist" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 20, .tty_only = true }); defer p.deinit(); _ = try p.setTestFile("untouched\n"); p.acknowledgePanelPresentation(&.{}); try std.testing.expectEqual(TOPBAR_H + COLBAR_H, p.rects[0].y); + // a sweep over a header is its selection, the caret where it ended p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = 0, .row = 0 } }); p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = 6, .row = 0 } }); p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = 6, .row = 0 } }); - p.update(.{ .key = .{ .cp = 'H', .text = "Help" } }); - try std.testing.expect(std.mem.startsWith(u8, p.global_tag.slice(""), "Help Joincol")); + try std.testing.expect(p.global_tag.vsel.active and p.global_tag.vsel.col == 0 and p.global_tag.cur_col == 6); + p.update(.{ .key = .{ .cp = 'H', .text = " Help" } }); + try std.testing.expect(std.mem.startsWith(u8, p.global_tag.own.?, "Newcol Help Joincol")); p.update(.{ .key = .{ .cp = Key.escape } }); p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = TAG_TEXT_INSET, .row = TOPBAR_H } }); p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = TAG_TEXT_INSET, .row = TOPBAR_H } }); @@ -2726,9 +2727,10 @@ test "editable workspace and column tags replace selections and persist" { try dump.dumpState(p); const restored = try dump.restore(p, p.dump_out.?); defer restored.deinit(); - try std.testing.expectEqualStrings(p.global_tag.slice(""), restored.global_tag.slice("")); + try std.testing.expectEqualStrings(p.global_tag.own.?, restored.global_tag.own.?); try std.testing.expectEqualStrings(p.columnTag(0), restored.columnTag(0)); - try std.testing.expect(p.col_tags[0].set("")); + p.gpa.free(p.col_tags[0].own.?); + p.col_tags[0].own = try p.gpa.dupe(u8, ""); try dump.dumpState(p); const empty = try dump.restore(p, p.dump_out.?); defer empty.deinit(); @@ -2739,11 +2741,11 @@ test "column tags follow their column through split and close" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 20, .tty_only = true }); defer p.deinit(); _ = try p.setTestFile("left\n"); - try std.testing.expect(p.col_tags[0].set("Left Find")); + p.col_tags[0].own = try p.gpa.dupe(u8, "Left Find"); _ = exec.execute(p, 0, "Newcol"); try std.testing.expectEqual(@as(usize, 2), p.ncol); try std.testing.expectEqualStrings("Left Find", p.columnTag(0)); - try std.testing.expect(p.col_tags[1].set("Right Grep")); + p.col_tags[1].own = try p.gpa.dupe(u8, "Right Grep"); p.active = p.col_panes[0][0]; layout.joinCol(p); try std.testing.expectEqual(@as(usize, 1), p.ncol); @@ -2770,7 +2772,7 @@ test "column tags render edit hover and scroll from the column edge" { try std.testing.expectEqual(Color{ .rgb = p.theme().sel_bg }, hovered.at(x, TOPBAR_H).style.bg); p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = x, .row = TOPBAR_H } }); try std.testing.expectEqual(column, p.header_column.?); - try std.testing.expectEqual(@as(u16, 0), p.topbar_col.?); + try std.testing.expectEqual(@as(i32, 0), p.focusedHeader().?.cur_col); const at_start = try p.render(frame.allocator()); try std.testing.expectEqual(x, at_start.cursor.?.x); p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = x + 3, .row = TOPBAR_H } }); @@ -2778,13 +2780,15 @@ test "column tags render edit hover and scroll from the column edge" { const selected = try p.render(frame.allocator()); for (0..3) |offset| try std.testing.expectEqual(Color{ .rgb = p.theme().sel_bg }, selected.at(x + @as(u16, @intCast(offset)), TOPBAR_H).style.bg); - p.update(.{ .key = .{ .cp = 'H', .text = "Help" } }); - try std.testing.expect(std.mem.startsWith(u8, p.columnTag(column), "Help Tty")); + p.update(.{ .key = .{ .cp = Key.home } }); + p.update(.{ .key = .{ .cp = 'H', .text = "Help " } }); + try std.testing.expect(std.mem.startsWith(u8, p.columnTag(column), "Help New Tty")); const edited = try p.render(frame.allocator()); - try std.testing.expectEqual(x + 4, edited.cursor.?.x); + try std.testing.expectEqual(x + 5, edited.cursor.?.x); // Only the text viewport participates in caret reveal. const long: [80]u8 = @splat('a'); - try std.testing.expect(p.col_tags[column].set(long[0 .. width - 1])); + if (p.col_tags[column].own) |own| p.gpa.free(own); + p.col_tags[column].own = try p.gpa.dupe(u8, long[0 .. width - 1]); p.update(.{ .key = .{ .cp = Key.end } }); const at_end = try p.render(frame.allocator()); try std.testing.expectEqual(@as(usize, 0), p.header_scroll); @@ -2827,7 +2831,7 @@ test "header clicks beyond text append and long UTF-8 tags reveal their caret" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 50, .rows = 12, .tty_only = true }); defer p.deinit(); _ = try p.setTestFile("body\n"); - try std.testing.expect(p.col_tags[0].set("New")); + p.col_tags[0].own = try p.gpa.dupe(u8, "New"); p.acknowledgePanelPresentation(&.{}); p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = 40, .row = TOPBAR_H } }); p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = 40, .row = TOPBAR_H } }); @@ -2856,21 +2860,21 @@ test "ColumnTags reclaims the row and releases hidden header focus without losin const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12, .tty_only = true }); defer p.deinit(); const pane = try p.setTestFile("unchanged body\n"); - try std.testing.expect(p.col_tags[0].set("New Help")); + p.col_tags[0].own = try p.gpa.dupe(u8, "New Help"); p.acknowledgePanelPresentation(&.{}); const shown = p.rects[0]; try std.testing.expectEqual(TOPBAR_H + COLBAR_H, shown.y); p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = TAG_TEXT_INSET, .row = TOPBAR_H } }); p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = TAG_TEXT_INSET, .row = TOPBAR_H } }); - try std.testing.expect(p.header_column != null and p.topbar_col != null); + try std.testing.expect(p.header_focus and p.header_column != null); p.update(.{ .command = "ColumnTags" }); try std.testing.expect(!p.settings.column_tags); try std.testing.expectEqual(@as(u16, 0), p.columnBarHeight()); try std.testing.expectEqual(TOPBAR_H, p.rects[0].y); try std.testing.expectEqual(shown.h + COLBAR_H, p.rects[0].h); - try std.testing.expect(p.header_column == null and p.topbar_col == null); - try std.testing.expect(p.header_anchor == null and !p.header_drag); + try std.testing.expect(!p.header_focus and p.header_column == null); + try std.testing.expect(!p.header_drag); try std.testing.expectEqualStrings("New Help", p.columnTag(0)); p.update(.{ .command = "ColumnTags" }); @@ -2884,25 +2888,63 @@ test "ColumnTags reclaims the row and releases hidden header focus without losin try std.testing.expect(p.settings.column_tags); try std.testing.expectEqual(@as(u16, 0), p.columnBarHeight()); try std.testing.expectEqual(TOPBAR_H, p.rects[0].y); - try std.testing.expect(p.header_column == null and p.topbar_col == null); + try std.testing.expect(!p.header_focus and p.header_column == null); p.update(.{ .resize = .{ .cols = 60, .rows = 12 } }); try std.testing.expectEqual(shown, p.rects[0]); try std.testing.expectEqualStrings("New Help", p.columnTag(0)); try std.testing.expectEqualStrings("unchanged body\n", pane.file.?.content); } -test "normal header Enter executes its command rather than searching for it" { +test "a header's execute key runs the word under its cursor and lets go of the keyboard first" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 12, .tty_only = true }); defer p.deinit(); _ = try p.setTestFile("body\n"); - p.topbar_col = @intCast(std.mem.indexOf(u8, config.topbar_str, "Dump").?); - p.header_insert = false; - p.update(.{ .key = .{ .cp = Key.enter } }); - try std.testing.expect(p.topbar_col == null); + p.enterHeader(null); + p.global_tag.cur_col = @intCast(std.mem.indexOf(u8, config.topbar_str, "Dump").?); + p.update(.{ .key = .{ .cp = Key.tab } }); + try std.testing.expect(!p.header_focus); try std.testing.expect(p.dump_out != null); try std.testing.expectEqual(@as(usize, 1), p.col_n[0]); } +test "window keys walk from a pane up through the column and workspace tags and back" { + const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 20, .tty_only = true }); + defer p.deinit(); + _ = try p.setTestFile("body\n"); + p.newScratchColumn(0); + p.sync(); + p.active = p.col_panes[0][0]; + const window = struct { + fn key(core: *Pardes, letter: u21) void { + core.update(.{ .key = .{ .cp = 'w', .ctrl = true } }); + core.update(.{ .key = .{ .cp = letter } }); + } + }; + // Up from the top pane: its column's tag, in normal mode; `:` there is + // the way back to the body. + window.key(p, 'k'); + try std.testing.expect(p.header_focus and p.header_column.? == 0); + try std.testing.expectEqual(Text.Mode.normal, p.col_tags[0].mode); + p.update(.{ .key = .{ .cp = 'w' } }); + try std.testing.expect(p.col_tags[0].cur_col > 0); + const remembered = p.col_tags[0].cur_col; + window.key(p, 'l'); + try std.testing.expect(p.header_focus and p.header_column.? == 1); + window.key(p, 'h'); + try std.testing.expectEqual(remembered, p.col_tags[0].cur_col); + window.key(p, 'k'); + try std.testing.expect(p.header_focus and p.header_column == null); + window.key(p, 'j'); + try std.testing.expect(p.header_focus and p.header_column.? == 0); + window.key(p, 'j'); + try std.testing.expect(!p.header_focus); + try std.testing.expectEqual(p.col_panes[0][0], p.active); + window.key(p, 'k'); + p.update(.{ .key = .{ .cp = ':' } }); + try std.testing.expect(!p.header_focus and p.panes[p.active].?.focus == .body); + try std.testing.expectEqualStrings("body\n", p.panes[0].?.file.?.content); +} + pub const Mouse = struct { /// The host has inverted a compact body layer. Physical col/row still /// route pane chrome; these coordinates address the pane's logical text. @@ -3656,10 +3698,12 @@ pub const Pardes = struct { col_weight: [MAX_COLS]u64 = @splat(column_weight_unit), col_panes: [MAX_COLS][MAX_PANES]usize = undefined, col_n: [MAX_COLS]usize = @splat(0), - col_tags: [MAX_COLS]TagLine = @splat(.{}), + /// Each column's tag and the workspace's: Texts like a pane's tag, with + /// no prefix, showing a default until someone edits them. + col_tags: [MAX_COLS]Text = @splat(.{ .what = .column }), col_serial: [MAX_COLS]u32 = @splat(0), next_column_serial: u32 = 1, - global_tag: TagLine = .{}, + global_tag: Text = .{ .what = .workspace }, // derived each sync rects: [MAX_PANES]Rect = @splat(.{}), col_x: [MAX_COLS]u16 = undefined, @@ -3716,10 +3760,11 @@ pub const Pardes = struct { leader_on: bool = false, leader_keys: [4]u8 = undefined, leader_n: u8 = 0, - topbar_col: ?u16 = null, + /// The keyboard is on a header: the column tag `header_column` names, or + /// the workspace's when that is null. + header_focus: bool = false, header_column: ?usize = null, - header_insert: bool = false, - header_anchor: ?u16 = null, + /// A mouse sweep is extending the focused header's selection. header_drag: bool = false, header_scroll: usize = 0, ov_pinch_scale: f32 = 1.0, @@ -3951,6 +3996,8 @@ pub const Pardes = struct { slot.* = null; }; const gpa = p.gpa; + for (&p.col_tags) |*t| t.deinit(gpa); + p.global_tag.deinit(gpa); if (p.yank) |y| gpa.free(y); if (p.dump_out) |d| gpa.free(d); p.fallback.deinit(); @@ -3994,13 +4041,21 @@ pub const Pardes = struct { return a; } - /// the topbar line: the fixed builtins, plus `Restore ` once a dump - /// exists — render and click dispatch must agree on this exact string - fn topbar(p: *Pardes, buf: []u8) []const u8 { - if (p.global_tag.custom) return p.global_tag.slice(""); - if (p.last_dump) |d| - return std.fmt.bufPrint(buf, config.topbar_str ++ " Restore {s}", .{d}) catch config.topbar_str; - return config.topbar_str; + /// What a column's tag says until someone edits it. + pub const column_tag_default = "New Tty Find Grep Joincol Delcol"; + + /// What a header says until someone edits it: for the workspace the + /// fixed builtins, plus `Restore ` once a dump exists. + pub fn headerDefault(p: *Pardes, what: Text.What) []const u8 { + if (what == .column) return column_tag_default; + const d = p.last_dump orelse return config.topbar_str; + return std.fmt.allocPrint(p.scratch.allocator(), config.topbar_str ++ " Restore {s}", .{d}) catch config.topbar_str; + } + + /// the topbar line -- render and click dispatch must agree on this exact + /// string + fn topbar(p: *Pardes) []const u8 { + return p.global_tag.own orelse p.headerDefault(.workspace); } /// The workspace tag row's height: `TOPBAR_H` while the setting keeps @@ -4016,43 +4071,32 @@ pub const Pardes = struct { } pub fn columnTag(p: *const Pardes, c: usize) []const u8 { - return p.col_tags[c].slice("New Tty Find Grep Joincol Delcol"); + return p.col_tags[c].own orelse column_tag_default; } - pub fn headerText(p: *Pardes) []const u8 { - if (p.header_column) |c| return if (c < p.ncol) p.columnTag(c) else ""; - var buf: [1200]u8 = undefined; - return p.scratch.allocator().dupe(u8, p.topbar(&buf)) catch ""; + /// The header with the keyboard, when one has it. + pub fn focusedHeader(p: *Pardes) ?*Text { + if (!p.header_focus) return null; + if (p.header_column) |c| return if (c < p.ncol) &p.col_tags[c] else null; + return &p.global_tag; } fn revealHeader(p: *Pardes) void { - const cur = p.topbar_col orelse { + const t = p.focusedHeader() orelse { p.header_scroll = 0; return; }; - const text = p.headerText(); + const text = edit.flatSurface(p, t) catch return; + const line = modal.lineSlice(text, 0); const width = p.tagCapacity(if (p.header_column) |c| p.col_w[c] -| TAG_TEXT_INSET else p.screen_w); - const col = panes.File.rawDisplayCol(text, @min(cur, text.len)); + const col = panes.File.rawDisplayCol(line, @min(@as(usize, @intCast(@max(0, t.cur_col))), line.len)); if (col < p.header_scroll) p.header_scroll = col; if (col >= p.header_scroll + width) p.header_scroll = col -| (width -| 1); - var raw = panes.File.rawAtDisplay(text, p.header_scroll); - p.header_scroll = panes.File.rawDisplayCol(text, raw); + var raw = panes.File.rawAtDisplay(line, p.header_scroll); + p.header_scroll = panes.File.rawDisplayCol(line, raw); if (width > 0 and col >= p.header_scroll + width) { - raw = modal.nextGrapheme(text, raw); - p.header_scroll = panes.File.rawDisplayCol(text, raw); - } - } - - pub fn headerReplace(p: *Pardes, bytes: []const u8) void { - const cur = p.topbar_col orelse return; - const anchor = p.header_anchor orelse cur; - const lo = @min(cur, anchor); - const hi = @max(cur, anchor); - const fallback = p.headerText(); - const line = if (p.header_column) |c| &p.col_tags[c] else &p.global_tag; - if (line.replace(fallback, lo, hi, bytes)) { - p.topbar_col = @intCast(lo + bytes.len); - p.header_anchor = null; + raw = modal.nextGrapheme(line, raw); + p.header_scroll = panes.File.rawDisplayCol(line, raw); } } @@ -4109,9 +4153,7 @@ pub const Pardes = struct { if (pane.file) |*file| panes.File.deinit(p, pane, file); if (pane.ovl) |o| p.gpa.free(o.text); if (pane.input.own) |text| p.gpa.free(text); - if (pane.tag.own) |text| p.gpa.free(text); - for (pane.tag.ed_undo[0..pane.tag.ed_undo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); - for (pane.tag.ed_redo[0..pane.tag.ed_redo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); + pane.tag.deinit(p.gpa); for (pane.body.ed_undo[0..pane.body.ed_undo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); for (pane.body.ed_redo[0..pane.body.ed_redo_len]) |sn| if (sn.ovl) |o| p.gpa.free(o.text); panes.Terminal.deinitEmulator(pane, p.gpa); @@ -4921,165 +4963,34 @@ pub const Pardes = struct { return true; } - fn lineMotion(text: []const u8, cur: usize, key: Key) ?modal.Selection { - const target: ?usize = if (hit(key, config.line_move_left)) - modal.prevGrapheme(text, cur) - else if (hit(key, config.line_move_right)) - modal.nextGrapheme(text, cur) - else if (hit(key, config.line_start)) - 0 - else if (hit(key, config.line_end)) - modal.prevGrapheme(text, text.len) - else if (hit(key, config.line_first_nonws)) - modal.firstNonWs(text) - else - null; - if (target) |t| return .{ .anchor = t, .head = t }; - const wt: ?modal.WordTarget = if (hit(key, config.next_word_start)) - .next_word_start - else if (hit(key, config.prev_word_start)) - .prev_word_start - else if (hit(key, config.next_word_end)) - .next_word_end - else if (hit(key, config.next_long_word_start)) - .next_long_word_start - else if (hit(key, config.prev_long_word_start)) - .prev_long_word_start - else if (hit(key, config.next_long_word_end)) - .next_long_word_end - else - null; - const t = wt orelse return null; - return modal.moveWord(text, .{ .anchor = cur, .head = modal.nextGrapheme(text, cur) }, 1, t); - } - - pub fn rememberHeader(p: *Pardes) void { - const col = p.topbar_col orelse return; - const line = if (p.header_column) |c| &p.col_tags[c] else &p.global_tag; - line.saved_col = col; - } - pub fn exitHeader(p: *Pardes) void { - p.rememberHeader(); - p.topbar_col = null; + p.header_focus = false; p.header_column = null; - p.header_anchor = null; p.header_drag = false; p.header_scroll = 0; } - fn enterHeader(p: *Pardes, column: ?usize) void { - p.rememberHeader(); + /// Give the keyboard to a column's tag, or the workspace's for null, in + /// normal mode, its cursor where that header last had it. + pub fn enterHeader(p: *Pardes, column: ?usize) void { + p.exitHeader(); + if (p.panes[p.active]) |pane| pane.focus = .body; + p.header_focus = true; p.header_column = column; - const line = if (column) |c| &p.col_tags[c] else &p.global_tag; - const text = p.headerText(); - p.topbar_col = @intCast(modal.graphemeStart(text, @min(line.saved_col orelse 0, text.len))); - p.header_insert = false; - p.header_anchor = null; - p.header_drag = false; - p.header_scroll = 0; - } - - fn topbarKey(p: *Pardes, key: Key) void { - const bar = p.headerText(); - // the line GROWS a `Restore ` word the moment a dump lands, so - // the column is clamped against the live line on every use - const cur: usize = @min(@as(usize, p.topbar_col orelse return), bar.len); - if (hit(key, config.escape) or (!p.header_insert and hit(key, &.{.{ .cp = 'j' }}))) { - p.exitHeader(); - return; - } - if (hit(key, config.look_key) or hit(key, config.exec_key)) { - const a = p.header_anchor orelse @as(u16, @intCast(cur)); - const word = if (a != cur) bar[@min(a, cur)..@max(a, cur)] else wordAtCol(bar, cur); - p.exitHeader(); - if (word.len > 0) { - if (!p.header_insert) { - // Preserve the workspace tag's keyboard command semantics. - _ = exec.execute(p, p.active, word); - } else exec.runBuiltin(p, if (hit(key, config.look_key)) config.look_cmd else config.exec_cmd, p.active, "", word); - } - return; - } - if (p.header_insert) { - if (key.ctrl and key.cp == 'v') { - p.emit(.read_clipboard); - return; - } - if (key.ctrl and (key.cp == 'c' or key.cp == 'x')) { - const anchor = p.header_anchor orelse @as(u16, @intCast(cur)); - if (anchor != cur) { - edit.setClipboard(p, bar[@min(anchor, cur)..@max(anchor, cur)]); - if (key.cp == 'x') p.headerReplace(""); - } - return; - } - if (key.text.len > 0 and !key.ctrl and !key.alt) { - p.headerReplace(key.text); - return; - } - if (key.cp == Key.backspace or key.cp == Key.delete) { - if (p.header_anchor == null or p.header_anchor.? == cur) p.header_anchor = @intCast(if (key.cp == Key.backspace) modal.prevGrapheme(bar, cur) else modal.nextGrapheme(bar, cur)); - p.headerReplace(""); - return; - } - const next: ?usize = switch (key.cp) { - Key.left => modal.prevGrapheme(bar, cur), - Key.right => modal.nextGrapheme(bar, cur), - Key.home => 0, - Key.end => bar.len, - else => null, - }; - if (next) |at| { - if (key.shift) { - if (p.header_anchor == null) p.header_anchor = @intCast(cur); - } else p.header_anchor = null; - p.topbar_col = @intCast(at); - } - return; - } - if (hit(key, config.insert) or hit(key, config.append) or hit(key, config.insert_line_start) or hit(key, config.insert_line_end)) { - p.header_insert = true; - p.topbar_col = @intCast(if (hit(key, config.insert_line_end)) bar.len else if (hit(key, config.insert_line_start)) 0 else if (hit(key, config.append)) modal.nextGrapheme(bar, cur) else cur); - return; - } - if (hit(key, config.topbar_down)) { - if (p.header_column == null and p.columnBarHeight() > 0) { - p.enterHeader(if (layout.findPane(p, p.active)) |f| f.col else 0); - return; - } - var dest: ?usize = null; - for (p.panes, 0..) |slot, i| { - if (slot == null or p.rects[i].y != p.topBarHeight() + p.columnBarHeight()) continue; - if (p.header_column) |c| if (p.rects[i].x != p.col_x[c]) continue; - if (i == p.active) { - dest = i; - break; - } - if (dest == null or p.rects[i].x < p.rects[dest.?].x) dest = i; - } - const d = dest orelse return; - const pane = p.panes[d].?; - p.exitHeader(); - p.active = d; - p.enterTag(pane); - return; - } - if (hit(key, config.topbar_up)) { - p.enterHeader(null); - return; - } - const col: ?usize = if (hit(key, config.topbar_left)) - modal.prevGrapheme(bar, cur) - else if (hit(key, config.topbar_right)) - modal.nextGrapheme(bar, cur) - else if (lineMotion(bar, cur, key)) |r| - modal.selectionCursor(bar, r) - else - null; - // never past the last cell: there is nothing to append up here, so the - // block cursor stays ON a character (which is where `$` already lands) - if (col) |c| p.topbar_col = @intCast(@min(c, modal.prevGrapheme(bar, bar.len))); + const t = p.focusedHeader() orelse return p.exitHeader(); + const text = edit.flatSurface(p, t) catch ""; + const rows = modal.cursorLineCount(text); + t.cur_row = @intCast(@min(@as(usize, @intCast(@max(0, t.cur_row))), rows - 1)); + const line = modal.lineSlice(text, @intCast(t.cur_row)); + t.cur_col = @intCast(modal.graphemeStart(line, @min(line.len, @as(usize, @intCast(@max(0, t.cur_col)))))); + t.cur_pinned = true; + t.vsel.active = false; + t.msel.active = false; + t.nsel = 0; + t.select = false; + t.append_at = null; + t.mode = .normal; + t.normal.clear(); } /// Cycle only the body modes supported by this pane. @@ -5129,9 +5040,9 @@ pub const Pardes = struct { if (hit(key, config.del_below)) exec.runBuiltin(p, .Del, id, "", "j"); return; } - if (p.topbar_col != null) return p.topbarKey(key); const pane = p.panes[p.active] orelse return; - if (pane.isTerminal() and pane.body.mode == .tty and pane.focus == .body and pane.prompt == .none) { + const header = p.focusedHeader(); + if (header == null and pane.isTerminal() and pane.body.mode == .tty and pane.focus == .body and pane.prompt == .none) { p.leader_on = false; p.ctrl_w_pending = false; if (key.ctrl and !key.alt and key.cp == p.opts.tty_toggle) @@ -5169,14 +5080,15 @@ pub const Pardes = struct { } // insert mode owns Ctrl-w (delete word backward, helix); the focus // prefix applies outside raw tty mode - const t = if (pane.focus == .tag) &pane.tag else &pane.body; - if (hit(key, config.window_prefix) and t.mode != .insert and pane.prompt == .none) { + const t = header orelse if (pane.focus == .tag) &pane.tag else &pane.body; + if (hit(key, config.window_prefix) and t.mode != .insert and (header != null or pane.prompt == .none)) { p.ctrl_w_pending = true; return; } // global window ops (any mode): Alt-n new terminal below, Alt-c move // the active terminal into a fresh column if (hit(key, config.new_shell_below)) { + p.exitHeader(); const free = p.freeSlot() orelse return; const nt = p.newShell(free, "") catch return; nt.greet = true; @@ -5189,9 +5101,12 @@ pub const Pardes = struct { return; } for (config.jump_keys) |jk| { - if (hit(key, &.{jk.chord})) return exec.runBuiltin(p, jk.cmd, p.active, "", null); + if (!hit(key, &.{jk.chord})) continue; + p.exitHeader(); + return exec.runBuiltin(p, jk.cmd, p.active, "", null); } if (hit(key, config.pane_to_new_column)) { + p.exitHeader(); const f = layout.findPane(p, p.active).?; if (p.ncol < MAX_COLS and p.col_n[f.col] > 1) { _ = layout.splitColumn(p, p.active, p.active, false); @@ -5203,7 +5118,7 @@ pub const Pardes = struct { if (pane.isTerminal() and tty_toggle) { return p.toggleTty(p.active); } - if (pane.prompt == .name) { + if (header == null and pane.prompt == .name) { // Enter or the execute key commits the draft and the keyboard // goes back to the body; Esc drops it. if (hit(key, config.look_key) or hit(key, config.exec_key)) { @@ -5218,7 +5133,7 @@ pub const Pardes = struct { edit.handleInsert(p, &pane.input, key); return; } - if (pane.prompt != .none) { + if (header == null and pane.prompt != .none) { if (hit(key, config.search_submit) or hit(key, config.escape)) { const submit = hit(key, config.search_submit); switch (pane.prompt) { @@ -5241,22 +5156,24 @@ pub const Pardes = struct { } if (t.mode == .normal and (hit(key, config.look_key) or hit(key, config.exec_key))) { const cmd = if (hit(key, config.look_key)) config.look_cmd else config.exec_cmd; - if (pane.focus == .tag) { + if (t.what != .body) { // An explicit selection, else the word under the cursor in the - // tag as it is shown: the prefix is part of what a word is. - const tag = p.tagText(p.scratch.allocator(), pane) catch return; - const tail = curTail(pane); - const range = t.primaryRange(tail, 0); + // text as it is shown: a tag's prefix is part of what a word is. + const arena = p.scratch.allocator(); + const own = arena.dupe(u8, edit.flatSurface(p, t) catch return) catch return; + const shown = if (t.what == .tag) p.tagText(arena, pane) catch return else own; + const range = t.primaryRange(own, 0); const lo = @min(range.anchor, range.head); const hi = @max(range.anchor, range.head); const txt = if ((t.vsel.active and t.vsel.explicit) or t.msel.active) - tail[lo..hi] + own[lo..hi] else word: { - const b = config.wordBounds(tag, tag.len - tail.len + modal.selectionCursor(tail, range)); - break :word tag[b.lo..b.hi]; + const b = config.wordBounds(shown, shown.len - own.len + modal.selectionCursor(own, range)); + break :word shown[b.lo..b.hi]; }; - // Out of the tag FIRST: Del frees the pane. - pane.focus = .body; + // Out of the tag or header FIRST: Del frees the pane, Kill + // and Restore the whole session. + if (header != null) p.exitHeader() else pane.focus = .body; if (txt.len > 0) exec.runBuiltin(p, cmd, p.active, "", txt); return; } @@ -5899,7 +5816,7 @@ pub const Pardes = struct { const pane = slot.* orelse continue; // The keyboard is on one pane, or on a header: a tag it has left // hands it back to its body, and a name drafted there is dropped. - if (id != p.active or p.topbar_col != null) { + if (id != p.active or p.header_focus) { pane.focus = .body; if (pane.prompt == .name) pane.closePrompt(); } @@ -6134,9 +6051,8 @@ pub const Pardes = struct { // global tagbar: full width, top row — unless a native shell has // taken its commands over, in which case the row is not ours to draw p.revealHeader(); - var tb_buf: [1200]u8 = undefined; - const global_bar = p.topbar(&tb_buf); - const global_scroll = if (p.topbar_col != null and p.header_column == null) p.header_scroll else 0; + const global_bar = modal.lineSlice(p.topbar(), 0); + const global_scroll = if (p.header_focus and p.header_column == null) p.header_scroll else 0; if (p.settings.workspace_tag) { s.fill(0, 0, s.cols, TOPBAR_H, .{ .bg = .{ .rgb = chrome.tag_bg }, @@ -6149,7 +6065,7 @@ pub const Pardes = struct { }); } if (p.pointer_inside and p.hover_row < p.topBarHeight()) { - const bar = p.topbar(&tb_buf); + const bar = global_bar; if (wordBoundsAtCol(bar, panes.File.rawAtDisplay(bar, p.hover_col + global_scroll))) |bounds| { var col = panes.File.rawDisplayCol(bar, bounds.lo) -| global_scroll; const hi = panes.File.rawDisplayCol(bar, bounds.hi) -| global_scroll; @@ -6161,10 +6077,6 @@ pub const Pardes = struct { } } } - if (p.topbar_col) |c| if (p.header_column == null) { - const col = panes.File.rawDisplayCol(p.topbar(&tb_buf), c) -| global_scroll; - if (col < s.cols) s.cursor = .{ .x = @intCast(col), .y = 0, .bar = p.header_insert }; - }; if (p.columnBarHeight() > 0) for (0..p.ncol) |c| { const grip = @min(config.GUTTER, p.col_w[c]); const inset = @min(TAG_TEXT_INSET, p.col_w[c]); @@ -6185,8 +6097,8 @@ pub const Pardes = struct { s.fill(p.col_x[c] + grip, p.topBarHeight(), inset - grip, 1, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); s.fill(x, p.topBarHeight(), w, 1, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); - const bar_scroll = if (p.topbar_col != null and p.header_column == c) p.header_scroll else 0; - const tag = p.columnTag(c); + const bar_scroll = if (p.header_focus and p.header_column == c) p.header_scroll else 0; + const tag = modal.lineSlice(p.columnTag(c), 0); _ = s.print(x, p.topBarHeight(), w, tag[panes.File.rawAtDisplay(tag, bar_scroll)..], .{ .fg = .{ .rgb = fg }, .bg = .{ .rgb = bg }, @@ -6194,7 +6106,7 @@ pub const Pardes = struct { }); // A carried column's pointer is aiming at a place, not a word. if (p.pointer_inside and p.drag != .column_move and p.hover_row == p.topBarHeight() and p.hover_col >= x and p.hover_col < x + w) { - const bar = p.columnTag(c); + const bar = tag; if (wordBoundsAtCol(bar, panes.File.rawAtDisplay(bar, p.hover_col - x + bar_scroll))) |bounds| { var col = panes.File.rawDisplayCol(bar, bounds.lo) -| bar_scroll; const hi = panes.File.rawDisplayCol(bar, bounds.hi) -| bar_scroll; @@ -6206,21 +6118,24 @@ pub const Pardes = struct { } } }; - if (p.topbar_col) |cur| { - const bar = p.headerText(); + if (p.focusedHeader()) |t| { + const bar = modal.lineSlice(try edit.flatSurface(p, t), 0); const x = if (p.header_column) |c| p.col_x[c] + TAG_TEXT_INSET else 0; const w = if (p.header_column) |c| p.col_w[c] -| TAG_TEXT_INSET else s.cols; const y: u16 = if (p.header_column != null) p.topBarHeight() else 0; - const anchor = p.header_anchor orelse cur; - var col = panes.File.rawDisplayCol(bar, @min(cur, anchor)) -| p.header_scroll; - const hi = panes.File.rawDisplayCol(bar, @max(cur, anchor)) -| p.header_scroll; - while (col < hi and col < w) : (col += 1) { - const cell = s.at(x + @as(u16, @intCast(col)), y); - cell.style.fg = .{ .rgb = th.sel_fg }; - cell.style.bg = .{ .rgb = th.sel_bg }; + if (headerSelection(t, bar)) |span| { + var col = panes.File.rawDisplayCol(bar, span.lo) -| p.header_scroll; + const hi = panes.File.rawDisplayCol(bar, span.hi) -| p.header_scroll; + while (col < hi and col < w) : (col += 1) { + const cell = s.at(x + @as(u16, @intCast(col)), y); + cell.style.fg = .{ .rgb = th.sel_fg }; + cell.style.bg = .{ .rgb = th.sel_bg }; + } + } + if (t.cur_row == 0) { + const caret = panes.File.rawDisplayCol(bar, @min(@as(usize, @intCast(@max(0, t.cur_col))), bar.len)) -| p.header_scroll; + if (caret < w) s.cursor = .{ .x = x + @as(u16, @intCast(caret)), .y = y, .bar = t.mode == .insert }; } - const caret = panes.File.rawDisplayCol(bar, @min(cur, bar.len)) -| p.header_scroll; - if (caret < w) s.cursor = .{ .x = x + @as(u16, @intCast(caret)), .y = y, .bar = p.header_insert }; } try p.renderTagLayers(arena); @@ -6489,13 +6404,12 @@ pub const Pardes = struct { layer.viewport = .{ .x = r.x + TAG_TEXT_INSET, .y = if (p.settings.tag_bottom) r.y + r.h - BOX_H else r.y, .w = r.w - TAG_TEXT_INSET, .h = BOX_H }; layer.cols = columns; layer.bg = if (id == p.active and p.settings.focus_tint) chrome.tag_active_bg else chrome.tag_bg; - layer.cursor = if (p.topbar_col == null and temporary.cursor != null) .{ .col = temporary.cursor.?.x - TAG_TEXT_INSET, .bar = temporary.cursor.?.bar } else null; + layer.cursor = if (!p.header_focus and temporary.cursor != null) .{ .col = temporary.cursor.?.x - TAG_TEXT_INSET, .bar = temporary.cursor.?.bar } else null; } - var text_buf: [1200]u8 = undefined; // With the workspace tag row handed to native chrome there is no // workspace layer to render; the menu bar carries its commands. if (p.settings.workspace_tag) - try p.renderHeaderLayer(arena, MAX_PANES + MAX_COLS, .workspace, 0, .{ .x = 0, .y = 0, .w = p.screen_w, .h = TOPBAR_H }, p.topbar(&text_buf), chrome.tag_bg, chrome.tag_fg); + try p.renderHeaderLayer(arena, MAX_PANES + MAX_COLS, .workspace, 0, .{ .x = 0, .y = 0, .w = p.screen_w, .h = TOPBAR_H }, modal.lineSlice(p.topbar(), 0), chrome.tag_bg, chrome.tag_fg); // Each notice is its own tagline-shaped chip over the top of the body. // Going through the same layer machinery the pane and column tags use // is what gives it the tagline's height, its small-font metrics, the @@ -6558,10 +6472,21 @@ pub const Pardes = struct { if (p.columnBarHeight() > 0) for (0..p.ncol) |column| { if (p.col_w[column] == 0) continue; const active = if (layout.findPane(p, p.active)) |found| found.col == column and p.settings.focus_tint else false; - try p.renderHeaderLayer(arena, MAX_PANES + column, .column, @intCast(column), .{ .x = p.col_x[column] + @min(TAG_TEXT_INSET, p.col_w[column]), .y = p.topBarHeight(), .w = p.col_w[column] -| TAG_TEXT_INSET, .h = COLBAR_H }, p.columnTag(column), if (active) chrome.tag_active_bg else chrome.tag_bg, if (active) chrome.tag_active_fg else chrome.tag_fg); + try p.renderHeaderLayer(arena, MAX_PANES + column, .column, @intCast(column), .{ .x = p.col_x[column] + @min(TAG_TEXT_INSET, p.col_w[column]), .y = p.topBarHeight(), .w = p.col_w[column] -| TAG_TEXT_INSET, .h = COLBAR_H }, modal.lineSlice(p.columnTag(column), 0), if (active) chrome.tag_active_bg else chrome.tag_bg, if (active) chrome.tag_active_fg else chrome.tag_fg); }; } + /// The span a header's selection covers on its first line: up to the + /// caret while typing, and over the cursor's own cell in normal mode, + /// where a cursor is a cell. + pub fn headerSelection(t: *const Text, line: []const u8) ?struct { lo: usize, hi: usize } { + if (!t.vsel.active or t.vsel.row != 0 or t.cur_row != 0) return null; + const anchor = @min(@as(usize, @intCast(@max(0, t.vsel.col))), line.len); + const cursor = @min(@as(usize, @intCast(@max(0, t.cur_col))), line.len); + if (t.mode == .insert) return .{ .lo = @min(anchor, cursor), .hi = @max(anchor, cursor) }; + return .{ .lo = @min(anchor, cursor), .hi = modal.nextGrapheme(line, @max(anchor, cursor)) }; + } + fn renderHeaderLayer(p: *Pardes, arena: std.mem.Allocator, index: usize, kind: TagKind, id: u16, viewport: Rect, text: []const u8, bg: [3]u8, fg: [3]u8) !void { _ = arena; const layer = &p.surface.tag_layers[index]; @@ -6584,25 +6509,25 @@ pub const Pardes = struct { // A notice band carries a PANE id, not a column index, so it must not // answer to the column being edited -- that would scroll and select // its text with the column tag's offsets and give it a second caret. - const editing = p.topbar_col != null and switch (kind) { + const editing: ?*Text = if (p.header_focus and switch (kind) { .workspace => p.header_column == null, .column => p.header_column == id, .pane, .notice => false, - }; - const scroll = if (editing) p.header_scroll else 0; + }) p.focusedHeader() else null; + const scroll = if (editing != null) p.header_scroll else 0; surface.fill(0, 0, columns, 1, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); _ = surface.print(0, 0, columns, text[panes.File.rawAtDisplay(text, scroll)..], .{ .fg = .{ .rgb = fg }, .bg = .{ .rgb = bg }, .font_role = .tagline }); - if (editing) { - const cursor = p.topbar_col.?; - const anchor = p.header_anchor orelse cursor; - var col = panes.File.rawDisplayCol(text, @min(cursor, anchor)) -| scroll; - const end = panes.File.rawDisplayCol(text, @max(cursor, anchor)) -| scroll; - while (col < end and col < columns) : (col += 1) { - surface.at(@intCast(col), 0).style.bg = .{ .rgb = p.theme().sel_bg }; - surface.at(@intCast(col), 0).style.fg = .{ .rgb = p.theme().sel_fg }; + if (editing) |t| { + if (headerSelection(t, text)) |span| { + var col = panes.File.rawDisplayCol(text, span.lo) -| scroll; + const end = panes.File.rawDisplayCol(text, span.hi) -| scroll; + while (col < end and col < columns) : (col += 1) { + surface.at(@intCast(col), 0).style.bg = .{ .rgb = p.theme().sel_bg }; + surface.at(@intCast(col), 0).style.fg = .{ .rgb = p.theme().sel_fg }; + } } - const caret = panes.File.rawDisplayCol(text, cursor) -| scroll; - if (caret < columns) layer.cursor = .{ .col = @intCast(caret), .bar = p.header_insert }; + const caret = panes.File.rawDisplayCol(text, @min(@as(usize, @intCast(@max(0, t.cur_col))), text.len)) -| scroll; + if (t.cur_row == 0 and caret < columns) layer.cursor = .{ .col = @intCast(caret), .bar = t.mode == .insert }; } else if (p.pointer_inside) { const tag_hit = p.pointer_tag_hit; const col: ?usize = if (tag_hit) |pointer| diff --git a/src/tag_line.zig b/src/tag_line.zig deleted file mode 100644 index d3bdf59c..00000000 --- a/src/tag_line.zig +++ /dev/null @@ -1,42 +0,0 @@ -//! Bounded, single-line editable chrome. Offsets are UTF-8 byte offsets. -const std = @import("std"); -const modal = @import("modal.zig"); -pub const Line = struct { - text: [@import("memory.zig").limits.max_tag_tail]u8 = undefined, - len: usize = 0, - custom: bool = false, - saved_col: ?u16 = null, - - pub fn slice(self: *const Line, fallback: []const u8) []const u8 { - return if (self.custom) self.text[0..self.len] else fallback; - } - pub fn set(self: *Line, bytes: []const u8) bool { - if (bytes.len > self.text.len or std.mem.indexOfAny(u8, bytes, "\r\n\x00") != null or !std.unicode.utf8ValidateSlice(bytes)) return false; - @memcpy(self.text[0..bytes.len], bytes); - self.len = bytes.len; - self.custom = true; - return true; - } - pub fn replace(self: *Line, fallback: []const u8, lo: usize, hi: usize, bytes: []const u8) bool { - const current = self.slice(fallback); - if (lo > hi or hi > current.len) return false; - var next: [@import("memory.zig").limits.max_tag_tail]u8 = undefined; - const size = lo + bytes.len + current.len - hi; - if (size > next.len) return false; - @memcpy(next[0..lo], current[0..lo]); - @memcpy(next[lo..][0..bytes.len], bytes); - @memcpy(next[lo + bytes.len ..][0 .. current.len - hi], current[hi..]); - return self.set(next[0..size]); - } -}; - -test "tag replacement is atomic and keeps UTF-8 intact" { - var line: Line = .{}; - try std.testing.expect(line.replace("New Find", 4, 8, "Grep")); - try std.testing.expectEqualStrings("New Grep", line.slice("")); - try std.testing.expect(!line.replace("", 0, 0, "bad\nline")); - try std.testing.expectEqualStrings("New Grep", line.slice("")); - try std.testing.expect(line.set("é界")); - try std.testing.expect(line.replace("", 0, modal.nextGrapheme(line.slice(""), 0), "")); - try std.testing.expectEqualStrings("界", line.slice("")); -} diff --git a/test/column_drag.zig b/test/column_drag.zig index b2b8f35d..f128aa61 100644 --- a/test/column_drag.zig +++ b/test/column_drag.zig @@ -26,7 +26,7 @@ const Snapshot = struct { serial: u32, panes: [pardes.MAX_PANES]usize = undefined, count: usize, - tag: pardes.TagLine, + tag: []const u8, }; fn expectOrder(p: *Pardes, before: []const Snapshot, order: []const usize) !void { @@ -37,7 +37,7 @@ fn expectOrder(p: *Pardes, before: []const Snapshot, order: []const usize) !void try std.testing.expectEqual(saved.serial, p.col_serial[column]); try std.testing.expectEqual(saved.count, p.col_n[column]); try std.testing.expectEqualSlices(usize, saved.panes[0..saved.count], p.col_panes[column][0..p.col_n[column]]); - try std.testing.expectEqualStrings(saved.tag.slice(""), p.col_tags[column].slice("")); + try std.testing.expectEqualStrings(saved.tag, p.columnTag(column)); } } @@ -59,7 +59,7 @@ test "column grip drag moves only its interval and keeps tag caret with the colu try std.testing.expectEqual(@as(usize, 2), p.col_n[1]); for ([_]u64{ 2, 3, 5, 7 }, 0..) |weight, column| { p.col_weight[column] = weight; - try std.testing.expect(p.col_tags[column].set(([_][]const u8{ "zero column header", "one column header", "two column header", "three column header" })[column])); + p.col_tags[column].own = try p.gpa.dupe(u8, ([_][]const u8{ "zero column header", "one column header", "two column header", "three column header" })[column]); } p.update(.tick); var frame = std.heap.ArenaAllocator.init(p.gpa); @@ -67,7 +67,7 @@ test "column grip drag moves only its interval and keeps tag caret with the colu _ = try p.render(frame.allocator()); var before: [4]Snapshot = undefined; for (&before, 0..) |*saved, column| { - saved.* = .{ .weight = p.col_weight[column], .serial = p.col_serial[column], .count = p.col_n[column], .tag = p.col_tags[column] }; + saved.* = .{ .weight = p.col_weight[column], .serial = p.col_serial[column], .count = p.col_n[column], .tag = p.columnTag(column) }; @memcpy(saved.panes[0..saved.count], p.col_panes[column][0..saved.count]); } const layer = try tagLayer(p, 1); @@ -75,8 +75,8 @@ test "column grip drag moves only its interval and keeps tag caret with the colu p.update(.{ .mouse = headerMouse(layer, 10, .press) }); p.update(.{ .mouse = headerMouse(layer, 10, .release) }); try std.testing.expectEqual(@as(?usize, 1), p.header_column); - const caret = p.topbar_col; - const anchor = p.header_anchor; + const caret = p.focusedHeader().?.cur_col; + const anchor = p.focusedHeader().?.vsel; const scroll = p.header_scroll; const target = p.col_x[3] + p.col_w[3] - 2; const last_rect = p.rects[p.col_panes[3][0]]; @@ -93,14 +93,14 @@ test "column grip drag moves only its interval and keeps tag caret with the colu try expectOrder(p, &before, &.{ 0, 2, 3, 1 }); try std.testing.expectEqual(active, p.active); try std.testing.expectEqual(@as(?usize, 3), p.header_column); - try std.testing.expectEqual(caret, p.topbar_col); - try std.testing.expectEqual(anchor, p.header_anchor); + try std.testing.expectEqual(caret, p.focusedHeader().?.cur_col); + try std.testing.expectEqual(anchor, p.focusedHeader().?.vsel); try std.testing.expectEqual(scroll, p.header_scroll); // The old tag envelope must not edit the new occupant of its old index, // including the interval before hosts request another rendered frame. p.update(.{ .mouse = stale }); try std.testing.expectEqual(@as(?usize, 3), p.header_column); - try std.testing.expectEqual(caret, p.topbar_col); + try std.testing.expectEqual(caret, p.focusedHeader().?.cur_col); _ = try p.render(frame.allocator()); try std.testing.expectEqual(before[1].serial, (try tagLayer(p, 3)).serial); try std.testing.expectEqual(p.col_w[3] - pardes.TAG_TEXT_INSET, (try tagLayer(p, 3)).viewport.w); @@ -110,7 +110,7 @@ test "column grip drag moves only its interval and keeps tag caret with the colu mouse(p, .release, back); try expectOrder(p, &before, &.{ 0, 1, 2, 3 }); try std.testing.expectEqual(@as(?usize, 1), p.header_column); - try std.testing.expectEqual(caret, p.topbar_col); + try std.testing.expectEqual(caret, p.focusedHeader().?.cur_col); try std.testing.expectEqual(active, p.active); // A structural change between press and release must not retarget the // in-flight drag to whichever column now occupies the original index. @@ -165,7 +165,7 @@ test "column grip is separate from compact text and the resize seam" { try std.testing.expect(p.drag != .column_move); try std.testing.expect(p.header_drag); p.update(.{ .mouse = headerMouse(layer, 0, .release) }); - try std.testing.expectEqual(@as(?u16, 0), p.topbar_col); + try std.testing.expectEqual(@as(i32, 0), p.focusedHeader().?.cur_col); mouse(p, .press, p.col_x[1] + config.GUTTER - 1); try std.testing.expect(p.drag == .column_move); mouse(p, .release, p.col_x[1] + config.GUTTER - 1); diff --git a/test/panes.zig b/test/panes.zig index a391dba2..b9fa9a88 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -152,8 +152,8 @@ const TagLayerTests = struct { try std.testing.expect(left.sel[0].state == .done and left.sel[0].r0 == 0); p.update(.{ .key = .{ .cp = Key.escape } }); const long = "a" ** 60 ++ "界END"; - try std.testing.expect(p.global_tag.set(long)); - for (p.col_tags[0..p.ncol]) |*tag| try std.testing.expect(tag.set(long)); + p.global_tag.own = try p.gpa.dupe(u8, long); + for (p.col_tags[0..p.ncol]) |*tag| tag.own = try p.gpa.dupe(u8, long); _ = try p.render(frame.allocator()); for ([_]Kind{ .workspace, .column }) |kind| { const id: usize = if (kind == .column) 1 else 0; @@ -161,7 +161,7 @@ const TagLayerTests = struct { const x = @as(f32, @floatFromInt(header.viewport.x)) * 10 + 62.5 * 5; p.update(.{ .mouse = mouse(header, x, .press) }); p.update(.{ .mouse = mouse(header, x, .release) }); - try std.testing.expectEqual(@as(?u16, 63), p.topbar_col); + try std.testing.expectEqual(@as(i32, 63), p.focusedHeader().?.cur_col); if (kind == .column) try std.testing.expectEqual(@as(?usize, 1), p.header_column) else try std.testing.expect(p.header_column == null); p.update(.{ .key = .{ .cp = Key.escape } }); } @@ -334,7 +334,7 @@ const TagNavigationTests = struct { key(p, 'j'); try std.testing.expectEqual(@as(i32, 0), pane.tag.cur_col); try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expect(pane.focus == .tag and p.topbar_col == null); + try std.testing.expect(pane.focus == .tag and !p.header_focus); window(p, 'l'); try std.testing.expectEqual(right, p.active); try std.testing.expect(pane.focus == .body and p.panes[right].?.focus == .body); @@ -1291,13 +1291,13 @@ test "leaving a pane or entering a header cancels an uncommitted filename" { const pane = try p.setTestFile("untouched\n"); for ([_]bool{ false, true }) |header| { p.active = 0; - p.topbar_col = null; + p.exitHeader(); p.update(.tick); clickPathEnd(p, pane); p.update(.{ .paste = "/draft" }); try std.testing.expect(pane.prompt == .name); if (header) { - p.topbar_col = 0; + p.enterHeader(null); p.update(.tick); } else { try std.testing.expect(p.executeBuiltinLine(0, "New")); diff --git a/test/snapshots/tagnav.golden b/test/snapshots/tagnav.golden index 3fdba9f2..45d64b42 100644 --- a/test/snapshots/tagnav.golden +++ b/test/snapshots/tagnav.golden @@ -39,3 +39,27 @@ |5: 3 gamma $ == snap tty-tag grid=100x31 cursor=90,2 == snap tty-restored grid=100x31 cursor=54,5 +== snap column-tag grid=100x31 cursor=3,1 +|2: /tmp/pardes-snap/tagnav/cwd/w.txt Save Tty Coll /tmp/pardes-snap/tagnav/cwd Tty Save Mode Filte +|3: 1 alpha Up ls +|5: 3 gamma +== snap column-word grid=100x31 cursor=6,1 +|3: 1 alpha ls +== snap workspace-tag grid=100x31 cursor=0,0 +|3: 1 alpha Up ls +== snap topbar-dollar grid=100x31 cursor=70,0 +|3: 1 alpha ls +== snap topbar-dump-word grid=100x31 cursor=46,0 +== snap topbar-exec grid=100x31 cursor=7,3 +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill Restore /tmp/pardes-snap/tag +|3: 1 alpha Dump ls +== snap topbar-restore-word grid=100x31 cursor=72,0 +|3: 1 alpha ls +== snap topbar-restored grid=100x31 cursor=7,3 +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill +|3: 1 alpha $ ls +|5: 3 gamma $ +|6: ── restored history ── +|18: $ ls +|20: $ +|21: ── restored history ── diff --git a/test/snapshots/tagnav.snap b/test/snapshots/tagnav.snap index eed808de..c9ac9605 100644 --- a/test/snapshots/tagnav.snap +++ b/test/snapshots/tagnav.snap @@ -77,3 +77,46 @@ settle 100 key : stable 400 5000 snap tty-restored +# The column and workspace tags are Texts in the same layout, with the same +# keys: Up from a pane with nothing above it reaches its column's tag, in +# normal mode, then the workspace's; Down comes back the same way. +key c-b +stable 700 15000 +key c-w h +stable 400 5000 +key c-w k +stable 400 5000 +snap column-tag +key w +stable 400 5000 +snap column-word +key c-w k +stable 400 5000 +snap workspace-tag +# `$` is the last cell; four long-word steps back land on `Dump`, and the +# execute key runs it and gives the keyboard back to the body FIRST -- `Kill` +# lives up here too, so a builtin that frees the session must never return +# into a focused header. Dump grows a `Restore ` word, which is also the +# case where the line gets longer than the column you were parked on. +key $ +stable 400 5000 +snap topbar-dollar +key B B B B +stable 400 5000 +snap topbar-dump-word +key tab +stable 700 15000 +snap topbar-exec +# THE DELETION HAZARD, from the bar itself: `Restore` frees every pane and +# swaps the core out from under the caller. Walk back up onto the word the +# Dump just grew -- B twice off the tail, because the LONG word motions are the +# ones that step over a path in one go -- and run it. +key c-w k +key c-w k +stable 400 5000 +key $ B B +stable 400 5000 +snap topbar-restore-word +key tab +stable 900 15000 +snap topbar-restored -- cgit v1.3 From 232bfbbc4371a1fe9df210874118b4450dce7f9d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 00:30:46 -0300 Subject: Let a pane's tag take a row for each line it holds A tag that is a text can hold a newline, and the tagline, the body under it and the pointer all assumed one row. The pane's tag now takes a row per line (up to eight, and never the body's last row); the body starts below it, the rows a pointer counts start the body after the tag's lines, a click on any line puts the tag's cursor there, and a pixel shell gets a tag layer per line. A tag of one line draws exactly as before. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 14 ++-- src/Messages.zig | 8 +- src/Terminal.zig | 12 +-- src/body_layer.zig | 69 ++++++++-------- src/edit.zig | 34 ++++---- src/exec.zig | 14 ++-- src/gui/gui.zig | 34 ++++---- src/look.zig | 2 +- src/mouse.zig | 127 +++++++++++++++------------- src/panes.zig | 6 +- src/pardes.zig | 237 ++++++++++++++++++++++++++++++++--------------------- src/pdf_view.zig | 23 +++--- src/tag_layer.zig | 6 ++ test/output.zig | 4 +- test/panes.zig | 80 +++++++++++++++--- 15 files changed, 406 insertions(+), 264 deletions(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index 22e3c434..262f3ebb 100644 --- a/src/File.zig +++ b/src/File.zig @@ -378,7 +378,7 @@ pub fn gutterWidth(pane: *const Pane) u16 { /// Convert between rendered cells and UTF-8 byte columns. Tag rows always /// need grapheme conversion; file body rows additionally skip the gutter. pub fn renderedLineByteCol(pane: *const Pane, row: i32, line_text: []const u8, display_col: usize) usize { - if (row < pardes.BOX_H) return rawAtDisplay(line_text, display_col); + if (row < pane.tag_rows) return rawAtDisplay(line_text, display_col); if (pane.file == null) return rawAtDisplay(line_text, display_col); const prefix = @min(@as(usize, gutterWidth(pane)), line_text.len); if (display_col <= prefix) return display_col; @@ -386,7 +386,7 @@ pub fn renderedLineByteCol(pane: *const Pane, row: i32, line_text: []const u8, d } pub fn renderedLineDisplayCol(pane: *const Pane, row: i32, line_text: []const u8, byte_col: usize) usize { - if (row < pardes.BOX_H) return rawDisplayCol(line_text, byte_col); + if (row < pane.tag_rows) return rawDisplayCol(line_text, byte_col); if (pane.file == null) return rawDisplayCol(line_text, byte_col); const prefix = @min(@as(usize, gutterWidth(pane)), line_text.len); if (byte_col <= prefix) return byte_col; @@ -1133,7 +1133,7 @@ pub fn drawGutter(p: *Pardes, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, bod const typing_body = pane.focus == .body and (pane.prompt == .none or pane.prompt == .del_side); const cur_line: i32 = if (active and typing_body) gcrow else std.math.minInt(i32); // the body's first row, the way renderPane derives it (Tagbottom) - const body_y = p.bodyTop(r); + const body_y = p.bodyTop(pane, r); const context_bg = p.theme().tag_bg; for (0..@min(pane.context_rows, body_h)) |context_row| { for (0..tw) |col| { @@ -1187,7 +1187,7 @@ pub fn recolorSyntax(p: *Pardes, pane: *Pane, f: *State, r: pardes.Rect, tx: u16 // indexed start, same as bodyText — an empty tail simply paints nothing var flines = std.mem.splitScalar(u8, f.content[lineStart(p.gpa, f, f.scroll)..], '\n'); const total = nlines(p.gpa, f); - const body_y = p.bodyTop(r); + const body_y = p.bodyTop(pane, r); var vr: u16 = 0; while (vr < body_h) : (vr += 1) { var base: usize = undefined; @@ -1263,7 +1263,7 @@ pub fn drawWrapMarkers( pane_bg: pardes.Color, ) void { if (tw <= gutterWidth(pane) + 1) return; - const body_y = p.bodyTop(r); + const body_y = p.bodyTop(pane, r); const marker_fg = p.chromeTheme().lineno; var row: u16 = 0; while (row + 1 < pane.wrap_n and row + 1 < body_h) : (row += 1) { @@ -1287,9 +1287,9 @@ pub fn paintWordSelection( const tx = r.x + config.GUTTER; const tw = r.w - config.GUTTER; const prefix_width = gutterWidth(pane); - const body_y = p.bodyTop(r); + const body_y = p.bodyTop(pane, r); var vr: i32 = 0; - while (vr + @as(i32, pardes.BOX_H) < @as(i32, r.h)) : (vr += 1) { + while (vr + @as(i32, pane.tag_rows) < @as(i32, r.h)) : (vr += 1) { const here = pane.wrapAt(vr); if (here.line != row) continue; var hi = word_hi; diff --git a/src/Messages.zig b/src/Messages.zig index 053950da..c7ff09be 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -397,7 +397,7 @@ pub fn reportError(p: *Pardes, id: usize, operation: []const u8, err: anyerror) /// them instead of letting the last one win the row. pub fn collectNotices(p: *Pardes, pane: *Pane, r: Rect, id: usize) void { pane.notices.len = 0; - if (r.w <= config.GUTTER or r.h <= BOX_H) return; + if (r.w <= config.GUTTER or r.h <= pane.tag_rows) return; // Oldest message line on top, so lines already up do not move when a // new one lands under them; when rows run out the oldest go first. for (pane.msg_older[0..pane.msg_older_len], 0..) |line, i| pane.notices.pushAt(.older, @intCast(i), line.slot); @@ -409,7 +409,7 @@ pub fn collectNotices(p: *Pardes, pane: *Pane, r: Rect, id: usize) void { // carrying the cursor: a prompt you cannot see is a prompt you type // into blind. A two-row pane spends its only body row on one notice, // which is what the single shared row used to do anyway. - const room: u8 = @intCast(@min(@as(u16, Pane.Notices.max), r.h - BOX_H)); + const room: u8 = @intCast(@min(@as(u16, Pane.Notices.max), r.h - pane.tag_rows)); const n = &pane.notices; if (n.span() <= room) return; // Too short for the gaps: close them up in screen order, and if even @@ -743,7 +743,7 @@ test "notices stack over the body's top rows without moving them" { defer frame.deinit(); const r = p.rects[id]; - const top = p.bodyTop(r); + const top = p.bodyTop(pane, r); // A message and a leader prefix at once: two chips, in the order // collectNotices chose, each one row tall and each one row further down. @@ -754,7 +754,7 @@ test "notices stack over the body's top rows without moving them" { _ = try p.render(frame.allocator()); try std.testing.expectEqual(@as(u8, 2), pane.notices.len); // An overlay, not a reservation: the body still starts where it did. - try std.testing.expectEqual(top, p.bodyTop(r)); + try std.testing.expectEqual(top, p.bodyTop(pane, r)); var seen: usize = 0; for (p.surface.tagLayers()) |*layer| { diff --git a/src/Terminal.zig b/src/Terminal.zig index 7b5af696..16d5af26 100644 --- a/src/Terminal.zig +++ b/src/Terminal.zig @@ -1723,7 +1723,7 @@ pub fn recolorAnsi(p: *Pardes, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, bo if (comptime !enabled) return; const s = &p.surface; if (pane.terminal == null) return; - const body_y = p.bodyTop(r); + const body_y = p.bodyTop(pane, r); var filtered_storage: FilteredColors = undefined; const filtered: ?*FilteredColors = if (pane.tty_filter) blk: { const tz_filter = tracy.zone(@src(), "filterInit"); @@ -2081,7 +2081,7 @@ test "terminal Filter keys indexed truecolor OSC and background-only cells throu defer frame.deinit(); const r = p.rects[0]; const tx = r.x + config.GUTTER; - const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; + const body_y = p.bodyTop(pane, r); const raw = try p.render(frame.allocator()); try testing.expectEqual(pardes.Color{ .index = 1 }, raw.at(tx, body_y).style.fg); @@ -2231,7 +2231,7 @@ test "terminal Filter preserves exact palette-null light theme default roles" { defer frame.deinit(); const r = p.rects[0]; const tx = r.x + config.GUTTER; - const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; + const body_y = p.bodyTop(pane, r); const ordinary = try p.render(frame.allocator()); try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, ordinary.at(tx, body_y).style.fg); try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, ordinary.at(tx, body_y).style.bg); @@ -2290,7 +2290,7 @@ test "terminal Filter refuses a foreground that would collapse onto the page" { defer frame.deinit(); const r = p.rects[0]; const tx = r.x + config.GUTTER; - const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; + const body_y = p.bodyTop(pane, r); for (0..9) |t| { p.settings.theme = @intCast(t); @@ -2382,7 +2382,7 @@ test "tty ansi colors follow the prompt hug into normal mode" { defer frame.deinit(); const r = p.rects[0]; const tx = r.x + config.GUTTER; - const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; + const body_y = p.bodyTop(pane, r); const red: pardes.Color = .{ .rgb = p.theme().palette.?[1] }; const blue: pardes.Color = .{ .rgb = p.theme().palette.?[4] }; @@ -2417,7 +2417,7 @@ test "a prompt row hidden end to end paints nothing at all" { defer frame.deinit(); const r = p.rects[0]; const tx = r.x + config.GUTTER; - const body_y = if (p.settings.tag_bottom) r.y else r.y + pardes.BOX_H; + const body_y = p.bodyTop(pane, r); p.shell_rows.stale = true; const s = try p.render(frame.allocator()); diff --git a/src/body_layer.zig b/src/body_layer.zig index e85e10f1..2b2c8a74 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -135,11 +135,11 @@ fn paintTerminalSelection(p: *Pardes, pane: *Pane, r: Rect, rows: []const Pane.P const raw = pane.body.mode == .tty; const tx = r.x + config.GUTTER; const width = r.w -| config.GUTTER; - const body_y = p.bodyTop(r); + const body_y = p.bodyTop(pane, r); var lines = std.mem.splitScalar(u8, body, '\n'); var visible: i32 = 0; while (lines.next()) |line| : (visible += 1) { - if (visible >= r.h -| BOX_H) break; + if (visible >= r.h -| pane.tag_rows) break; const source_row = if (raw) panes.Terminal.gridOffset(pane) + visible else pane.wrapAt(visible).line; for (rows) |row| { const target = if (row.raw_terminal) @@ -177,10 +177,10 @@ fn paintSourceSelection(p: *Pardes, pane: *Pane, r: Rect, rows: []const Pane.Poi const terminal_lines = if (pane.file == null) panes.Terminal.cursorLines(p, pane) catch return else &.{}; const tx = r.x + config.GUTTER; const width = r.w -| config.GUTTER; - const body_y = p.bodyTop(r); + const body_y = p.bodyTop(pane, r); const prefix: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; var visible: i32 = 0; - while (visible < @as(i32, r.h -| BOX_H)) : (visible += 1) { + while (visible < @as(i32, r.h -| pane.tag_rows)) : (visible += 1) { const source = pane.wrapAt(visible); const line = edit.pointerSourceLine(pane, terminal_lines, source.line); const start = @min(line.len, @as(usize, @intCast(@max(0, source.at)))); @@ -224,13 +224,13 @@ pub fn paintPointerSelection( var row: u16 = 0; while (row < r.h) : (row += 1) { if (@as(i32, row) < r0 or @as(i32, row) > r1) continue; - const sy = if (row < BOX_H) tag_y else body_y + row - BOX_H; + const sy = if (row < pane.tag_rows) tag_y + row else body_y + row - pane.tag_rows; // File line numbers occupy a gutter only in the body. The tag is // row zero in Sel space and starts at its real first text cell. - const scroll: i32 = if (row < BOX_H) pane.tag_scroll else 0; - var col: i32 = if (pane.file != null and row >= BOX_H) @max(c0, @as(i32, panes.File.gutterWidth(pane))) else @max(0, c0 - scroll); - const row_x = if (row < BOX_H) r.x + @min(TAG_TEXT_INSET, r.w) else tx; - const row_width = if (row < BOX_H) r.w -| TAG_TEXT_INSET else tw; + const scroll: i32 = if (row < pane.tag_rows) pane.tag_scroll else 0; + var col: i32 = if (pane.file != null and row >= pane.tag_rows) @max(c0, @as(i32, panes.File.gutterWidth(pane))) else @max(0, c0 - scroll); + const row_x = if (row < pane.tag_rows) r.x + @min(TAG_TEXT_INSET, r.w) else tx; + const row_width = if (row < pane.tag_rows) r.w -| TAG_TEXT_INSET else tw; while (col <= c1 - scroll and col < row_width) : (col += 1) { const cell = s.at(row_x + @as(u16, @intCast(col)), sy); cell.default = false; @@ -242,8 +242,8 @@ pub fn paintPointerSelection( pub fn renderBodyLayer(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize) !void { if (!p.settings.tree_context_tag_style or pane.context_rows == 0 or pane.file == null or pane.collapsed) return; - if (r.w <= config.GUTTER or r.h <= BOX_H) return; - const viewport_rows = r.h - BOX_H; + if (r.w <= config.GUTTER or r.h <= pane.tag_rows) return; + const viewport_rows = r.h - pane.tag_rows; if (viewport_rows == 0) return; // The canonical fixed grid remains available to terminal clients. The // separate body layer reserves enough rows for any compact font size. @@ -260,24 +260,24 @@ pub fn renderBodyLayer(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rec const layer = &p.surface.body_layers[id]; const count = logical_rows * width; if (layer.cells.len != count) layer.cells = try p.gpa.realloc(layer.cells, count); - const temporary_cells = try arena.alloc(Cell, @as(usize, r.w) * (logical_rows + BOX_H)); + const temporary_cells = try arena.alloc(Cell, @as(usize, r.w) * (logical_rows + pane.tag_rows)); @memset(temporary_cells, .{}); - var temporary: Surface = .{ .cols = r.w, .rows = @intCast(logical_rows + BOX_H), .cells = temporary_cells }; + var temporary: Surface = .{ .cols = r.w, .rows = @intCast(logical_rows + pane.tag_rows), .cells = temporary_cells }; std.mem.swap(Surface, &p.surface, &temporary); - const synthetic: Rect = .{ .x = 0, .y = 0, .w = r.w, .h = @intCast(logical_rows + BOX_H) }; + const synthetic: Rect = .{ .x = 0, .y = 0, .w = r.w, .h = @intCast(logical_rows + pane.tag_rows) }; renderBody(p, arena, pane, synthetic, id, id == p.active, false) catch |err| { std.mem.swap(Surface, &p.surface, &temporary); return err; }; std.mem.swap(Surface, &p.surface, &temporary); - const first_row: usize = if (p.settings.tag_bottom) 0 else BOX_H; + const first_row: usize = if (p.settings.tag_bottom) 0 else pane.tag_rows; for (0..logical_rows) |row| { const start = (row + first_row) * r.w + config.GUTTER; @memcpy(layer.cells[row * width ..][0..width], temporary_cells[start..][0..width]); } layer.pane = @intCast(id); layer.serial = pane.serial; - layer.viewport = .{ .x = r.x + config.GUTTER, .y = p.bodyTop(r), .w = width, .h = viewport_rows }; + layer.viewport = .{ .x = r.x + config.GUTTER, .y = p.bodyTop(pane, r), .w = width, .h = viewport_rows }; layer.cols = width; layer.rows = @intCast(logical_rows); layer.context_rows = pane.context_rows; @@ -295,15 +295,15 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id const chrome = p.chromeTheme(); const tx = r.x + config.GUTTER; const tw = r.w - config.GUTTER; - const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; + const tag_y = p.tagTop(pane, r); // Below the notice bands: they are stacked at the top of the body the // way tree-sitter context rows are, so the body starts under them // rather than being painted over by them. - const body_y = p.bodyTop(r); + const body_y = p.bodyTop(pane, r); const pane_bg: Color = if (th.bg) |c| .{ .rgb = c } else .default; const page_rgb = th.bg orelse th.tag_bg; // body: emulator rows, prompt rows hidden outside tty mode - const body_h = r.h -| BOX_H; + const body_h = r.h -| pane.tag_rows; const body_bottom = r.h; const body_style: CellStyle = .{ .fg = if (th.fg) |c| .{ .rgb = c } else .default, @@ -365,7 +365,7 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id if (sl.state == .done and b != 0) continue; // A select sweep over the tag is the tag's selection, painted there // in the tag's own selection colours. - if (b == pardes.sel_slot and @min(sl.r0, sl.r1) < BOX_H) continue; + if (b == pardes.sel_slot and @min(sl.r0, sl.r1) < pane.tag_rows) continue; paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, sl, sel_btn[b], th.sel_fg); } // modal line selection (helix `x`): whole body rows, normal mode only @@ -377,13 +377,13 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id th.sel_bg; const lo = @min(pane.body.msel.r0, pane.body.msel.r1); const hi = @max(pane.body.msel.r0, pane.body.msel.r1); - var row: u16 = BOX_H; // never paint the tag row + var row: u16 = pane.tag_rows; // never paint the tag row while (row < body_bottom) : (row += 1) { - const ar = pane.wrapAt(@as(i32, row) - @as(i32, BOX_H)).line; + const ar = pane.wrapAt(@as(i32, row) - @as(i32, pane.tag_rows)).line; if (ar < lo or ar > hi) continue; var col: u16 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; while (col < tw) : (col += 1) { - const cell = s.at(tx + col, body_y + row - BOX_H); + const cell = s.at(tx + col, body_y + row - pane.tag_rows); cell.default = false; cell.style.bg = .{ .rgb = modal_bg }; if (!hover_only) cell.style.fg = .{ .rgb = th.sel_fg }; @@ -415,7 +415,7 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id else colors.mix(th.sel_bg, page_rgb); var vr: i32 = 0; - while (vr + @as(i32, BOX_H) < @as(i32, body_bottom)) : (vr += 1) { + while (vr + @as(i32, pane.tag_rows) < @as(i32, body_bottom)) : (vr += 1) { const w = pane.wrapAt(vr); if (w.line < bnd.lo_row or w.line > bnd.hi_row) continue; const visible_line = modal.lineSlice(body, @intCast(vr)); @@ -444,7 +444,7 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id if (primary and !preview and !hover_only) continue; // the hardware cursor IS the primary's if (hover_only) continue; // quiet preview preserves the source ink const cw = pane.wrapRow(sr.row, sr.col); - const crow = cw.row + @as(i32, BOX_H); + const crow = cw.row + @as(i32, pane.tag_rows); const ccol = (if (pane.file != null) panes.File.displayOffset(pane, sr.row, cw.at, sr.col) else @@ -453,8 +453,8 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id @intCast(@max(0, cw.at)), @intCast(@max(0, sr.col)), )) + vpfx; - if (crow >= BOX_H and crow < @as(i32, body_bottom) and ccol >= vpfx and ccol < tw) { - const cell = s.at(tx + @as(u16, @intCast(ccol)), body_y + @as(u16, @intCast(crow - BOX_H))); + if (crow >= pane.tag_rows and crow < @as(i32, body_bottom) and ccol >= vpfx and ccol < tw) { + const cell = s.at(tx + @as(u16, @intCast(ccol)), body_y + @as(u16, @intCast(crow - pane.tag_rows))); cell.default = false; cell.style.bg = .{ .rgb = th.sel_fg }; cell.style.fg = .{ .rgb = th.sel_bg }; @@ -471,7 +471,7 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id const crow = if (pane.body.cur_pinned) pane.body.cur_row else pane.surfRow(@as(i32, @intCast(cur.y)) + goff); const ccol = if (pane.body.cur_pinned) pane.body.cur_col else @as(i32, @intCast(cur.x)); const cwp = pane.wrapRow(crow, ccol); - const prow = cwp.row + @as(i32, BOX_H); + const prow = cwp.row + @as(i32, pane.tag_rows); // Files store source-byte columns; the Surface stores display // cells, so account for every expanded tab before the cursor. const cx = if (pane.file != null) @@ -484,10 +484,10 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id ) else ccol; - if (prow >= BOX_H and cx >= 0 and prow < body_bottom and cx < tw) - s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = body_y + @as(u16, @intCast(prow - BOX_H)), .bar = pane.body.mode == .insert }; + if (prow >= pane.tag_rows and cx >= 0 and prow < body_bottom and cx < tw) + s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = body_y + @as(u16, @intCast(prow - pane.tag_rows)), .bar = pane.body.mode == .insert }; } else if (panes.Terminal.visibleCursor(pane)) |cur| { - if (cur.y + BOX_H < body_bottom and cur.x < tw) + if (cur.y + pane.tag_rows < body_bottom and cur.x < tw) s.cursor = .{ .x = tx + cur.x, .y = body_y + cur.y }; } } @@ -496,10 +496,9 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id // The rail covers the notice bands too: nothing else paints those // two gutter columns, so a gap there keeps the frame-wide border // fill and reads as a notch cut out of the scrollbar. - const rail_y = if (p.settings.tag_bottom) r.y else r.y + BOX_H; - const rail_h = r.h -| BOX_H; - s.fill(r.x, rail_y, 1, rail_h, .{ .bg = .{ .rgb = chrome.scroll_track } }); - s.fill(r.x + 1, rail_y, 1, rail_h, .{ .bg = pane_bg }); + const rail_h = r.h -| pane.tag_rows; + s.fill(r.x, body_y, 1, rail_h, .{ .bg = .{ .rgb = chrome.scroll_track } }); + s.fill(r.x + 1, body_y, 1, rail_h, .{ .bg = pane_bg }); const sb: struct { total: usize, offset: usize, len: usize } = if (pane.file) |*f| .{ .total = panes.File.nlines(p.gpa, f), .offset = f.scroll, diff --git a/src/edit.zig b/src/edit.zig index 1822db31..36544d6b 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -128,10 +128,14 @@ pub fn clipYank(p: *Pardes, pane: *Pane, main_only: bool) void { p.emit(.{ .set_clipboard = {} }); } -/// tag + '\n' + body: the full selectable pane text (row 0 = the tag) +/// tag + '\n' + body: the full selectable pane text, a row to a screen row +/// (the tag's lines first, as many as it shows) pub fn paneText(p: *Pardes, pane: *Pane) ![]u8 { const arena = p.scratch.allocator(); - return std.fmt.allocPrint(arena, "{s}\n{s}", .{ try p.tagText(arena, pane), try body_layer.bodyText(p, arena, pane) }); + const tag = try p.tagText(arena, pane); + const cut = modal.lineStartOffset(tag, pane.tag_rows); + const shown = if (cut < tag.len) tag[0 .. cut - 1] else tag; + return std.fmt.allocPrint(arena, "{s}\n{s}", .{ shown, try body_layer.bodyText(p, arena, pane) }); } pub fn pointerSourceLine(pane: *Pane, terminal_lines: []const []const u8, row: i32) []const u8 { @@ -144,16 +148,16 @@ pub fn pointerSourceLine(pane: *Pane, terminal_lines: []const []const u8, row: i pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { var gesture = pane.sel[slot]; if (pane.hasPdf()) return; - if (gesture.state != .done or @min(gesture.r0, gesture.r1) < BOX_H) return; + if (gesture.state != .done or @min(gesture.r0, gesture.r1) < pane.tag_rows) return; if (pane.pointerSelection(gesture) != null) return; pane.clearPointerSelection(slot); // Refresh the source map before translating the rendered rectangle. const raw = pane.isTerminal() and pane.body.mode == .tty; const body = try body_layer.bodyText(p, p.scratch.allocator(), pane); const terminal_lines = if (pane.file == null and !raw) try panes.Terminal.cursorLines(p, pane) else &.{}; - const first = @max(0, @min(gesture.r0, gesture.r1) - BOX_H); + const first = @max(0, @min(gesture.r0, gesture.r1) - pane.tag_rows); const logical_rows = if (pane.body_rows > 0) pane.body_rows else pane.rows; - const last = @min(@as(i32, logical_rows) - 1, @max(gesture.r0, gesture.r1) - BOX_H); + const last = @min(@as(i32, logical_rows) - 1, @max(gesture.r0, gesture.r1) - pane.tag_rows); if (first > last) return; const rows = try p.gpa.alloc(Pane.PointerRow, @intCast(last - first + 1)); errdefer p.gpa.free(rows); @@ -1595,28 +1599,28 @@ const PointerTextSelection = struct { }; pub fn pointerTextSelection(p: *const Pardes, id: usize, col: u16, row: u16, body_hit: ?Mouse.BodyHit, tag_hit: ?TagHit) ?PointerTextSelection { - if (p.panes[id] == null) return null; + const pane = p.panes[id] orelse return null; const r = p.rects[id]; if (col < r.x + config.GUTTER or col >= r.x + r.w or row < r.y or row >= r.y + r.h) return null; - const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; - const body_y = p.bodyTop(r); - const on_tag = row >= tag_y and row < tag_y + BOX_H; + const tag_y = p.tagTop(pane, r); + const body_y = p.bodyTop(pane, r); + const on_tag = row >= tag_y and row < tag_y + pane.tag_rows; if (on_tag and col < r.x + TAG_TEXT_INSET) return null; // A notice chip is chrome: it sits OVER the body's top rows, so a // click inside one belongs to nobody. The rest of those rows is // ordinary body text and still answers normally. - if (!on_tag and row >= body_y and row - body_y < p.panes[id].?.notices.span() and - p.panes[id].?.notices.covers(row - body_y, col)) return null; + if (!on_tag and row >= body_y and row - body_y < pane.notices.span() and + pane.notices.covers(row - body_y, col)) return null; if (!on_tag) if (body_hit) |supplied| { const mapped_hit = mouse.bodyHitForPane(p, id, supplied, false) orelse return null; const c = @as(i32, mapped_hit.col) - config.GUTTER; - const v = @as(i32, mapped_hit.row) + BOX_H; + const v = @as(i32, mapped_hit.row) + pane.tag_rows; return .{ .sel = .{ .state = .dragging, .c0 = c, .c1 = c, .r0 = v, .r1 = v }, .on_tag = false }; }; - const tag_col = if (on_tag) mouse.tagColumn(p, .pane, id, tag_hit, false) else null; + const tag_col = if (on_tag) mouse.tagColumn(p, .pane, id, tag_hit, false, row - tag_y) else null; const c: i32 = (if (tag_col) |value| @as(i32, value) else @as(i32, col) - @as(i32, r.x + (if (on_tag) TAG_TEXT_INSET else config.GUTTER))) + - (if (on_tag) @as(i32, p.panes[id].?.tag_scroll) else 0); - const v: i32 = if (on_tag) 0 else @as(i32, row) - @as(i32, body_y) + @as(i32, BOX_H); + (if (on_tag) @as(i32, pane.tag_scroll) else 0); + const v: i32 = if (on_tag) @as(i32, row) - @as(i32, tag_y) else @as(i32, row) - @as(i32, body_y) + @as(i32, pane.tag_rows); return .{ .sel = .{ .state = .dragging, .c0 = c, .c1 = c, .r0 = v, .r1 = v }, .on_tag = on_tag, diff --git a/src/exec.zig b/src/exec.zig index 82b3da4a..a673e9e7 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -94,14 +94,14 @@ pub const PointerOperand = struct { }; pub fn pointerOperand(p: *Pardes, pane: *Pane, clicked: Pane.Sel) PointerOperand { - const visible = clicked.r0 - @as(i32, BOX_H); + const visible = clicked.r0 - @as(i32, pane.tag_rows); const wrapped = pane.wrapAt(visible); - const raw = pane.isTerminal() and pane.body.mode == .tty and clicked.r0 >= BOX_H; + const raw = pane.isTerminal() and pane.body.mode == .tty and clicked.r0 >= pane.tag_rows; const row = if (raw) panes.Terminal.gridOffset(pane) + visible else wrapped.line; const raw_line = if (raw) modal.lineSlice(body_layer.bodyText(p, p.scratch.allocator(), pane) catch "", @intCast(@max(0, visible))) else ""; const col = if (raw) @as(i32, @intCast(panes.File.rawAtDisplay(raw_line, @intCast(@max(0, clicked.c0))))) - else if (clicked.r0 >= BOX_H) + else if (clicked.r0 >= pane.tag_rows) edit.paneByteAtDisplay( p, &pane.body, @@ -115,7 +115,7 @@ pub fn pointerOperand(p: *Pardes, pane: *Pane, clicked: Pane.Sel) PointerOperand const kept = pane.sel[sel_slot]; const inside_kept = if (pane.pointerSelection(kept)) |rows| inside: { - if (clicked.r0 < BOX_H) break :inside false; + if (clicked.r0 < pane.tag_rows) break :inside false; if (pane.file != null and clicked.c0 < panes.File.gutterWidth(pane)) break :inside false; const source_col: usize = @intCast(@max(0, col)); for (rows) |span| { @@ -155,7 +155,7 @@ pub fn pointerOperand(p: *Pardes, pane: *Pane, clicked: Pane.Sel) PointerOperand result.text = edit.currentSelText(p, pane); return result; } - if (pane.file != null and clicked.r0 >= BOX_H and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1) { + if (pane.file != null and clicked.r0 >= pane.tag_rows and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1) { const line = panes.File.sourceLine(pane, row); const source_col: usize = @intCast(@max(0, col)); const b = look.expandedWord(line, source_col) orelse return result; @@ -168,9 +168,9 @@ pub fn pointerOperand(p: *Pardes, pane: *Pane, clicked: Pane.Sel) PointerOperand const first = pane.wrapRow(row, lo); const last = pane.wrapRow(row, hi - 1); if (first.row >= 0 and last.row >= 0) { - expanded.r0 = first.row + @as(i32, BOX_H); + expanded.r0 = first.row + @as(i32, pane.tag_rows); expanded.c0 = @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayOffset(pane, row, first.at, lo); - expanded.r1 = last.row + @as(i32, BOX_H); + expanded.r1 = last.row + @as(i32, pane.tag_rows); expanded.c1 = @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayEndOffset(pane, row, last.at, hi - 1); } result.preview = expanded; diff --git a/src/gui/gui.zig b/src/gui/gui.zig index dfd528a3..140ca1db 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1842,6 +1842,7 @@ const Gui = struct { scroll_pane: ?usize = null, scroll_rect: pardes.Rect = .{ .x = 0, .y = 0, .w = 0, .h = 0 }, scroll_body_y: u16 = 0, // that rect's first BODY row (Tagbottom moves it) + scroll_body_h: u16 = 0, // and its BODY rows, which a taller tag leaves fewer of scroll_col: u16 = 0, // where the wheel turned: crossed rows are delivered scroll_row: u16 = 0, // THERE, not wherever the pointer has drifted to since scroll_delta: f32 = 0, // finite raw distance waiting for the render batch @@ -4460,11 +4461,11 @@ fn stepScroll(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { return; } const r = core.rects[id]; - if (r.h <= pardes.BOX_H) { + if (r.h <= pane.tag_rows) { resetScroll(g); return; } - const delta = boundScrollDelta(g.scroll_lag, queued_delta, r.h - pardes.BOX_H); + const delta = boundScrollDelta(g.scroll_lag, queued_delta, r.h - pane.tag_rows); const st = applyScrollDelta(g.scroll_lag, delta); var left = st.rows; while (left != 0) { @@ -4484,14 +4485,15 @@ fn stepScroll(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { } g.scroll_lag = st.lag; g.scroll_rect = r; - const body_y = core.bodyTop(r); + const body_y = core.bodyTop(pane, r); g.scroll_body_y = body_y; + g.scroll_body_h = r.h -| pane.tag_rows; if (st.rows != 0) { const s = &core.surface; g.scroll_edge_len = 0; - if (r.w > config.GUTTER and r.h > pardes.BOX_H and r.x + r.w <= s.cols) { + if (r.w > config.GUTTER and r.h > pane.tag_rows and r.x + r.w <= s.cols) { const bw = r.w - config.GUTTER; - const bh = r.h - pardes.BOX_H; + const bh = g.scroll_body_h; const k: u16 = @intCast(@min(@abs(st.rows), @as(i32, bh))); const srow = body_y + (if (st.rows > 0) k - 1 else bh - k); if (srow < s.rows) { @@ -4515,11 +4517,11 @@ fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pard for (surface.panelTracks()) |track| if (track.active() and track.pane == scroll_pane) return 0; const r = g.scroll_rect; - if (r.w <= config.GUTTER or r.h <= pardes.BOX_H) return 0; + const bh = g.scroll_body_h; + if (r.w <= config.GUTTER or bh == 0) return 0; const x0 = r.x + config.GUTTER; const y0 = g.scroll_body_y; const bw = r.w - config.GUTTER; - const bh = r.h - pardes.BOX_H; if (x0 + bw > surface.cols or y0 + bh > surface.rows) return 0; // resized under us var shifted = layout; shifted.y_off -= g.scroll_lag * layout.h; @@ -4553,7 +4555,7 @@ fn scrollScissor(g: *const Gui, layout: CellLayout, sw: u32, sh: u32) c.SDL_Rect const px = layout.x_off + @as(f32, @floatFromInt(r.x + config.GUTTER)) * layout.w; const py = layout.y_off + @as(f32, @floatFromInt(g.scroll_body_y)) * layout.h; const pw = @as(f32, @floatFromInt(r.w - config.GUTTER)) * layout.w; - const ph = @as(f32, @floatFromInt(r.h - pardes.BOX_H)) * layout.h; + const ph = @as(f32, @floatFromInt(g.scroll_body_h)) * layout.h; const x0 = std.math.clamp(@as(i32, @intFromFloat(@floor(px))), 0, @as(i32, @intCast(sw))); const y0 = std.math.clamp(@as(i32, @intFromFloat(@floor(py))), 0, @as(i32, @intCast(sh))); const x1 = std.math.clamp(@as(i32, @intFromFloat(@ceil(px + pw))), x0, @as(i32, @intCast(sw))); @@ -5617,8 +5619,9 @@ fn taglineBaseRgb(core: *const pardes.Pardes, col: u16, row: u16) [3]u8 { }; } const r = core.rects[core.active]; - const tag_y = if (core.settings.tag_bottom) r.y + r.h -| pardes.BOX_H else r.y; - return if (r.h > 0 and row == tag_y and col >= r.x and col - r.x < r.w) chrome.tag_active_bg else chrome.tag_bg; + const pane = core.panes[core.active] orelse return chrome.tag_bg; + const tag_y = core.tagTop(pane, r); + return if (r.h > 0 and row >= tag_y and row < tag_y + pane.tag_rows and col >= r.x and col - r.x < r.w) chrome.tag_active_bg else chrome.tag_bg; } test "compact column and pane underlays share focus tint without tinting the global tag" { @@ -7474,11 +7477,12 @@ fn appendPaneChrome( const chrome = core.chromeTheme(); const page = overlayRgb(core.theme().bg orelse bg_default); for (core.panes, core.rects) |slot, r| { - if (slot == null or r.w <= config.GUTTER or r.h <= pardes.BOX_H) continue; + const pane = slot orelse continue; + if (r.w <= config.GUTTER or r.h <= pane.tag_rows) continue; if (@as(u32, r.x) + r.w > surface.cols or @as(u32, r.y) + r.h > surface.rows) continue; - const tag_y = if (core.settings.tag_bottom) r.y + r.h - pardes.BOX_H else r.y; - const body_y = core.bodyTop(r); - const body_end = body_y + (r.h -| pardes.BOX_H); + const tag_y = core.tagTop(pane, r); + const body_y = core.bodyTop(pane, r); + const body_end = body_y + (r.h -| pane.tag_rows); const x0 = @as(f32, @floatFromInt(r.x)) * layout.w; const x1 = x0 + @as(f32, @floatFromInt(r.w)) * layout.w; const tag_cells = surface.cells[@as(usize, tag_y) * surface.cols + r.x + pardes.TAG_TEXT_INSET ..][0 .. r.w - pardes.TAG_TEXT_INSET]; @@ -7486,7 +7490,7 @@ fn appendPaneChrome( if (cellFontRole(cell) != .tagline) break false; } else true; if (tag_visible) { - const rule_y = @as(f32, @floatFromInt(tag_y + @as(u16, if (core.settings.tag_bottom) 0 else 1))) * layout.h; + const rule_y = @as(f32, @floatFromInt(tag_y + (if (core.settings.tag_bottom) 0 else pane.tag_rows))) * layout.h; // Like the band above it, the rule of a pane at the right edge // runs on through the pixels past the last whole cell. const rule_x1 = if (builder.win_w - x1 < layout.w) @max(x1, builder.win_w) else x1; diff --git a/src/look.zig b/src/look.zig index 6f9f8c6a..8aa2c0a1 100644 --- a/src/look.zig +++ b/src/look.zig @@ -483,7 +483,7 @@ pub fn expandedSel(p: *Pardes, pane: *Pane, at: Pane.Sel) ?Pane.Sel { /// coords: row 0 is the tag; file panes carry the line-number prefix) pub fn cursorWordSel(p: *Pardes, pane: *Pane) Pane.Sel { const w = pane.wrapRow(pane.body.cur_row, pane.body.cur_col); - const vrow = w.row + @as(i32, BOX_H); + const vrow = w.row + @as(i32, pane.tag_rows); const vcol = if (pane.file != null) panes.File.displayOffset(pane, pane.body.cur_row, w.at, pane.body.cur_col) + @as(i32, panes.File.gutterWidth(pane)) else blk: { diff --git a/src/mouse.zig b/src/mouse.zig index 343051b0..33646090 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -103,11 +103,11 @@ pub const ChromeTarget = struct { col: u16, row: u16 }; pub fn chromeTarget(p: *const Pardes, col: u16, row: u16) ?ChromeTarget { if (row < p.topBarHeight() + p.columnBarHeight()) return .{ .col = col, .row = row }; for (p.panes, 0..) |slot, id| { - if (slot == null) continue; + const pane = slot orelse continue; const rect = p.rects[id]; - const tag = if (p.settings.tag_bottom) rect.y + rect.h -| BOX_H else rect.y; - if (row == tag and col >= rect.x and col < rect.x + rect.w and col < rect.x + config.GUTTER) - return .{ .col = col, .row = tag }; + const tag = p.tagTop(pane, rect); + if (row >= tag and row < tag + pane.tag_rows and col >= rect.x and col < rect.x + rect.w and col < rect.x + config.GUTTER) + return .{ .col = col, .row = row }; } for (0..p.ncol -| 1) |column| { const handle = p.col_x[column] + p.col_w[column] -| 1; @@ -122,11 +122,11 @@ pub fn chromeTarget(p: *const Pardes, col: u16, row: u16) ?ChromeTarget { } } for (p.panes, 0..) |slot, id| { - if (slot == null) continue; + const pane = slot orelse continue; const rect = p.rects[id]; - const tag = if (p.settings.tag_bottom) rect.y + rect.h -| BOX_H else rect.y; - if (row == tag and col >= rect.x and col < rect.x + rect.w) - return .{ .col = col, .row = tag }; + const tag = p.tagTop(pane, rect); + if (row >= tag and row < tag + pane.tag_rows and col >= rect.x and col < rect.x + rect.w) + return .{ .col = col, .row = row }; } for (0..p.ncol -| 1) |column| { const handle = p.col_x[column] + p.col_w[column] -| 1; @@ -182,11 +182,13 @@ pub fn sameTagCell(a: ?TagHit, b: ?TagHit) bool { return first.kind == second.kind and first.id == second.id and first.serial == second.serial and first.col == second.col; } -pub fn tagColumn(p: *const Pardes, kind: TagKind, id: usize, supplied: ?TagHit, clamp: bool) ?u16 { +/// The tag column a host's pointer is at. Clamped, a point off the tag is +/// brought back onto line `line` of it, for a drag that leaves it. +pub fn tagColumn(p: *const Pardes, kind: TagKind, id: usize, supplied: ?TagHit, clamp: bool, line: u16) ?u16 { var point = supplied orelse return null; if (point.kind != kind or point.id != id) return null; if (clamp) for (p.surface.tagLayers()) |*layer| { - if (layer.cols == 0 or layer.kind != kind or layer.id != id or layer.serial != point.serial) continue; + if (layer.cols == 0 or layer.kind != kind or layer.id != id or layer.serial != point.serial or layer.line != line) continue; const bw: f32 = @floatFromInt(point.metrics.body_w); const bh: f32 = @floatFromInt(point.metrics.body_h); const left = @as(f32, @floatFromInt(layer.viewport.x)) * bw; @@ -298,7 +300,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { }; const x = if (p.header_column) |c| p.col_x[c] + TAG_TEXT_INSET else 0; const bar = modal.lineSlice(edit.flatSurface(p, t) catch return, 0); - const at = @min(bar.len, panes.File.rawAtDisplay(bar, (tagColumn(p, if (p.header_column != null) .column else .workspace, p.header_column orelse 0, p.pointer_tag_hit, p.header_drag) orelse (mcol -| x)) + p.header_scroll)); + const at = @min(bar.len, panes.File.rawAtDisplay(bar, (tagColumn(p, if (p.header_column != null) .column else .workspace, p.header_column orelse 0, p.pointer_tag_hit, p.header_drag, 0) orelse (mcol -| x)) + p.header_scroll)); // the anchor stays where the press put it t.cur_row = 0; t.cur_col = @intCast(at); @@ -330,7 +332,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { const focused = p.header_focus and p.header_column == column; const bar = modal.lineSlice(edit.flatSurface(p, t) catch return, 0); const scroll = if (focused) p.header_scroll else 0; - const at = @min(bar.len, panes.File.rawAtDisplay(bar, (tagColumn(p, if (column != null) .column else .workspace, column orelse 0, p.pointer_tag_hit, p.header_drag) orelse (mcol -| x)) + scroll)); + const at = @min(bar.len, panes.File.rawAtDisplay(bar, (tagColumn(p, if (column != null) .column else .workspace, column orelse 0, p.pointer_tag_hit, p.header_drag, 0) orelse (mcol -| x)) + scroll)); if (m.button == config.select_button) { // A clicked header is typed straight into, as a clicked tag is. if (!focused) p.enterHeader(column); @@ -417,8 +419,9 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { } if (hovered) |mid| { const mr = p.rects[mid]; - const mtag = if (p.settings.tag_bottom) mr.y + mr.h -| BOX_H else mr.y; - if (mcol < mr.x + config.GUTTER and mrow >= mtag and mrow < mtag + BOX_H) { + const mpane = p.panes[mid].?; + const mtag = p.tagTop(mpane, mr); + if (mcol < mr.x + config.GUTTER and mrow >= mtag and mrow < mtag + mpane.tag_rows) { p.drag = .{ .move = .{ .id = mid, .cur_x = mcol, .cur_y = mrow } }; return; } @@ -449,14 +452,14 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { previous.focus = .body; previous.closePrompt(); }; - const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; - const body_y = p.bodyTop(r); + const tag_y = p.tagTop(pane, r); + const body_y = p.bodyTop(pane, r); if (mcol < r.x + config.GUTTER) { // gutter scrollbar: a left click scrolls UP to that row p.active = id; pane.scrollBy(-(@as(i32, mrow) - @as(i32, body_y))); } else { - const on_tag = mrow >= tag_y and mrow < tag_y + BOX_H; + const on_tag = mrow >= tag_y and mrow < tag_y + pane.tag_rows; if (on_tag and mcol < r.x + TAG_TEXT_INSET) return; p.active = id; pane.closePrompt(); @@ -475,8 +478,9 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { pane.tag.msel.active = false; pane.tag.nsel = 0; pane.tag.cur_pinned = true; - pane.tag.cur_row = 0; - pane.tag.cur_col = @intCast(p.tagOffsetAt(pane, @intCast(@max(0, pointed.sel.c0))) orelse 0); + const at = p.tagOffsetAt(pane, @intCast(@max(0, pointed.sel.r0)), @intCast(@max(0, pointed.sel.c0))) orelse modal.Cursor{ .row = 0, .col = 0 }; + pane.tag.cur_row = @intCast(at.row); + pane.tag.cur_col = @intCast(at.col); } p.drag = .{ .select = .{ .id = id, @@ -524,9 +528,9 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { const pane = p.panes[id] orelse return; // the tag row and the body's first, exactly as the select // arm above derives them - const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; - const body_y = p.bodyTop(r); - const on_tag = mrow >= tag_y and mrow < tag_y + BOX_H; + const tag_y = p.tagTop(pane, r); + const body_y = p.bodyTop(pane, r); + const on_tag = mrow >= tag_y and mrow < tag_y + pane.tag_rows; if (mcol < r.x + config.GUTTER and !on_tag) { const local = @as(i32, mrow) - @as(i32, body_y); if (m.button == config.look_button) p.active = id; @@ -605,30 +609,37 @@ pub fn dragUpdate(p: *Pardes, mcol: u16, mrow: u16, body_hit: ?Mouse.BodyHit) vo if (p.panes[s.id]) |pane| { const r = p.rects[s.id]; const b = @intFromEnum(s.button); - if (pane.body_rows > 0 and pane.sel[b].r0 >= BOX_H) if (body_hit) |supplied| { + const tag_rows: i32 = pane.tag_rows; + if (pane.body_rows > 0 and pane.sel[b].r0 >= tag_rows) if (body_hit) |supplied| { const mapped_hit = bodyHitForPane(p, s.id, supplied, true) orelse return; pane.sel[b].c1 = @as(i32, mapped_hit.col) - config.GUTTER; - pane.sel[b].r1 = @as(i32, mapped_hit.row) + BOX_H; + pane.sel[b].r1 = @as(i32, mapped_hit.row) + tag_rows; return; }; - if (pane.sel[b].r0 < BOX_H) if (tagColumn(p, .pane, s.id, p.pointer_tag_hit, true)) |value| { + // A sweep that began on the tag stays on it, on the tag line + // nearest the pointer. + const tag_y = p.tagTop(pane, r); + const tag_line: u16 = @intCast(std.math.clamp(@as(i32, mrow) - @as(i32, tag_y), 0, tag_rows - 1)); + if (pane.sel[b].r0 < tag_rows) if (tagColumn(p, .pane, s.id, p.pointer_tag_hit, true, tag_line)) |value| { pane.sel[b].c1 = @as(i32, value) + pane.tag_scroll; - pane.sel[b].r1 = 0; + pane.sel[b].r1 = tag_line; return; }; pane.sel[b].c1 = @as(i32, mcol) - @as(i32, r.x + config.GUTTER); - // Sel row BOX_H is the body's FIRST row, the same thing + // Sel row tag_rows is the body's FIRST row, the same thing // pointerTextSelection means by it -- so the drag has to // measure from the body's top, notice bands included, or a // selection made while a message is up lands rows away // from the pointer. - const body_y = p.bodyTop(r); - const body_h = r.h -| BOX_H; - pane.sel[b].r1 = if (pane.sel[b].r0 < BOX_H or body_h == 0) + const body_y = p.bodyTop(pane, r); + const body_h = r.h -| pane.tag_rows; + pane.sel[b].r1 = if (pane.sel[b].r0 < tag_rows) + tag_line + else if (body_h == 0) 0 else - @as(i32, @min(@max(mrow, body_y), body_y + body_h - 1)) - @as(i32, body_y) + @as(i32, BOX_H); - if (pane.sel[b].r1 < BOX_H) pane.sel[b].c1 += @as(i32, pane.tag_scroll) - TAG_GAP; + @as(i32, @min(@max(mrow, body_y), body_y + body_h - 1)) - @as(i32, body_y) + tag_rows; + if (pane.sel[b].r1 < tag_rows) pane.sel[b].c1 += @as(i32, pane.tag_scroll) - TAG_GAP; if (comptime pdf_enabled) panes.Pdf.pointerUpdate(&s.pdf, p, pane, mcol, mrow); } @@ -668,8 +679,10 @@ fn gestureRange(p: *Pardes, id: usize, text: []const u8, on_tag: bool, operand: if (on_tag) { const tag = p.tagText(p.scratch.allocator(), pane) catch return .{}; const sel = operand.expanded orelse operand.preview orelse return .{}; - const lead = @min(sel.c0, sel.c1); - const at = panes.File.rawAtDisplay(tag, @intCast(@max(0, lead))); + const lead = if (sel.r0 < sel.r1 or (sel.r0 == sel.r1 and sel.c0 <= sel.c1)) sel else Pane.Sel{ .r0 = sel.r1, .c0 = sel.c1 }; + const row: usize = @intCast(@max(0, lead.r0)); + const start = modal.lineStartOffset(tag, row); + const at = start + panes.File.rawAtDisplay(modal.lineSlice(tag, row), @intCast(@max(0, lead.c0))); const q0: u32 = @intCast(@min(at, tag.len)); return .{ .q0 = q0, .q1 = @intCast(@min(q0 + text.len, tag.len)) }; } @@ -692,7 +705,7 @@ fn gestureRange(p: *Pardes, id: usize, text: []const u8, on_tag: bool, operand: else if (operand.expanded orelse operand.preview) |sel| lead: { // A selection's leading corner in reading order, converted the way // `pointerOperand` converts the click itself. - const top = @min(sel.r0, sel.r1) - @as(i32, BOX_H); + const top = @min(sel.r0, sel.r1) - @as(i32, pane.tag_rows); if (top < 0) break :lead null; const w = pane.wrapAt(top); const col = edit.paneByteAtDisplay(p, &pane.body, w.line, w.at, @min(sel.c0, sel.c1) - panes.File.gutterWidth(pane)); @@ -825,19 +838,19 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { const sl = pane.sel[sel_slot]; const dragged = sl.c0 != sl.c1 or sl.r0 != sl.r1; if (!dragged) pane.sel[sel_slot].state = .none; - if (sl.r0 < BOX_H) { + if (sl.r0 < pane.tag_rows) { // On the tag the caret goes where the button came up. A // click on the path, if it can be renamed, drafts a name. - const at = p.tagOffsetAt(pane, @intCast(@max(0, sl.c1))); - if (at) |col| { - pane.tag.cur_row = 0; - pane.tag.cur_col = @intCast(col); + const at = p.tagOffsetAt(pane, @intCast(@max(0, sl.r1)), @intCast(@max(0, sl.c1))); + if (at) |cursor| { + pane.tag.cur_row = @intCast(cursor.row); + pane.tag.cur_col = @intCast(cursor.col); } else if (!dragged) p.draftName(pane, @intCast(@max(0, sl.c1))); return; } if (dragged) edit.capturePointerSelection(p, pane, sel_slot) catch {}; if (dragged and pane.body.mode == .tty) mirrorTtySelection(p, pane); - const body_vis = sl.r1 - @as(i32, BOX_H); + const body_vis = sl.r1 - @as(i32, pane.tag_rows); if (body_vis >= 0 and pane.body.mode != .tty) { const w = pane.wrapAt(body_vis); pane.body.cur_row = w.line; @@ -864,10 +877,10 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { // A right-click on a line NUMBER looks at that line of // this file -- a sticky context header's number included, // since the row map holds each header's own source line. - if (s.button == config.look_button and clk.r0 >= BOX_H and clk.r0 == clk.r1 and + if (s.button == config.look_button and clk.r0 >= pane.tag_rows and clk.r0 == clk.r1 and clk.c0 == clk.c1 and clk.c0 >= 0 and pane.body.mode != .tty) if (pane.file) |f| if (f.output == null and clk.c0 < panes.File.gutterWidth(pane)) { - const line = pane.wrapAt(clk.r0 - BOX_H).line; + const line = pane.wrapAt(clk.r0 - pane.tag_rows).line; if (line >= 0) { pane.sel[b].state = .none; var buf: [48]u8 = undefined; @@ -881,14 +894,14 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { pane.sel[b] = expanded else if (operand.text == null) pane.sel[b].state = .none; - if (s.button == config.look_button and clk.r0 >= BOX_H and pane.body.mode != .tty) { + if (s.button == config.look_button and clk.r0 >= pane.tag_rows and pane.body.mode != .tty) { pane.body.cur_row = operand.row; pane.body.cur_col = operand.col; if (edit.clampFileCursor(&pane.body)) pane.ensureCursorVisible(); } const txt = operand.text; const cmd = if (s.button == config.look_button) config.look_cmd else config.exec_cmd; - if (clk.r0 < BOX_H and s.button == config.exec_button and pane.prompt == .name) { + if (clk.r0 == 0 and s.button == config.exec_button and pane.prompt == .name) { const prefix_width = panes.File.displayWidth(p.tagPrefix(pane) catch return); const on_name = @as(usize, @intCast(@max(0, clk.c0))) < prefix_width; if (!p.commitTagName(pane)) return; @@ -909,7 +922,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { pane.sel[b].c1 += shift; } dispatchPointerBuiltin(p, s.id, cmd, txt, .{ - .on_tag = clk.r0 < BOX_H, + .on_tag = clk.r0 < pane.tag_rows, .operand = operand, }); } @@ -931,7 +944,7 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { if (cut and pv.selection_text.len > 0) edit.setYank(p, pv.selection_text); return; }; - if (@min(pane.sel[sel_slot].r0, pane.sel[sel_slot].r1) < BOX_H) { + if (@min(pane.sel[sel_slot].r0, pane.sel[sel_slot].r1) < pane.tag_rows) { // A sweep over the tag cuts from and pastes into the tag's own text; // the part of it over the prefix is not the tag's to cut. const t = &pane.tag; @@ -939,12 +952,16 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { s.chorded = true; const sl = pane.sel[sel_slot]; pane.sel[sel_slot].state = .none; - const from = p.tagOffsetAt(pane, @intCast(@max(0, @min(sl.c0, sl.c1)))) orelse 0; - const to = p.tagOffsetAt(pane, @intCast(@max(0, @max(sl.c0, sl.c1)))) orelse 0; - t.cur_row = 0; - t.cur_col = @intCast(to); + const forward = sl.r0 < sl.r1 or (sl.r0 == sl.r1 and sl.c0 <= sl.c1); + const start = if (forward) .{ sl.r0, sl.c0 } else .{ sl.r1, sl.c1 }; + const end = if (forward) .{ sl.r1, sl.c1 } else .{ sl.r0, sl.c0 }; + const origin: modal.Cursor = .{ .row = 0, .col = 0 }; + const from = p.tagOffsetAt(pane, @intCast(@max(0, start[0])), @intCast(@max(0, start[1]))) orelse origin; + const to = p.tagOffsetAt(pane, @intCast(@max(0, end[0])), @intCast(@max(0, end[1]))) orelse origin; + t.cur_row = @intCast(to.row); + t.cur_col = @intCast(to.col); t.cur_pinned = true; - t.vsel = .{ .active = from != to, .row = 0, .col = @intCast(from), .explicit = false }; + t.vsel = .{ .active = from.row != to.row or from.col != to.col, .row = @intCast(from.row), .col = @intCast(from.col), .explicit = false }; t.msel.active = false; t.nsel = 0; } @@ -965,7 +982,7 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { if (y.len == 0) return; if (panes.Terminal.reportsMouse(pane)) { const col: u16 = @intCast(std.math.clamp(pane.sel[sel_slot].c1 + 1, 1, 9999)); - const row: u16 = @intCast(std.math.clamp(pane.sel[sel_slot].r1 - @as(i32, BOX_H) + 1, 1, 9999)); + const row: u16 = @intCast(std.math.clamp(pane.sel[sel_slot].r1 - @as(i32, pane.tag_rows) + 1, 1, 9999)); var mb: [32]u8 = undefined; if (panes.Terminal.mouseFormatSgr(pane)) { p.emitWrite(s.id, std.fmt.bufPrint(&mb, "\x1b[<0;{d};{d}M\x1b[<0;{d};{d}m", .{ col, row, col, row }) catch return); @@ -986,8 +1003,8 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { const pfx: i32 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; // both ends of the sweep through the same last-frame map, so a // chord over wrapped rows cuts the text that was under it - const w0 = pane.wrapAt(@max(0, sl.r0 - @as(i32, BOX_H))); - const w1 = pane.wrapAt(@max(0, sl.r1 - @as(i32, BOX_H))); + const w0 = pane.wrapAt(@max(0, sl.r0 - @as(i32, pane.tag_rows))); + const w1 = pane.wrapAt(@max(0, sl.r1 - @as(i32, pane.tag_rows))); const row0 = w0.line; const row1 = w1.line; const col0 = edit.paneByteAtDisplay(p, &pane.body, w0.line, w0.at, sl.c0 - pfx); diff --git a/src/panes.zig b/src/panes.zig index 720f655f..6887008c 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -25,7 +25,7 @@ pub const EditText = struct { text: []u8, row0: i32 }; pub const Pane = struct { /// One mouse selection (block-shaped), per button. c/r are text-area relative; - /// r counts from the tag row (body starts at BOX_H). + /// r counts from the tag's first row (the body starts at Pane.tag_rows). pub const Sel = struct { state: enum { none, dragging, done } = .none, source_id: u64 = 0, @@ -121,6 +121,10 @@ pub const Pane = struct { focus: Focus = .body, /// Display columns hidden to reveal the tag caret; tag addresses stay whole. tag_scroll: u16 = 0, + /// Rows the tag takes on screen: one per line of it, as many as the pane + /// has room for with a body row to spare. Set with the geometry in sync. + /// Pointer rows count from the tag's first, so a body starts at this one. + tag_rows: u16 = 1, cwd: Cwd = .none, hscroll: i32 = 0, // Visible rows map to source lines and raw/display column origins. diff --git a/src/pardes.zig b/src/pardes.zig index 60c41f50..72a282c2 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -249,8 +249,13 @@ pub const TagLayer = @import("tag_layer.zig").Layer; pub const TagHit = @import("tag_layer.zig").Hit; pub const TagKind = @import("tag_layer.zig").Kind; /// Panes, then columns, then the workspace bar, then each pane's notice bands. -pub const MAX_TAG_LAYERS = MAX_PANES + MAX_COLS + 1 + MAX_PANES * Pane.Notices.max; +/// A tag shows at most this many lines; past them it is cut, like a line +/// too long for its width. +pub const MAX_TAG_ROWS = 8; +pub const MAX_TAG_LAYERS = MAX_PANES + MAX_COLS + 1 + MAX_PANES * Pane.Notices.max + MAX_PANES * (MAX_TAG_ROWS - 1); pub const NOTICE_LAYER_BASE = MAX_PANES + MAX_COLS + 1; +/// Where the layers for a pane tag's second and later lines start. +pub const TAG_LINE_LAYER_BASE = NOTICE_LAYER_BASE + MAX_PANES * Pane.Notices.max; pub const PDF_PAGE_GAP_PX = panes.Pdf.page_gap_px; pub const MAX_COLS = 6; const column_weight_unit = layout.column_weight_unit; @@ -285,16 +290,17 @@ pub fn taglineOriginCol(p: *const Pardes, col: u16, row: u16, track: ?layout.Tra } if (track) |active| { const box = active.contentBox(); - const tag_y = if (p.settings.tag_bottom) box.y + box.h - @as(f32, @floatFromInt(BOX_H)) else box.y; + const rows: f32 = @floatFromInt(if (active.pane < MAX_PANES) if (p.panes[active.pane]) |pane| pane.tag_rows else BOX_H else BOX_H); + const tag_y = if (p.settings.tag_bottom) box.y + box.h - rows else box.y; if (@as(f32, @floatFromInt(row)) >= tag_y and - @as(f32, @floatFromInt(row)) < tag_y + @as(f32, @floatFromInt(BOX_H))) + @as(f32, @floatFromInt(row)) < tag_y + rows) return box.x; } for (p.panes, 0..) |slot, id| { - if (slot == null) continue; + const pane = slot orelse continue; const r = p.rects[id]; - const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; - if (row == tag_y and col >= r.x and col < r.x + r.w) return @floatFromInt(r.x); + const tag_y = p.tagTop(pane, r); + if (row >= tag_y and row < tag_y + pane.tag_rows and col >= r.x and col < r.x + r.w) return @floatFromInt(r.x); } return @floatFromInt(col); } @@ -352,10 +358,10 @@ pub fn gridColAt(p: ?*const Pardes, x: f32, row: u16, body_w: f32, tagline_w: f3 } }; if (p) |core| for (core.panes, 0..) |slot, id| { - if (slot == null) continue; + const pane = slot orelse continue; const r = core.rects[id]; - const tag_y = if (core.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; - if (row != tag_y or r.w == 0) continue; + const tag_y = core.tagTop(pane, r); + if (row < tag_y or row >= tag_y + pane.tag_rows or r.w == 0) continue; const left = @as(f32, @floatFromInt(r.x)) * body; const right = @as(f32, @floatFromInt(r.x + r.w)) * body; if (x < left or x >= right) continue; @@ -813,7 +819,7 @@ test "TreeContext tag style preserves message rows and its opt-out survives rest const band = for (p.surface.tagLayers()) |*layer| { if (layer.cols != 0 and layer.kind == .notice) break layer; } else return error.NoNoticeBand; - try std.testing.expectEqual(p.bodyTop(r), band.viewport.y); + try std.testing.expectEqual(p.bodyTop(pane, r), band.viewport.y); try std.testing.expectEqual(p.surface.body_layers[0].viewport.y, band.viewport.y); // Sized to its message, flush with the pane's right edge, and the text // right aligned a cell short of that edge. @@ -829,7 +835,7 @@ test "TreeContext tag style preserves message rows and its opt-out survives rest _ = try p.render(p.scratch.allocator()); try std.testing.expectEqual(@as(u16, 0), p.surface.body_layers[0].rows); try std.testing.expectEqual(@as(u16, 0), pane.body_rows); - try std.testing.expectEqual(FontRole.body, p.surface.at(r.x + config.GUTTER, p.bodyTop(r)).style.font_role); + try std.testing.expectEqual(FontRole.body, p.surface.at(r.x + config.GUTTER, p.bodyTop(pane, r)).style.font_role); try dump.dumpState(p); const restored = try dump.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); defer restored.deinit(); @@ -4915,15 +4921,14 @@ pub const Pardes = struct { pane.focus = .tag; } - /// Where display column `col` of the tagline (tag scroll included) lands - /// in the tag's own text, or null when it is on the prefix. - pub fn tagOffsetAt(p: *Pardes, pane: *Pane, col: usize) ?usize { - const prefix = p.tagPrefix(pane) catch return null; - const width = panes.File.displayWidth(prefix); + /// Where display column `col` of tag line `row` (tag scroll included) + /// lands in the tag's own text, or null when it is on the prefix, which + /// only the first line has. + pub fn tagOffsetAt(p: *Pardes, pane: *Pane, row: usize, col: usize) ?modal.Cursor { + const width = if (row == 0) panes.File.displayWidth(p.tagPrefix(pane) catch return null) else 0; if (col < width) return null; - const tail = curTail(pane); - const line = tail[0 .. std.mem.indexOfScalar(u8, tail, '\n') orelse tail.len]; - return modal.graphemeStart(line, panes.File.rawAtDisplay(line, col - width)); + const line = modal.lineSlice(curTail(pane), row); + return .{ .row = row, .col = modal.graphemeStart(line, panes.File.rawAtDisplay(line, col - width)) }; } /// Start a name draft for a file that can take one, its caret at display @@ -5822,7 +5827,7 @@ pub const Pardes = struct { } // A sweep over the tag is the tag's while it has the keyboard. const swept = pane.sel[sel_slot]; - if (pane.focus == .body and swept.state == .done and @min(swept.r0, swept.r1) < BOX_H) { + if (pane.focus == .body and swept.state == .done and @min(swept.r0, swept.r1) < pane.tag_rows) { pane.clearPointerSelection(sel_slot); pane.sel[sel_slot].state = .none; } @@ -5836,9 +5841,14 @@ pub const Pardes = struct { state.reply_len = 0; }; const r = p.rects[id]; + // The tag takes a row per line, leaving the body one row if it + // had any; a folded pane shows its first line only. + const lines = std.mem.count(u8, curTail(pane), "\n") + 1; + pane.tag_rows = @intCast(@min(lines, MAX_TAG_ROWS, @max(BOX_H, r.h -| 1))); + if (pane.collapsed) pane.tag_rows = BOX_H; const cols = @max(1, r.w -| config.GUTTER); - const rows = @max(1, r.h -| BOX_H); // the tag steals the top row - if ((cols != pane.cols or rows != pane.rows) and r.h > BOX_H) { + const rows = @max(1, r.h -| pane.tag_rows); // the tag steals the top rows + if ((cols != pane.cols or rows != pane.rows) and r.h > pane.tag_rows) { // doc panes have no pty/emulator grid to reflow; just record // the size so bodyText renders the right number of rows if (pane.isTerminal()) { @@ -5905,7 +5915,8 @@ pub const Pardes = struct { if (pane.serial != layer.serial) return null; } if (layer.kind == .column and (layer.id >= p.ncol or p.col_serial[layer.id] != layer.serial)) return null; - return layer.hitAt(tag_hit.pixel_x, tag_hit.pixel_y, @floatFromInt(tag_hit.metrics.body_w), @floatFromInt(tag_hit.metrics.body_h), @floatFromInt(tag_hit.metrics.tagline_w), @floatFromInt(tag_hit.metrics.tagline_h)); + // A taller tag has a layer per line; the point is on one of them. + return layer.hitAt(tag_hit.pixel_x, tag_hit.pixel_y, @floatFromInt(tag_hit.metrics.body_w), @floatFromInt(tag_hit.metrics.body_h), @floatFromInt(tag_hit.metrics.tagline_w), @floatFromInt(tag_hit.metrics.tagline_h)) orelse continue; } return null; } @@ -5913,8 +5924,13 @@ pub const Pardes = struct { /// The pane's first body row: under the tag when it is on top, over it /// when it is at the bottom. Notice bands do NOT move it -- they are an /// overlay, drawn over the top rows rather than taking them. - pub fn bodyTop(p: *const Pardes, r: Rect) u16 { - return if (p.settings.tag_bottom) r.y else r.y + BOX_H; + pub fn bodyTop(p: *const Pardes, pane: *const Pane, r: Rect) u16 { + return if (p.settings.tag_bottom) r.y else r.y + pane.tag_rows; + } + + /// The tag's first row: the pane's top, or its last rows with Tagbottom. + pub fn tagTop(p: *const Pardes, pane: *const Pane, r: Rect) u16 { + return if (p.settings.tag_bottom) r.y + r.h -| pane.tag_rows else r.y; } fn tagCapacity(p: *const Pardes, physical_width: u16) u16 { @@ -6005,7 +6021,7 @@ pub const Pardes = struct { // taken out of the body the way a tree-sitter context header is. // The chip is as wide as its own message and no wider, so the text // beneath the rest of the row keeps reading as the file it is. - const first = p.bodyTop(r); + const first = p.bodyTop(pane, r); var leader_buf: [16]u8 = undefined; for (pane.notices.slice(), 0..) |kind, i| { const row = first + @as(u16, pane.notices.row[i]); @@ -6385,26 +6401,41 @@ pub const Pardes = struct { const r = p.rects[id]; if (r.w <= TAG_TEXT_INSET or r.h == 0) continue; const tag = try p.tagText(arena, pane); - const columns: u16 = @intCast(@min(std.math.maxInt(u16) - TAG_TEXT_INSET, @max(p.tagCapacity(r.w - TAG_TEXT_INSET), panes.File.displayWidth(tag) + 1))); - const layer = &p.surface.tag_layers[id]; - if (layer.cells.len != columns) layer.cells = try p.gpa.realloc(layer.cells, columns); - const storage = try arena.alloc(Cell, @as(usize, columns) + TAG_TEXT_INSET); + const rows = pane.tag_rows; + // As wide as the widest line it shows, and never narrower than + // its viewport. + var widest: usize = 0; + var split = std.mem.splitScalar(u8, tag, '\n'); + for (0..rows) |_| widest = @max(widest, panes.File.displayWidth(split.next() orelse "")); + const columns: u16 = @intCast(@min(std.math.maxInt(u16) - TAG_TEXT_INSET, @max(p.tagCapacity(r.w - TAG_TEXT_INSET), widest + 1))); + const pitch = @as(usize, columns) + TAG_TEXT_INSET; + const storage = try arena.alloc(Cell, pitch * rows); @memset(storage, .{}); - var temporary: Surface = .{ .cols = columns + TAG_TEXT_INSET, .rows = 1, .cells = storage }; + var temporary: Surface = .{ .cols = columns + TAG_TEXT_INSET, .rows = rows, .cells = storage }; std.mem.swap(Surface, &p.surface, &temporary); - p.paintPaneTag(arena, pane, .{ .x = 0, .y = 0, .w = columns + TAG_TEXT_INSET, .h = 1 }, id, id == p.active, p.tagCapacity(r.w - TAG_TEXT_INSET)) catch |err| { + p.paintPaneTag(arena, pane, .{ .x = 0, .y = 0, .w = columns + TAG_TEXT_INSET, .h = rows }, id, id == p.active, p.tagCapacity(r.w - TAG_TEXT_INSET)) catch |err| { std.mem.swap(Surface, &p.surface, &temporary); return err; }; std.mem.swap(Surface, &p.surface, &temporary); - @memcpy(layer.cells, storage[TAG_TEXT_INSET..]); - layer.kind = .pane; - layer.id = @intCast(id); - layer.serial = pane.serial; - layer.viewport = .{ .x = r.x + TAG_TEXT_INSET, .y = if (p.settings.tag_bottom) r.y + r.h - BOX_H else r.y, .w = r.w - TAG_TEXT_INSET, .h = BOX_H }; - layer.cols = columns; - layer.bg = if (id == p.active and p.settings.focus_tint) chrome.tag_active_bg else chrome.tag_bg; - layer.cursor = if (!p.header_focus and temporary.cursor != null) .{ .col = temporary.cursor.?.x - TAG_TEXT_INSET, .bar = temporary.cursor.?.bar } else null; + // A layer to a line: the first in the pane's own slot, the rest + // in the slots kept for the lines of taller tags. + for (0..rows) |line| { + const layer = &p.surface.tag_layers[if (line == 0) id else TAG_LINE_LAYER_BASE + id * (MAX_TAG_ROWS - 1) + line - 1]; + if (layer.cells.len != columns) layer.cells = try p.gpa.realloc(layer.cells, columns); + @memcpy(layer.cells, storage[line * pitch + TAG_TEXT_INSET ..][0..columns]); + layer.kind = .pane; + layer.id = @intCast(id); + layer.serial = pane.serial; + layer.line = @intCast(line); + layer.viewport = .{ .x = r.x + TAG_TEXT_INSET, .y = p.tagTop(pane, r) + @as(u16, @intCast(line)), .w = r.w - TAG_TEXT_INSET, .h = BOX_H }; + layer.cols = columns; + layer.bg = if (id == p.active and p.settings.focus_tint) chrome.tag_active_bg else chrome.tag_bg; + layer.cursor = if (p.header_focus) null else if (temporary.cursor) |cursor| + (if (cursor.y == line) .{ .col = cursor.x - TAG_TEXT_INSET, .bar = cursor.bar } else null) + else + null; + } } // With the workspace tag row handed to native chrome there is no // workspace layer to render; the menu bar carries its commands. @@ -6422,8 +6453,8 @@ pub const Pardes = struct { for (p.panes, 0..) |slot, id| { const pane = slot orelse continue; const r = p.rects[id]; - if (r.w <= TAG_TEXT_INSET or r.h <= BOX_H) continue; - const first = p.bodyTop(r); + if (r.w <= TAG_TEXT_INSET or r.h <= pane.tag_rows) continue; + const first = p.bodyTop(pane, r); var leader_buf: [16]u8 = undefined; for (pane.notices.slice(), 0..) |kind, i| { const text = Messages.noticeText(p, pane, i, &leader_buf); @@ -6556,8 +6587,8 @@ pub const Pardes = struct { const chrome = p.chromeTheme(); const tx = r.x + config.GUTTER; // text area (tag + body), right of the gutter const tw = r.w - config.GUTTER; - const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; - const body_y = p.bodyTop(r); + const tag_y = p.tagTop(pane, r); + const body_y = p.bodyTop(pane, r); const pane_bg: Color = if (th.bg) |c| .{ .rgb = c } else .default; // text area resets to terminal-default cells (vaxis clear semantics); @@ -6579,7 +6610,7 @@ pub const Pardes = struct { // Grips keep physical grid dimensions, independently of tag text. .font_role = .tagline, }; - s.fill(r.x, tag_y, config.GUTTER, BOX_H, box_style); + s.fill(r.x, tag_y, config.GUTTER, pane.tag_rows, box_style); s.set(r.x, tag_y, switch (pane.body.mode) { .normal => config.tag_normal, .insert => config.tag_insert, @@ -6600,14 +6631,13 @@ pub const Pardes = struct { // GUI's image pass, kitty's z-order), so a chip over it would be // painted out. Text gets the overlay; a picture gives up the rows. const shown = pane.notices.span(); - const image_h = (r.h -| BOX_H) -| shown; + const image_h = (r.h -| pane.tag_rows) -| shown; panes.Image.draw(p, iv, @intCast(id), pane.serial, tx, body_y + shown, tw, image_h); // thumbless, but the same one column as the real scrollbar below — // that is the whole point of drawing it, and like that one it runs // past the notice bands so the gutter has no notch in it - const rail_y = if (p.settings.tag_bottom) r.y else r.y + BOX_H; - s.fill(r.x, rail_y, 1, r.h -| BOX_H, .{ .bg = .{ .rgb = chrome.scroll_track } }); - s.fill(r.x + 1, rail_y, 1, r.h -| BOX_H, .{ .bg = pane_bg }); + s.fill(r.x, body_y, 1, r.h -| pane.tag_rows, .{ .bg = .{ .rgb = chrome.scroll_track } }); + s.fill(r.x + 1, body_y, 1, r.h -| pane.tag_rows, .{ .bg = pane_bg }); return; } @@ -6620,8 +6650,9 @@ pub const Pardes = struct { const chrome = p.chromeTheme(); const tx = r.x + @min(TAG_TEXT_INSET, r.w); const tw = r.w -| TAG_TEXT_INSET; - const tag_y = if (p.settings.tag_bottom) r.y + r.h -| BOX_H else r.y; - const body_y = p.bodyTop(r); + const tag_y = p.tagTop(pane, r); + const body_y = p.bodyTop(pane, r); + const rows = pane.tag_rows; const page_rgb = th.bg orelse th.tag_bg; // Focus is visible along the tag without changing its live text grid. const tag_bg = if (active and p.settings.focus_tint) chrome.tag_active_bg else chrome.tag_bg; @@ -6629,44 +6660,53 @@ pub const Pardes = struct { const tag_style: CellStyle = .{ .fg = .{ .rgb = tag_fg }, .bg = .{ .rgb = tag_bg }, .font_role = .tagline }; // Padding belongs to the same font row but keeps its default ink: a // role must not manufacture a foreground color for blank cells. - s.fill(r.x + config.GUTTER, tag_y, @min(TAG_GAP, r.w -| config.GUTTER), BOX_H, .{ .bg = .{ .rgb = tag_bg }, .font_role = .tagline }); - s.fill(tx, tag_y, tw, BOX_H, .{ + s.fill(r.x + config.GUTTER, tag_y, @min(TAG_GAP, r.w -| config.GUTTER), rows, .{ .bg = .{ .rgb = tag_bg }, .font_role = .tagline }); + s.fill(tx, tag_y, tw, rows, .{ .bg = .{ .rgb = tag_bg }, .font_role = .tagline, }); const whole = try p.tagText(arena, pane); const tail = curTail(pane); const prefix_len = whole.len - tail.len; - // The tagline shows the tag's first line: its prefix and the first - // line of its own text. - const tag = whole[0 .. std.mem.indexOfScalar(u8, whole, '\n') orelse whole.len]; - // The keyboard's caret on it, as a byte offset: in its own text when - // the tag has the keyboard, in the path while a name is drafted. - const caret_at: ?usize = if (!active) + // A row per line: the first carries the prefix, the rest are the + // tag's own text alone. + var lines: [MAX_TAG_ROWS][]const u8 = @splat(""); + var split = std.mem.splitScalar(u8, whole, '\n'); + for (lines[0..rows]) |*line| line.* = split.next() orelse ""; + // The keyboard's caret, as a row and a byte offset in that row's + // line: in the tag's own text when the tag has the keyboard, in the + // path while a name is drafted. + const Caret = struct { row: usize, at: usize }; + const caret: ?Caret = if (!active) null else if (pane.prompt == .name) - @min(tag.len, @as(usize, @intCast(@max(0, pane.input.cur_col)))) - else if (pane.focus == .tag and pane.tag.cur_row == 0) - @min(tag.len, prefix_len + @as(usize, @intCast(@max(0, pane.tag.cur_col)))) - else - null; - if (caret_at) |at| { - const caret = panes.File.rawDisplayCol(tag, at); + .{ .row = 0, .at = @min(lines[0].len, @as(usize, @intCast(@max(0, pane.input.cur_col)))) } + else if (pane.focus == .tag and pane.tag.cur_row < rows) caret: { + const row: usize = @intCast(@max(0, pane.tag.cur_row)); + const lead: usize = if (row == 0) prefix_len else 0; + break :caret .{ .row = row, .at = @min(lines[row].len, lead + @as(usize, @intCast(@max(0, pane.tag.cur_col)))) }; + } else null; + if (caret) |at| { + const line = lines[at.row]; + const col = panes.File.rawDisplayCol(line, at.at); var scroll: usize = pane.tag_scroll; - if (caret < scroll) scroll = caret; - if (caret >= scroll + capacity) scroll = caret - capacity + 1; - var raw = panes.File.rawAtDisplay(tag, scroll); - scroll = panes.File.rawDisplayCol(tag, raw); - if (caret >= scroll + capacity) { - raw = modal.nextGrapheme(tag, raw); - scroll = panes.File.rawDisplayCol(tag, raw); + if (col < scroll) scroll = col; + if (col >= scroll + capacity) scroll = col - capacity + 1; + var raw = panes.File.rawAtDisplay(line, scroll); + scroll = panes.File.rawDisplayCol(line, raw); + if (col >= scroll + capacity) { + raw = modal.nextGrapheme(line, raw); + scroll = panes.File.rawDisplayCol(line, raw); } pane.tag_scroll = @intCast(scroll); } else if (pane.focus != .tag) pane.tag_scroll = 0; - const tag_start = panes.File.rawAtDisplay(tag, pane.tag_scroll); - _ = s.print(tx, tag_y, tw, tag[tag_start..], tag_style); + for (lines[0..rows], 0..) |line, row| { + const start = panes.File.rawAtDisplay(line, pane.tag_scroll); + _ = s.print(tx, tag_y + @as(u16, @intCast(row)), tw, line[start..], tag_style); + } + const tag = lines[0]; if (tagTintRange(pane, tag, prefix_len)) |name| { - const lo = @max(name.lo, tag_start); + const lo = @max(name.lo, panes.File.rawAtDisplay(tag, pane.tag_scroll)); const hi = @min(name.hi, tag.len); if (lo < hi) { var col = panes.File.rawDisplayCol(tag, lo) -| pane.tag_scroll; @@ -6677,41 +6717,50 @@ pub const Pardes = struct { } } if (p.look_hover_preview) |preview| { - if (preview.pane == id and preview.serial == pane.serial) if (preview.sel) |sel| if (@min(sel.r0, sel.r1) < BOX_H) { + if (preview.pane == id and preview.serial == pane.serial) if (preview.sel) |sel| if (@min(sel.r0, sel.r1) < rows) { const preview_bg = colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)); body_layer.paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, sel, preview_bg, null); }; } - // The tag's own selections, while it has the keyboard. A range of one - // grapheme is the block cursor, not a selection. + // The tag's own selections, while it has the keyboard, a line at a + // time. A range of one grapheme is the block cursor, not a selection. if (pane.focus == .tag) { var ranges: [Text.max_selections]modal.Selection = undefined; const got = pane.tag.ranges(tail, 0, &ranges); - const shown = tag.len - prefix_len; for (ranges[0..got.n]) |range| { const lo = @min(range.anchor, range.head); const hi = @max(range.anchor, range.head); - if (modal.nextGrapheme(tail, lo) >= hi or lo >= shown) continue; - var col = panes.File.rawDisplayCol(tag, prefix_len + lo) -| pane.tag_scroll; - const end = panes.File.rawDisplayCol(tag, prefix_len + @min(hi, shown)); - while (col + pane.tag_scroll < end and col < tw) : (col += 1) { - const cell = s.at(tx + @as(u16, @intCast(col)), tag_y); - cell.default = false; - cell.style.bg = .{ .rgb = th.sel_bg }; - cell.style.fg = .{ .rgb = th.sel_fg }; + if (modal.nextGrapheme(tail, lo) >= hi) continue; + const first = modal.positionAt(tail, lo); + const last = modal.positionAt(tail, hi); + var row = first.row; + while (row <= last.row and row < rows) : (row += 1) { + const line = lines[row]; + const lead: usize = if (row == 0) prefix_len else 0; + const from = lead + if (row == first.row) first.col else 0; + const to = @min(line.len, lead + if (row == last.row) last.col else modal.lineSlice(tail, row).len); + var col = panes.File.rawDisplayCol(line, from) -| pane.tag_scroll; + const end = panes.File.rawDisplayCol(line, to); + const y = tag_y + @as(u16, @intCast(row)); + while (col + pane.tag_scroll < end and col < tw) : (col += 1) { + const cell = s.at(tx + @as(u16, @intCast(col)), y); + cell.default = false; + cell.style.bg = .{ .rgb = th.sel_bg }; + cell.style.fg = .{ .rgb = th.sel_fg }; + } } } } // the caret: bar while typing, block in normal mode (same rule as a body) - if (caret_at) |at| { - const col = panes.File.rawDisplayCol(tag, at) -| pane.tag_scroll; + if (caret) |at| { + const col = panes.File.rawDisplayCol(lines[at.row], at.at) -| pane.tag_scroll; const mode = if (pane.prompt == .name) pane.input.mode else pane.tag.mode; - if (col < tw) s.cursor = .{ .x = tx + @as(u16, @intCast(col)), .y = tag_y, .bar = mode == .insert }; + if (col < tw) s.cursor = .{ .x = tx + @as(u16, @intCast(col)), .y = tag_y + @as(u16, @intCast(at.row)), .bar = mode == .insert }; } for (pane.sel, 0..) |selection, button| { if (selection.state == .none or (selection.state == .done and button != 0)) continue; - if (@min(selection.r0, selection.r1) >= BOX_H) continue; + if (@min(selection.r0, selection.r1) >= rows) continue; body_layer.paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, selection, th.sel_bg, th.sel_fg); } } @@ -6945,7 +6994,7 @@ test "a prompt chip is a band with its caret, still on the grid, and only the ch _ = try p.render(frame.allocator()); const r = p.rects[id]; const cursor = p.surface.cursor orelse return error.MissingPromptCursor; - const row = p.bodyTop(r); + const row = p.bodyTop(pane, r); try std.testing.expectEqual(@as(u8, 1), pane.notices.len); try std.testing.expectEqual(row, cursor.y); try std.testing.expect(cursor.x < r.x + r.w); @@ -7010,7 +7059,7 @@ test "a prompt is typed on its own line in the notice band and leaves the tag ro try std.testing.expectEqualStrings("t", band.cells[caret.col - 1].grapheme()); try std.testing.expectEqualStrings("w", band.cells[caret.col].grapheme()); const grid = p.surface.cursor orelse return error.MissingPromptCursor; - try std.testing.expectEqual(p.bodyTop(p.rects[0]), grid.y); + try std.testing.expectEqual(p.bodyTop(pane, p.rects[0]), grid.y); // Submitting searches for what was typed and gives the prompt its line back. p.update(.{ .key = .{ .cp = Key.enter } }); diff --git a/src/pdf_view.zig b/src/pdf_view.zig index 92a05618..b2fd5866 100644 --- a/src/pdf_view.zig +++ b/src/pdf_view.zig @@ -2170,7 +2170,7 @@ pub fn paneViewport(core: *const pardes.Pardes, pane: *const pardes.Pane) ?Viewp if (slot == pane) break core.rects[id]; } else return null; const cols = rect.w -| config.GUTTER; - const rows = rect.h -| pardes.BOX_H; + const rows = rect.h -| pane.tag_rows; if (cols == 0 or rows == 0) return null; return .{ .pixel_w = @as(u32, cols) * @as(u32, core.cell_pixels.w), @@ -2208,8 +2208,8 @@ pub fn pageAtGridRow(core: *const pardes.Pardes, pane: *const pardes.Pane, row: const rect = for (core.panes, 0..) |slot, id| { if (slot == pane) break core.rects[id]; } else return null; - const body_y = core.bodyTop(rect); - if (row < body_y or row >= body_y + (rect.h -| pardes.BOX_H)) return null; + const body_y = core.bodyTop(pane, rect); + if (row < body_y or row >= body_y + (rect.h -| pane.tag_rows)) return null; const local_y = @as(f64, @floatFromInt( @as(u32, row - body_y) * core.cell_pixels.h + core.cell_pixels.h / 2, )); @@ -2265,7 +2265,7 @@ pub fn panePointAtPage( if (slot == pane) break core.rects[id]; } else return null; const body_x = @as(i64, rect.x + config.GUTTER); - const body_y = @as(i64, core.bodyTop(rect)); + const body_y = @as(i64, core.bodyTop(pane, rect)); const px = (@as(i64, col) - body_x) * core.cell_pixels.w + core.cell_pixels.w / 2; const py = (@as(i64, row) - body_y) * core.cell_pixels.h + core.cell_pixels.h / 2; return pointAtPage(state, view, page, px, py, clamp_to_page); @@ -2549,7 +2549,7 @@ pub fn draw( text_width: u16, ) bool { if (comptime !enabled) return false; - if (!core.native_images or rect.h <= pardes.BOX_H) return false; + if (!core.native_images or rect.h <= pane.tag_rows) return false; const state = &(pane.pdf orelse return false); const view = paneViewport(core, pane) orelse return false; const key = TintKey{ .mode = state.tint, .colors = tintColors(core) }; @@ -2598,9 +2598,9 @@ pub fn draw( .x = text_x, // Below the notice chips, like an image: a placed page is // drawn after the cells and would paint a chip out. - .y = core.bodyTop(rect) + pane.notices.span(), + .y = core.bodyTop(pane, rect) + pane.notices.span(), .w = text_width, - .h = (rect.h -| pardes.BOX_H) -| pane.notices.span(), + .h = (rect.h -| pane.tag_rows) -| pane.notices.span(), .rgba = placed.rgba, .iw = placed.width, // The texture contains the retained band, not the full page. @@ -2616,15 +2616,14 @@ pub fn draw( // This frame has spent the motion used to choose its raster band. state.scroll_travel = 0; - const body_y = core.bodyTop(rect); - const body_h = rect.h -| pardes.BOX_H; + const body_y = core.bodyTop(pane, rect); + const body_h = rect.h -| pane.tag_rows; const chrome = core.chromeTheme(); const theme = core.theme(); const pane_bg: pardes.Color = if (theme.bg) |color| .{ .rgb = color } else .default; // The rail runs past the notice bands; only the thumb tracks the text. - const rail_y = if (core.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H; - core.surface.fill(rect.x, rail_y, 1, rect.h -| pardes.BOX_H, .{ .bg = .{ .rgb = chrome.scroll_track } }); - core.surface.fill(rect.x + 1, rail_y, 1, rect.h -| pardes.BOX_H, .{ .bg = pane_bg }); + core.surface.fill(rect.x, body_y, 1, body_h, .{ .bg = .{ .rgb = chrome.scroll_track } }); + core.surface.fill(rect.x + 1, body_y, 1, body_h, .{ .bg = pane_bg }); const track_h: usize = body_h; const total = @max(@as(u64, 1), state.document_height); diff --git a/src/tag_layer.zig b/src/tag_layer.zig index 52da297d..ac7c4ac2 100644 --- a/src/tag_layer.zig +++ b/src/tag_layer.zig @@ -13,6 +13,8 @@ pub const Hit = struct { id: u16, serial: u32, col: u16, + /// Which line of a taller tag the layer draws. + line: u16 = 0, pixel_x: f32, pixel_y: f32, metrics: pardes.RowMetrics, @@ -21,6 +23,9 @@ pub const Layer = struct { kind: Kind = .workspace, id: u16 = 0, serial: u32 = 0, + /// A pane's tag taller than a line is drawn a layer to a line; this is + /// which one, counted from its first. + line: u16 = 0, viewport: pardes.Rect = .{ .x = 0, .y = 0, .w = 0, .h = 0 }, cols: u16 = 0, bg: [3]u8 = .{ 0, 0, 0 }, @@ -54,6 +59,7 @@ pub const Layer = struct { .kind = layer.kind, .id = layer.id, .serial = layer.serial, + .line = layer.line, .col = @intFromFloat(@min(@as(f32, @floatFromInt(layer.cols - 1)), @floor(dx / tw))), .pixel_x = x, .pixel_y = y, diff --git a/test/output.zig b/test/output.zig index c245e5f5..400e9508 100644 --- a/test/output.zig +++ b/test/output.zig @@ -77,7 +77,7 @@ fn outputCell(p: *Pardes, surface: *pardes.Surface, id: usize, byte: usize) *par const line = modal.lineSlice(pane.file.?.content, 0); const rect = p.rects[id]; const x = rect.x + config.GUTTER + panes.File.gutterWidth(pane) + @as(u16, @intCast(panes.File.displayWidth(line[0..byte]))); - const y = p.bodyTop(rect); + const y = p.bodyTop(pane, rect); return surface.at(x, y); } @@ -490,7 +490,7 @@ test "Mini syntax colors survive toggles themes and rendering without source acc const surface = try p.render(frame.allocator()); const rect = p.rects[id]; const x = rect.x + config.GUTTER + panes.File.gutterWidth(mini) + @as(u16, @intCast(column)); - const y = p.bodyTop(rect) + @as(u16, @intCast(position.row)); + const y = p.bodyTop(mini, rect) + @as(u16, @intCast(position.row)); if (enabled) try std.testing.expectEqualDeep(pardes.Color{ .rgb = p.theme().kw }, surface.at(x, y).style.fg); try std.testing.expectEqual(colors, mini.file.?.mini.?.colors.ptr); try std.testing.expectEqual(@as(usize, 0), mini.file.?.highlights.len); diff --git a/test/panes.zig b/test/panes.zig index b9fa9a88..4804c497 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -168,6 +168,66 @@ const TagLayerTests = struct { } }; +test "a tag with a newline in it is as tall as its lines, and each line is typed into and pointed at" { + for ([_]bool{ false, true }) |bottom| { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 14 }); + defer p.deinit(); + const pane = try p.setTestFile("body\n"); + p.presentation.enabled = false; + p.settings.tag_bottom = bottom; + p.update(.tick); + try std.testing.expectEqual(@as(u16, 1), pane.tag_rows); + const height = p.rects[0].h; + const body_rows = pane.rows; + // Insert mode in a tag is a body's: Enter is a new line. + p.update(.{ .key = .{ .cp = ':' } }); + p.update(.{ .key = .{ .cp = 'A' } }); + p.update(.{ .key = .{ .cp = Key.enter } }); + p.update(.{ .key = .{ .cp = 'S', .text = "Second" } }); + try std.testing.expect(std.mem.endsWith(u8, Pardes.curTail(pane), "\nSecond")); + try std.testing.expectEqual(@as(u16, 2), pane.tag_rows); + // The pane keeps its height; the body gives the tag its row. + try std.testing.expectEqual(height, p.rects[0].h); + try std.testing.expectEqual(body_rows - 1, pane.rows); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const surface = try p.render(frame.allocator()); + const r = p.rects[0]; + const tag_y = p.tagTop(pane, r); + const x = r.x + pardes.TAG_TEXT_INSET; + try std.testing.expectEqualStrings("/", surface.at(x, tag_y).grapheme()); + for ("Second", 0..) |byte, i| try std.testing.expectEqual(byte, surface.at(x + @as(u16, @intCast(i)), tag_y + 1).text[0]); + try std.testing.expectEqual(pardes.FontRole.tagline, surface.at(x, tag_y + 1).style.font_role); + // the caret is on the second line, after what was typed + try std.testing.expectEqual(tag_y + 1, surface.cursor.?.y); + try std.testing.expectEqual(x + 6, surface.cursor.?.x); + // the body starts under (or over) the whole tag + const body_y = p.bodyTop(pane, r); + try std.testing.expectEqual(if (bottom) r.y else r.y + 2, body_y); + try std.testing.expectEqualStrings("b", surface.at(r.x + config.GUTTER + panes.File.gutterWidth(pane), body_y).grapheme()); + // a layer to a line, for a pixel shell + var lines: usize = 0; + for (p.surface.tagLayers()) |*layer| { + if (layer.cols == 0 or layer.kind != .pane or layer.id != 0) continue; + try std.testing.expectEqual(tag_y + layer.line, layer.viewport.y); + lines += 1; + } + try std.testing.expectEqual(@as(usize, 2), lines); + // a click on the second line puts the tag's cursor on it + p.update(.{ .key = .{ .cp = Key.escape } }); + p.update(.{ .key = .{ .cp = ':' } }); + ClickCursorTests.click(p, .left, x + 2, tag_y + 1); + try std.testing.expect(pane.focus == .tag); + try std.testing.expectEqual(@as(i32, 1), pane.tag.cur_row); + try std.testing.expectEqual(@as(i32, 2), pane.tag.cur_col); + // and the pane's text, a row to a screen row, has both of its lines + const text = try pardes.edit.paneText(p, pane); + try std.testing.expect(std.mem.startsWith(u8, modal.lineSlice(text, 0), "/test.txt")); + try std.testing.expectEqualStrings("Second", modal.lineSlice(text, 1)); + try std.testing.expectEqualStrings("body\n", pane.file.?.content); + } +} + const TagNavigationTests = struct { fn key(p: *Pardes, cp: u21) void { p.update(.{ .key = .{ .cp = cp } }); @@ -521,7 +581,7 @@ const TreeContextTests = struct { try std.testing.expectEqual(@as(i32, 59), pane.wrapAt(visible.row).line); const cursor = surface.cursor orelse return error.MissingLookCursor; const rect = p.rects[0]; - const y = p.bodyTop(rect); + const y = p.bodyTop(pane, rect); try std.testing.expectEqual(y + @as(u16, @intCast(visible.row)), cursor.y); } } @@ -543,7 +603,7 @@ const TreeContextTests = struct { try std.testing.expectEqual(@as(i32, 7), pane.wrapAt(pane.context_rows).line); const rect = p.rects[0]; const x = rect.x + config.GUTTER + panes.File.gutterWidth(pane); - const y = p.bodyTop(rect); + const y = p.bodyTop(pane, rect); ClickCursorTests.click(p, .left, x + 6, y); try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); try std.testing.expectEqual(@as(i32, 6), pane.body.cur_col); @@ -552,7 +612,7 @@ const TreeContextTests = struct { try std.testing.expectEqual(x + 6, cursor.x); // Read the body top again: the click cleared the announcement band the // builtin above put up, and the body moved back up with it. - try std.testing.expectEqual(p.bodyTop(p.rects[0]), cursor.y); + try std.testing.expectEqual(p.bodyTop(pane, p.rects[0]), cursor.y); p.update(.{ .key = .{ .cp = 'i' } }); p.update(.{ .key = .{ .cp = 'Z', .text = "Z" } }); try std.testing.expect(std.mem.startsWith(u8, pane.file.?.content, "const ZBox = struct {")); @@ -591,7 +651,7 @@ const TreeContextTests = struct { const surface = try p.render(frame.allocator()); try std.testing.expectEqual(@as(u16, 3), pane.context_rows); const rect = p.rects[0]; - const y = p.bodyTop(rect); + const y = p.bodyTop(pane, rect); var glyph_x: ?u16 = null; for (0..surface.cols) |col| { if (std.mem.eql(u8, surface.at(@intCast(col), y).grapheme(), "界")) glyph_x = @intCast(col); @@ -605,7 +665,7 @@ const TreeContextTests = struct { try std.testing.expectEqual(x, cursor.x); // Read the body top again: the click cleared the announcement band the // builtin above put up, so the body moved with it. - try std.testing.expectEqual(p.bodyTop(p.rects[0]), cursor.y); + try std.testing.expectEqual(p.bodyTop(pane, p.rects[0]), cursor.y); panes.File.setContent(p, &pane.file.?, try p.gpa.dupe(u8, "// no enclosing declaration\n" ** 18)); _ = try p.render(frame.allocator()); try std.testing.expectEqual(@as(u16, 0), pane.context_rows); @@ -664,7 +724,7 @@ const TtySelectionTests = struct { _ = try p.render(frame.allocator()); const rect = p.rects[0]; const x = rect.x + config.GUTTER; - const y = p.bodyTop(rect); + const y = p.bodyTop(pane, rect); JumpSelectionTests.drag(p, x + 1, y, x + 3, y); try std.testing.expectEqualStrings("lph", p.yank orelse return error.MissingAutomaticTtyYank); p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); @@ -694,7 +754,7 @@ const TtySelectionTests = struct { _ = try p.render(frame.allocator()); const rect = p.rects[0]; const x = rect.x + config.GUTTER; - const y = p.bodyTop(rect); + const y = p.bodyTop(pane, rect); JumpSelectionTests.drag(p, x + @as(u16, if (prompt) 0 else 1), y, x + 3, y + @as(u16, if (prompt) 0 else 1)); const expected = if (prompt) "$ ab" else "lph\nrav"; try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); @@ -1009,7 +1069,7 @@ const JumpSelectionTests = struct { if (wrap) try std.testing.expectEqual(pane.wrap_line[0], pane.wrap_line[1]); const rect = p.rects[0]; const x = rect.x + config.GUTTER + panes.File.gutterWidth(pane); - const y = p.bodyTop(rect); + const y = p.bodyTop(pane, rect); if (reverse) drag(p, x + last_col, y + 1, x + first_col, y) else @@ -1040,7 +1100,7 @@ const JumpSelectionTests = struct { // A selection created after Back must also disappear on Forward. // Back announces itself, so the body sits under a notice band now. - const y2 = p.bodyTop(p.rects[0]); + const y2 = p.bodyTop(pane, p.rects[0]); drag(p, x + 1, y2, x + 3, y2 + 1); try std.testing.expect(pardes.test_api.heldSelection(p, 0) != null); p.update(.{ .key = .{ .cp = 'i', .ctrl = true } }); @@ -4093,7 +4153,7 @@ test "cancelled normal gestures leave no count or subprefix after mouse and focu .body, .tag => { const rect = p.rects[0]; const tag_y = if (p.settings.tag_bottom) rect.y + rect.h - pardes.BOX_H else rect.y; - const body_y = p.bodyTop(rect); + const body_y = p.bodyTop(pane, rect); const x = if (gesture == .tag) rect.x + pardes.TAG_TEXT_INSET + @as(u16, @intCast(panes.File.displayWidth(try p.tagPrefix(pane)))) + 3 else -- cgit v1.3 From f48ab559a4d257137a3aae987a4962f9d74ede23 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 01:09:05 -0300 Subject: Have Text.pane return nothing for a header instead of trapping A column's or the workspace's tag has no pane, and asking one for it hit unreachable; every caller guarded against that by checking `what` first. An optional makes each caller say what it does without a pane, so a forgotten guard no longer compiles into a crash. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 2 +- src/Text.zig | 30 +++++++++++++++++------------- src/edit.zig | 37 +++++++++++++++++++------------------ src/normal.zig | 4 ++-- 4 files changed, 39 insertions(+), 34 deletions(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index 262f3ebb..af538385 100644 --- a/src/File.zig +++ b/src/File.zig @@ -655,7 +655,7 @@ pub fn cursorLines(arena: std.mem.Allocator, pane: *Pane, f: *State) ![]const [] /// Edit-buffer fragments and other temporary text retain modal's scan path. fn contentIndex(t: *Text, text: []const u8) ?[]const usize { if (t.what != .body) return null; - const pane = t.pane(); + const pane = t.pane() orelse return null; const f = if (pane.file) |*file| file else return null; if (text.ptr != f.content.ptr or text.len != f.content.len) return null; return lineIndex(pane.gpa, f) catch null; diff --git a/src/Text.zig b/src/Text.zig index d4b6d048..61f238ae 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -76,13 +76,14 @@ ed_redo: [Terminal.history_max]Terminal.Snapshot = undefined, ed_redo_len: usize = 0, /// The window this text belongs to (acme's t->w). A column's or the -/// workspace's tag belongs to no pane; nothing asks it for one. -pub fn pane(t: *Text) *Pane { +/// workspace's tag belongs to none, and the optional makes every caller +/// say what it does then. +pub fn pane(t: *Text) ?*Pane { return switch (t.what) { .body => @alignCast(@fieldParentPtr("body", t)), .tag => @alignCast(@fieldParentPtr("tag", t)), .input => @alignCast(@fieldParentPtr("input", t)), - .column, .workspace => unreachable, + .column, .workspace => null, }; } @@ -98,7 +99,7 @@ pub fn deinit(t: *Text, gpa: std.mem.Allocator) void { /// the tagline follows its caret where it is drawn, and a prompt's answer is /// drawn whole. pub fn show(t: *Text) void { - if (t.what == .body) t.pane().ensureCursorVisible(); + if (t.what == .body) if (t.pane()) |w| w.ensureCursorVisible(); } pub fn toModalCursor(t: *Text) modal.Cursor { @@ -526,8 +527,9 @@ pub fn visualMove( pub fn halfPageMove(t: *Text, text: []const u8, range: modal.Selection, down: bool) void { // a view to move through is a body's; a tag or an answer is all shown if (t.what != .body) return; - const half: i32 = @max(1, @divTrunc(@as(i32, t.pane().rows), 2)); - t.pane().scrollBy(if (down) half else -half); + const w = t.pane() orelse return; + const half: i32 = @max(1, @divTrunc(@as(i32, w.rows), 2)); + w.scrollBy(if (down) half else -half); verticalMove(t, text, range, down, @intCast(half)); } @@ -536,9 +538,10 @@ pub fn halfPageMove(t: *Text, text: []const u8, range: modal.Selection, down: bo pub fn scrollViewMove(t: *Text, text: []const u8, range: modal.Selection, delta: i32) void { // a view to move through is a body's; a tag or an answer is all shown if (t.what != .body) return; - const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, t.pane().rows) - 1, 2)); - t.pane().scrollBy(delta); - const top = t.pane().scroll(); + const w = t.pane() orelse return; + const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, w.rows) - 1, 2)); + w.scrollBy(delta); + const top = w.scroll(); const last_row: i32 = @intCast(File.textLineCount(t, text) - 1); const cur = modal.selectionCursor(text, range); if (delta > 0) { @@ -548,7 +551,7 @@ pub fn scrollViewMove(t: *Text, text: []const u8, range: modal.Selection, delta: const anchor = if (t.select) range.anchor else head; setRange(t, text, 0, .{ .anchor = anchor, .head = head }, false); } else { - const snap: i32 = @max(0, @min(top + @as(i32, t.pane().rows) - margin - 1, last_row)); + const snap: i32 = @max(0, @min(top + @as(i32, w.rows) - margin - 1, last_row)); const head = File.textLineStart(t, text, @intCast(snap)); if (head >= cur) return; const anchor = if (t.select) range.anchor else head; @@ -560,10 +563,11 @@ pub fn scrollViewMove(t: *Text, text: []const u8, range: modal.Selection, delta: pub fn gotoWindow(t: *Text, text: []const u8, range: modal.Selection, which: enum { top, center, bottom }, cnt: usize) void { // a view to move through is a body's; a tag or an answer is all shown if (t.what != .body) return; - const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, t.pane().rows) - 1, 2)); - const top = t.pane().scroll(); + const w = t.pane() orelse return; + const margin: i32 = @min(config.scroll_off, @divTrunc(@as(i32, w.rows) - 1, 2)); + const top = w.scroll(); const last_row: i32 = @intCast(File.textLineCount(t, text) - 1); - const last_vis: i32 = @min(@as(i32, t.pane().rows) - 1, last_row - top); + const last_vis: i32 = @min(@as(i32, w.rows) - 1, last_row - top); const n: i32 = @intCast(cnt - 1); var vline: i32 = switch (which) { .top => top + margin + n, diff --git a/src/edit.zig b/src/edit.zig index 42032168..837a22c6 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -315,7 +315,7 @@ pub fn paneCursorLines(p: *Pardes, t: *Text) ![]const []const u8 { for (lines) |*line| line.* = it.next().?; return lines; } - const pane = t.pane(); + const pane = t.pane() orelse return &.{}; if (pane.file) |*f| return panes.File.cursorLines(arena, pane, f); if (pane.hasPdf()) { if (comptime pdf_enabled) return panes.Pdf.textLines(&pane.pdf.?, p.pdf_gpa, arena); @@ -325,8 +325,8 @@ pub fn paneCursorLines(p: *Pardes, t: *Text) ![]const []const u8 { } pub fn paneByteAtDisplay(p: *Pardes, t: *Text, row: i32, from_raw: i32, display_col: i32) i32 { - if (t.what == .body and t.pane().file != null) - return panes.File.byteAtRowDisplay(t.pane(), row, from_raw, display_col); + if (t.what == .body) if (t.pane()) |pane| if (pane.file != null) + return panes.File.byteAtRowDisplay(pane, row, from_raw, display_col); const lines = paneCursorLines(p, t) catch return @max(0, from_raw + display_col); const local = row; if (local < 0 or @as(usize, @intCast(local)) >= lines.len) @@ -347,7 +347,7 @@ pub fn pinPaneCursor(p: *Pardes, t: *Text) void { t.cur_pinned = true; return; } - const pane = t.pane(); + const pane = t.pane() orelse return; pane.pinCursor(); if (pane.file == null and !pane.hasPdf()) t.cur_col = paneByteAtDisplay(p, t, t.cur_row, 0, t.cur_col); @@ -356,11 +356,11 @@ pub fn pinPaneCursor(p: *Pardes, t: *Text) void { pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { switch (t.what) { .body => {}, - .tag => return tagline.curTail(t.pane()), + .tag => return if (t.pane()) |pane| tagline.curTail(pane) else "", .input => return t.own orelse "", .column, .workspace => return t.own orelse tagline.headerDefault(p, t.what), } - const pane = t.pane(); + const pane = t.pane() orelse return ""; if (pane.file) |f| return f.content; if (pane.hasPdf()) { if (comptime pdf_enabled) return pane.pdf.?.ensureText(p.pdf_gpa); @@ -372,7 +372,7 @@ pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { pub fn paneWrapWidth(p: *const Pardes, t: *Text) usize { if (t.what != .body) return 0; - const pane = t.pane(); + const pane = t.pane() orelse return 0; if (pane.file == null) return 0; return panes.File.wrapWidth(pane, p.settings.wrap); } @@ -385,7 +385,7 @@ fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText { if (t.what != .body and t.what != .input and t.own == null) t.own = p.gpa.dupe(u8, flatSurface(p, t) catch return null) catch return null; if (t.what != .body) return .{ .text = t.own orelse &.{}, .row0 = 0 }; - const pane = t.pane(); + const pane = t.pane() orelse return null; if (pane.file) |f| return .{ .text = f.content, .row0 = 0 }; if (pane.image != null or pane.hasPdf()) return null; return panes.Terminal.editText(p, pane, lo, hi, col); @@ -406,7 +406,7 @@ fn setEditText(p: *Pardes, t: *Text, new: []u8) void { t.own = new; return; } - const pane = t.pane(); + const pane = t.pane() orelse return p.gpa.free(new); if (pane.file) |*f| return panes.File.setContent(p, f, new); panes.Terminal.setEditText(p, pane, new); } @@ -417,7 +417,7 @@ pub const InsertAt = enum { at, append, line_start, line_end, open_below, open_a /// Terminal overlays can materialize virtual rows/columns, so keep those. pub fn clampFileCursor(t: *Text) bool { if (t.what != .body) return false; - const pane = t.pane(); + const pane = t.pane() orelse return false; const file = if (pane.file) |*file| file else return false; const old_row = t.cur_row; const old_col = t.cur_col; @@ -429,7 +429,7 @@ pub fn clampFileCursor(t: *Text) bool { } pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) void { - if (t.what == .body and t.pane().hasPdf()) return; + if (t.what == .body) if (t.pane()) |pane| if (pane.hasPdf()) return; pinPaneCursor(p, t); _ = clampFileCursor(t); // snapshot once per insert session (WITH the pre-insert selection) so @@ -563,7 +563,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { const flat = flatSurface(p, t) catch return; const range = t.primaryRange(flat, 0); if (t.what != .body) return; - const step: i32 = @intCast(@max(1, t.pane().rows)); + const step: i32 = @intCast(@max(1, (t.pane() orelse return).rows)); t.scrollViewMove(flat, range, if (key.cp == Key.page_down) step else -step); return; }, @@ -710,7 +710,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) void { const ln = modal.lineSlice(text, c.row); if (!p.multi_on and c.col > 0 and c.col <= ln.len and ln[c.col - 1] == '.') dot: { if (t.what != .body) break :dot; - const f = t.pane().file orelse break :dot; + const f = (t.pane() orelse break :dot).file orelse break :dot; if (f.output != null or !lsp.speaks(f.path)) break :dot; const seq = p.lsp_seq; p.lspRequest(p.active, .completion, ""); @@ -849,7 +849,7 @@ pub fn normalDelete(p: *Pardes, t: *Text, yank: bool) void { pub fn normalYank(p: *Pardes, t: *Text) void { t.select = false; - if (t.what == .body) if (t.pane().rawPointerText(t.pane().sel[sel_slot])) |text| { + if (t.what == .body) if (t.pane()) |pane| if (pane.rawPointerText(pane.sel[sel_slot])) |text| { setYank(p, text); return; }; @@ -1324,7 +1324,8 @@ pub fn normalToggleComment(p: *Pardes, t: *Text) void { } next = @max(next, end); } - const ext = if (t.what != .body) "" else if (t.pane().file) |f| std.fs.path.extension(f.path) else ""; + const file = if (t.what != .body) null else if (t.pane()) |pane| pane.file else null; + const ext = if (file) |f| std.fs.path.extension(f.path) else ""; var token: []const u8 = config.comment_token_default; lang: for (config.comment_tokens) |row| { for (row.exts) |e| if (std.ascii.eqlIgnoreCase(ext, e)) { @@ -1567,7 +1568,7 @@ pub fn pushUndo(p: *Pardes, t: *Text) void { // a prompt's answer is typed once and gone; it keeps no history .input => return, } - const pane = t.pane(); + const pane = t.pane() orelse return; if (pane.file != null) return panes.File.pushUndo(p, pane); panes.Terminal.pushUndo(p, pane); } @@ -1575,7 +1576,7 @@ pub fn pushUndo(p: *Pardes, t: *Text) void { pub fn doUndo(p: *Pardes, t: *Text) void { if (t.what == .tag or t.what == .column or t.what == .workspace) return stepOwn(p, t, true); if (t.what != .body) return; - const pane = t.pane(); + const pane = t.pane() orelse return; if (pane.file != null) return panes.File.undo(p, pane); panes.Terminal.undo(p, pane); } @@ -1583,7 +1584,7 @@ pub fn doUndo(p: *Pardes, t: *Text) void { pub fn doRedo(p: *Pardes, t: *Text) void { if (t.what == .tag or t.what == .column or t.what == .workspace) return stepOwn(p, t, false); if (t.what != .body) return; - const pane = t.pane(); + const pane = t.pane() orelse return; if (pane.file != null) return panes.File.redo(p, pane); panes.Terminal.redo(p, pane); } diff --git a/src/normal.zig b/src/normal.zig index 29d6d620..c7e75d70 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -175,7 +175,7 @@ const Replay = union(enum) { pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { const id = p.active; // a header belongs to no pane and cannot go away under the replay - const owner: ?*Pane = if (t.what == .column or t.what == .workspace) null else t.pane(); + const owner = t.pane(); const serial = if (owner) |pane| pane.serial else 0; // the whole selection in text coordinates, document order. t.sels // is already ordered, so this only slots the primary into place. @@ -292,7 +292,7 @@ pub fn handleNormal(p: *Pardes, t: *Text, key: Key) void { fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void { // What reaches past the text -- a builtin, a search, a language query -- // acts for the pane the text belongs to; a header's is the active one. - const pane = if (t.what == .column or t.what == .workspace) p.panes[p.active] orelse return else t.pane(); + const pane = t.pane() orelse p.panes[p.active] orelse return; const raw_selection = t.what == .body and pane.rawPointerText(pane.sel[sel_slot]) != null; const before = .{ t.cur_row, t.cur_col, t.vsel, t.msel, t.select, t.nsel, t.mode }; defer if (raw_selection and !std.meta.eql(before, .{ t.cur_row, t.cur_col, t.vsel, t.msel, t.select, t.nsel, t.mode })) { -- cgit v1.3 From e11048c20a50b67841e648a4d5ddd7490bc9c9b7 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 13:24:06 -0300 Subject: Paint into a target Surface instead of swapping the frame's out The painters of a pane's body and tag (renderBody and its selection, gutter, syntax, ANSI and wrap-marker passes; paintPaneTag; paintHeaders; renderPane; the image and PDF grid paths) take the Surface they paint as a parameter. The body layer and the tag layers paint straight into their own temporary surfaces, and the std.mem.swap of p.surface around those calls is gone. No behaviour change. --- src/File.zig | 13 +++++++------ src/Terminal.zig | 4 ++-- src/body_layer.zig | 38 ++++++++++++++++---------------------- src/draw.zig | 32 ++++++++++++-------------------- src/image.zig | 5 +++-- src/pdf_view.zig | 7 ++++--- 6 files changed, 44 insertions(+), 55 deletions(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index af538385..26585f77 100644 --- a/src/File.zig +++ b/src/File.zig @@ -6,6 +6,7 @@ const vaxis = @import("vaxis"); const pardes = @import("pardes.zig"); const config = @import("config.zig"); const Pardes = pardes.Pardes; +const Surface = pardes.Surface; const modal = @import("modal.zig"); const filesystem = @import("fs.zig"); const syntax = @import("syntax.zig"); @@ -1124,8 +1125,7 @@ fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) return written; } -pub fn drawGutter(p: *Pardes, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, active: bool) void { - const s = &p.surface; +pub fn drawGutter(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, active: bool) void { const prefix_width = gutterWidth(pane); const goff = pane.scroll(); const gcur = Terminal.gridCursor(pane); @@ -1176,11 +1176,10 @@ fn synStyle(p: *Pardes, sy: syntax.Syn) ?SynStyle { /// syntax colors: recolor each content cell from its tree-sitter style byte; /// content starts after the lineno gutter -pub fn recolorSyntax(p: *Pardes, pane: *Pane, f: *State, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void { +pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void { const highlights = if (f.mini) |mini| mini.colors else f.highlights; const highlight_start = if (f.mini != null) 0 else f.highlight_start; if (highlights.len == 0 and f.output == null) return; - const s = &p.surface; const prefix_width = gutterWidth(pane); const tz_recolor = tracy.zone(@src(), "synRecolor"); defer tz_recolor.end(); @@ -1255,6 +1254,7 @@ pub fn recolorSyntax(p: *Pardes, pane: *Pane, f: *State, r: pardes.Rect, tx: u16 pub fn drawWrapMarkers( p: *Pardes, + s: *Surface, pane: *const Pane, r: pardes.Rect, tx: u16, @@ -1268,7 +1268,7 @@ pub fn drawWrapMarkers( var row: u16 = 0; while (row + 1 < pane.wrap_n and row + 1 < body_h) : (row += 1) { if (pane.wrap_line[row + 1] != pane.wrap_line[row]) continue; - p.surface.set(tx + tw - 1, body_y + row, config.wrap_marker, .{ + s.set(tx + tw - 1, body_y + row, config.wrap_marker, .{ .fg = .{ .rgb = marker_fg }, .bg = pane_bg, }); @@ -1277,6 +1277,7 @@ pub fn drawWrapMarkers( pub fn paintWordSelection( p: *Pardes, + s: *Surface, pane: *Pane, r: pardes.Rect, row: i32, @@ -1301,7 +1302,7 @@ pub fn paintWordSelection( const c1 = @as(i32, prefix_width) + displayEndOffset(pane, row, here.at, hi - 1); var col = @max(@as(i32, prefix_width), c0); while (col <= c1 and col < @as(i32, tw)) : (col += 1) { - const cell = p.surface.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(vr))); + const cell = s.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(vr))); cell.default = false; cell.style.bg = .{ .rgb = bg }; } diff --git a/src/Terminal.zig b/src/Terminal.zig index cd292e5f..62a77ca8 100644 --- a/src/Terminal.zig +++ b/src/Terminal.zig @@ -5,6 +5,7 @@ const std = @import("std"); const pardes = @import("pardes.zig"); const config = @import("config.zig"); const Pardes = pardes.Pardes; +const Surface = pardes.Surface; const modal = @import("modal.zig"); const tracy = @import("tracy.zig"); const dump = @import("dump.zig"); @@ -1756,11 +1757,10 @@ const Anchor = struct { } }; -pub fn recolorAnsi(p: *Pardes, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void { +pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void { // No emulator, no ANSI cells: the whole pass — and the 256-colour theme // projection behind it — is compiled out. if (comptime !enabled) return; - const s = &p.surface; if (pane.terminal == null) return; const body_y = p.bodyTop(pane, r); var filtered_storage: FilteredColors = undefined; diff --git a/src/body_layer.zig b/src/body_layer.zig index aa52957c..db4d9524 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -145,7 +145,7 @@ test "compact context borders separate source gaps and preserve multiline header // ---- drawing a pane body into the surface ---- -fn paintTerminalSelection(p: *Pardes, pane: *Pane, r: Rect, rows: []const Pane.PointerRow, bg: [3]u8, fg: ?[3]u8) void { +fn paintTerminalSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: []const Pane.PointerRow, bg: [3]u8, fg: ?[3]u8) void { const body = bodyText(p, p.scratch.allocator(), pane) catch return; const raw = pane.body.mode == .tty; const tx = r.x + config.GUTTER; @@ -178,7 +178,7 @@ fn paintTerminalSelection(p: *Pardes, pane: *Pane, r: Rect, rows: []const Pane.P var col = panes.File.rawDisplayCol(line, lo); const end = panes.File.rawDisplayCol(line, hi); while (col < end and col < width) : (col += 1) { - const cell = p.surface.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(visible))); + const cell = s.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(visible))); cell.default = false; cell.style.bg = .{ .rgb = bg }; if (fg) |ink| cell.style.fg = .{ .rgb = ink }; @@ -187,8 +187,8 @@ fn paintTerminalSelection(p: *Pardes, pane: *Pane, r: Rect, rows: []const Pane.P } } -fn paintSourceSelection(p: *Pardes, pane: *Pane, r: Rect, rows: []const Pane.PointerRow, bg: [3]u8, fg: ?[3]u8) void { - if (pane.isTerminal()) return paintTerminalSelection(p, pane, r, rows, bg, fg); +fn paintSourceSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: []const Pane.PointerRow, bg: [3]u8, fg: ?[3]u8) void { + if (pane.isTerminal()) return paintTerminalSelection(p, s, pane, r, rows, bg, fg); const terminal_lines = if (pane.file == null) panes.Terminal.cursorLines(p, pane) catch return else &.{}; const tx = r.x + config.GUTTER; const width = r.w -| config.GUTTER; @@ -209,7 +209,7 @@ fn paintSourceSelection(p: *Pardes, pane: *Pane, r: Rect, rows: []const Pane.Poi var col = prefix + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], lo - start))); const last = prefix + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], hi - start))); while (col < last and col < width) : (col += 1) { - const cell = p.surface.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(visible))); + const cell = s.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(visible))); cell.default = false; cell.style.bg = .{ .rgb = bg }; if (fg) |ink| cell.style.fg = .{ .rgb = ink }; @@ -220,6 +220,7 @@ fn paintSourceSelection(p: *Pardes, pane: *Pane, r: Rect, rows: []const Pane.Poi pub fn paintPointerSelection( p: *Pardes, + s: *Surface, pane: *Pane, r: Rect, tx: u16, @@ -230,8 +231,7 @@ pub fn paintPointerSelection( bg: [3]u8, fg: ?[3]u8, ) void { - if (pane.pointerSelection(sl)) |rows| return paintSourceSelection(p, pane, r, rows, bg, fg); - const s = &p.surface; + if (pane.pointerSelection(sl)) |rows| return paintSourceSelection(p, s, pane, r, rows, bg, fg); const r0 = @min(sl.r0, sl.r1); const r1 = @max(sl.r0, sl.r1); const c0 = @max(0, @min(sl.c0, sl.c1)); @@ -278,13 +278,8 @@ pub fn renderBodyLayer(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rec const temporary_cells = try arena.alloc(Cell, @as(usize, r.w) * (logical_rows + pane.tag_rows)); @memset(temporary_cells, .{}); var temporary: Surface = .{ .cols = r.w, .rows = @intCast(logical_rows + pane.tag_rows), .cells = temporary_cells }; - std.mem.swap(Surface, &p.surface, &temporary); const synthetic: Rect = .{ .x = 0, .y = 0, .w = r.w, .h = @intCast(logical_rows + pane.tag_rows) }; - renderBody(p, arena, pane, synthetic, id, id == p.active, false) catch |err| { - std.mem.swap(Surface, &p.surface, &temporary); - return err; - }; - std.mem.swap(Surface, &p.surface, &temporary); + try renderBody(p, &temporary, arena, pane, synthetic, id, id == p.active, false); const first_row: usize = if (p.settings.tag_bottom) 0 else pane.tag_rows; for (0..logical_rows) |row| { const start = (row + first_row) * r.w + config.GUTTER; @@ -304,8 +299,7 @@ pub fn renderBodyLayer(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rec } } -pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool, scrollbar: bool) !void { - const s = &p.surface; +pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool, scrollbar: bool) !void { const th = p.theme(); const chrome = p.chromeTheme(); const tx = r.x + config.GUTTER; @@ -343,12 +337,12 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id const tz_color = tracy.zone(@src(), "paneRecolor"); // File layout is independent of whether its producer requests colors. if (pane.file) |*f| { - panes.File.drawGutter(p, pane, r, tx, tw, body_h, active); + panes.File.drawGutter(p, s, pane, r, tx, tw, body_h, active); if (p.settings.colors and pane.colorAlgo() != .none) - panes.File.recolorSyntax(p, pane, f, r, tx, tw, body_h); - panes.File.drawWrapMarkers(p, pane, r, tx, tw, body_h, pane_bg); + panes.File.recolorSyntax(p, s, pane, f, r, tx, tw, body_h); + panes.File.drawWrapMarkers(p, s, pane, r, tx, tw, body_h, pane_bg); } else if (pane.isTerminal() and p.settings.colors) { - panes.Terminal.recolorAnsi(p, pane, r, tx, tw, body_h, body); + panes.Terminal.recolorAnsi(p, s, pane, r, tx, tw, body_h, body); } tz_color.end(); @@ -366,9 +360,9 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id // macOS composes its glass overlay over exactly these. const preview_bg = colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)); if (preview.file_word) |word| - panes.File.paintWordSelection(p, pane, r, word.row, word.lo, word.hi, preview_bg) + panes.File.paintWordSelection(p, s, pane, r, word.row, word.lo, word.hi, preview_bg) else if (preview.sel) |sel| - paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, sel, preview_bg, null); + paintPointerSelection(p, s, pane, r, tx, tw, tag_y, body_y, sel, preview_bg, null); } } const modal_hover = if (p.look_hover_preview) |preview| @@ -381,7 +375,7 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id // A select sweep over the tag is the tag's selection, painted there // in the tag's own selection colours. if (b == pardes.sel_slot and @min(sl.r0, sl.r1) < pane.tag_rows) continue; - paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, sl, sel_btn[b], th.sel_fg); + paintPointerSelection(p, s, pane, r, tx, tw, tag_y, body_y, sl, sel_btn[b], th.sel_fg); } // modal line selection (helix `x`): whole body rows, normal mode only if ((pane.body.mode == .normal or modal_hover) and pane.body.msel.active) { diff --git a/src/draw.zig b/src/draw.zig index 5db6da30..d84f2033 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -90,7 +90,7 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { pane.context_row_limit = null; s.body_layers[id].rows = 0; Messages.collectNotices(p, pane, p.rects[id], id); - try renderPane(p, arena, pane, p.rects[id], id, id == p.active); + try renderPane(p, s, arena, pane, p.rects[id], id, id == p.active); try body_layer.renderBodyLayer(p, arena, pane, p.rects[id], id); } for (&p.panes, 0..) |*slot, id| { @@ -156,7 +156,7 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { } } - try paintHeaders(p); + try paintHeaders(p, s); try renderTagLayers(p, arena); switch (p.drag) { @@ -397,11 +397,10 @@ fn hasGlyph(cell: *const Cell) bool { return !cell.default and !(cell.len == 1 and cell.text[0] == ' '); } -fn renderPane(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool) !void { +fn renderPane(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool) !void { const tz = tracy.zone(@src(), "renderPane"); defer tz.end(); if (r.w <= config.GUTTER or r.h == 0) return; - const s = &p.surface; const th = p.theme(); const chrome = p.chromeTheme(); const tx = r.x + config.GUTTER; // text area (tag + body), right of the gutter @@ -436,14 +435,14 @@ fn renderPane(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: us .tty => config.tag_tty, }, box_style); - try paintPaneTag(p, arena, pane, r, id, active, p.tagCapacity(r.w -| TAG_TEXT_INSET)); + try paintPaneTag(p, s, arena, pane, r, id, active, p.tagCapacity(r.w -| TAG_TEXT_INSET)); // Folded panes retain their body state, but neither body pixels nor // its cursor belong outside the one-row tag rectangle. if (pane.collapsed) return; if (comptime pdf_enabled) - if (pane.hasPdf() and panes.Pdf.draw(p, pane, r, id, tx, tw)) return; + if (pane.hasPdf() and panes.Pdf.draw(p, s, pane, r, id, tx, tw)) return; if (pane.image) |*iv| { // Below the notice chips: a picture is drawn after the cells (the @@ -451,7 +450,7 @@ fn renderPane(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: us // painted out. Text gets the overlay; a picture gives up the rows. const shown = pane.notices.span(); const image_h = (r.h -| pane.tag_rows) -| shown; - panes.Image.draw(p, iv, @intCast(id), pane.serial, tx, body_y + shown, tw, image_h); + panes.Image.draw(p, s, iv, @intCast(id), pane.serial, tx, body_y + shown, tw, image_h); // thumbless, but the same one column as the real scrollbar below — // that is the whole point of drawing it, and like that one it runs // past the notice bands so the gutter has no notch in it @@ -460,14 +459,13 @@ fn renderPane(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: us return; } - try body_layer.renderBody(p, arena, pane, r, id, active, true); + try body_layer.renderBody(p, s, arena, pane, r, id, active, true); } /// The workspace and column tags as the grid shows them: their text, the /// word under the pointer and, in the one being edited, its selection and /// caret. Their tag layers are drawn by renderTagLayers. -pub fn paintHeaders(p: *Pardes) !void { - const s = &p.surface; +pub fn paintHeaders(p: *Pardes, s: *Surface) !void { const chrome = p.chromeTheme(); const th = p.theme(); // global tagbar: full width, top rows — unless a native shell has @@ -623,12 +621,7 @@ pub fn renderTagLayers(p: *Pardes, arena: std.mem.Allocator) !void { const storage = try arena.alloc(Cell, pitch * rows); @memset(storage, .{}); var temporary: Surface = .{ .cols = columns + TAG_TEXT_INSET, .rows = rows, .cells = storage }; - std.mem.swap(Surface, &p.surface, &temporary); - paintPaneTag(p, arena, pane, .{ .x = 0, .y = 0, .w = columns + TAG_TEXT_INSET, .h = rows }, id, id == p.active, p.tagCapacity(r.w - TAG_TEXT_INSET)) catch |err| { - std.mem.swap(Surface, &p.surface, &temporary); - return err; - }; - std.mem.swap(Surface, &p.surface, &temporary); + try paintPaneTag(p, &temporary, arena, pane, .{ .x = 0, .y = 0, .w = columns + TAG_TEXT_INSET, .h = rows }, id, id == p.active, p.tagCapacity(r.w - TAG_TEXT_INSET)); // A layer to a line: the first in the pane's own slot, the rest // in the slots kept for the lines of taller tags. for (0..rows) |line| { @@ -791,8 +784,7 @@ fn renderHeaderLayer(p: *Pardes, arena: std.mem.Allocator, index: usize, kind: T } } -pub fn paintPaneTag(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool, capacity: u16) !void { - const s = &p.surface; +pub fn paintPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool, capacity: u16) !void { const th = p.theme(); const chrome = p.chromeTheme(); const tx = r.x + @min(TAG_TEXT_INSET, r.w); @@ -867,7 +859,7 @@ pub fn paintPaneTag(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, if (p.look_hover_preview) |preview| { if (preview.pane == id and preview.serial == pane.serial) if (preview.sel) |sel| if (@min(sel.r0, sel.r1) < rows) { const preview_bg = colors.mix(page_rgb, colors.mix(page_rgb, th.sel_bg)); - body_layer.paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, sel, preview_bg, null); + body_layer.paintPointerSelection(p, s, pane, r, tx, tw, tag_y, body_y, sel, preview_bg, null); }; } // The tag's own selections, while it has the keyboard, a line at a @@ -908,6 +900,6 @@ pub fn paintPaneTag(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, for (pane.sel, 0..) |selection, button| { if (selection.state == .none or (selection.state == .done and button != 0)) continue; if (@min(selection.r0, selection.r1) >= rows) continue; - body_layer.paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, selection, th.sel_bg, th.sel_fg); + body_layer.paintPointerSelection(p, s, pane, r, tx, tw, tag_y, body_y, selection, th.sel_bg, th.sel_fg); } } diff --git a/src/image.zig b/src/image.zig index 09f049ca..071a2e2a 100644 --- a/src/image.zig +++ b/src/image.zig @@ -941,6 +941,7 @@ fn ensureGrid(p: *pardes.Pardes, state: *State, cols: u16, rows: u16) void { pub fn draw( p: *pardes.Pardes, + s: *pardes.Surface, state: *State, pane_id: u8, serial: u32, @@ -982,7 +983,7 @@ pub fn draw( }; const sx = x + @as(u16, @intCast(offx + cx)); const sy = y + @as(u16, @intCast(offy + cy)); - if (sx < p.surface.cols and sy < p.surface.rows) - p.surface.set(sx, sy, cell.glyph[0..cell.glyph_len], .{ .fg = fg, .bg = bg }); + if (sx < s.cols and sy < s.rows) + s.set(sx, sy, cell.glyph[0..cell.glyph_len], .{ .fg = fg, .bg = bg }); }; } diff --git a/src/pdf_view.zig b/src/pdf_view.zig index b2fd5866..78d3de27 100644 --- a/src/pdf_view.zig +++ b/src/pdf_view.zig @@ -2542,6 +2542,7 @@ pub fn horizontalWheel(core: *pardes.Pardes, pane: *pardes.Pane, direction: i8) pub fn draw( core: *pardes.Pardes, + s: *pardes.Surface, pane: *pardes.Pane, rect: pardes.Rect, pane_id: usize, @@ -2622,8 +2623,8 @@ pub fn draw( const theme = core.theme(); const pane_bg: pardes.Color = if (theme.bg) |color| .{ .rgb = color } else .default; // The rail runs past the notice bands; only the thumb tracks the text. - core.surface.fill(rect.x, body_y, 1, body_h, .{ .bg = .{ .rgb = chrome.scroll_track } }); - core.surface.fill(rect.x + 1, body_y, 1, body_h, .{ .bg = pane_bg }); + s.fill(rect.x, body_y, 1, body_h, .{ .bg = .{ .rgb = chrome.scroll_track } }); + s.fill(rect.x + 1, body_y, 1, body_h, .{ .bg = pane_bg }); const track_h: usize = body_h; const total = @max(@as(u64, 1), state.document_height); @@ -2641,7 +2642,7 @@ pub fn draw( )); var y = pos; while (y < track_h and y < pos + len) : (y += 1) - core.surface.fill( + s.fill( rect.x, body_y + @as(u16, @intCast(y)), 1, -- cgit v1.3 From eeadda6e7db3334e15708de2d7b5396f539c8186 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 14:31:42 -0300 Subject: A terminal bound as a language's REPL takes the execs made on that language's files Repl python in a terminal's tag or on its ctl binds it (Repl - unbinds, Repl bare says the binding, the same word again changes nothing), with an id, python-a, python-b, in its tag. An exec made by a gesture on the body of a file in that language -- a middle click or the execute key, on any text, a single word too -- or on the REPL's own body is typed into it, bracketed if its program asked for that, else line by line with a once-said warning for Python's blank lines, then Enter; the message row says -> python-a in the tag's name tint, the log send . Several bound for the language: the pane asks which on its notice band, as Del asks, one key answering, Esc none, nothing remembered. The gesture is known where it is dispatched (mouse.zig, the execute key), so the tag's words, Exec run by name and a command word @`cmd` stay commands, and a 9P exec is never sent. A finished command pane is no REPL; bindings are not dumped. The docs spell out the escapes, the pdb and input() caveat and the no-bracketed-paste papercut. Co-Authored-By: Claude Opus 5.5 --- .agents/skills/pardes-9p/SKILL.md | 6 +- docs/fs.md | 21 +++++++ docs/tags.md | 6 +- src/File.zig | 2 +- src/Messages.zig | 1 + src/body_layer.zig | 6 +- src/builtins.zig | 55 +++++++++++++++++ src/config.zig | 1 + src/edit.zig | 2 +- src/exec.zig | 101 ++++++++++++++++++++++++++++++ src/fs-help.txt | 4 +- src/mouse.zig | 5 +- src/panes.zig | 17 +++++ src/pardes.zig | 127 +++++++++++++++++++++++++++++++++++++- src/tagline.zig | 15 ++++- test/snapshots/builtins.snap | 1 + 16 files changed, 354 insertions(+), 16 deletions(-) (limited to 'src/File.zig') diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index df53c90f..8903a609 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -123,7 +123,11 @@ pane, a terminal whose child is `$SHELL -c` the line in the pane's directory, which ends showing `exit N` (a typo: `exit 127`) and logs `run ` and `exit ` -- `exec` reads back its serial, so follow `log` for the exit. The directory's next command reuses a finished -command pane, below what it showed. Every refused 9P write adds an `err +command pane, below what it showed. A terminal bound as a REPL (`Repl +python` on its ctl) takes the middle clicks made on a `.py` body instead, +but never a 9P write: a script sends code by writing the REPL pane's +`pty/data`, and runs a command from such a file with `Exec ` or the +tag. Every refused 9P write adds an `err : ` record to `$m/log`; through a mount the write itself only says `Invalid argument`. diff --git a/docs/fs.md b/docs/fs.md index d3e32e3a..e93704a6 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -253,6 +253,27 @@ same tree without leaving the process. command that says so and ends `exit 127`. `echo Tty > pane//ctl` makes an interactive terminal in that pane's directory. +A terminal can be bound as a language's REPL: `Repl python` in its tag or +on its `ctl` (the language names are the syntax table's; `Repl -` unbinds, +`Repl` bare says the binding, `Repl python` again changes nothing). Its tag +shows its id, `python-a`, `python-b` for the next, a freed letter reused. +Then an exec made by a gesture on the body of a file in that language -- a +middle click, the execute key, on a selection or a single word, even `make` +in a comment -- or on the REPL's own body is typed into the REPL instead of +run: bracketed paste when its program asked for it (DECSET 2004), else line +by line, where a blank line inside a Python block ends the block (said +once), then Enter. The message row says `→ python-a` in the tag's name tint +and the log `send `. With several REPLs bound for the +language the pane asks which, on its notice band, one key answering and Esc +sending nowhere; nothing is remembered. A command pane whose command is done +is no REPL any more. Still commands, whatever is bound: a word in a tag (so +the tag is how to run `make` from that file), `Exec ` run by name +(typed, a 2-1 chord onto `Exec`, a `ctl` line) and a command word @`cmd` in +the text, looked at or clicked (`# @`pytest -x`` in a script). A 9P `exec` +is no gesture and is never sent: a script writes to the REPL pane's +`pty/data`. The REPL gets the text wherever it is -- at a `pdb` or `input()` +prompt too. Bindings are not dumped, so a Restore leaves none. + The root's pair clicks at the active pane and `/pane//look` and `/pane//exec` at that pane. Blank lines are skipped, and every other line is checked before any of them runs, so a control character fails the whole diff --git a/docs/tags.md b/docs/tags.md index f1d7794d..f1e4a420 100644 --- a/docs/tags.md +++ b/docs/tags.md @@ -11,7 +11,11 @@ with the tag's name colour: `Tty+arg` is one word a tag can hold for `Tty arg`, so clicking it opens another terminal on that shell, as `Tty fish` would. Only a builtin that declares `plus_arg` reads a `+` so; `Tty` is the one, since other arguments (a dump's name) may contain `+`. A command pane's tag reads ` () running` or `exit N` -and offers `Kill`. +and offers `Kill`. `Repl python` in a terminal's tag binds it as Python's +REPL, its id, `python-a`, beside the Tty word: a middle click or the execute +key on a `.py` body then types the text into it rather than running it, and +several bound ask which. The tag's own words, `Exec ` by name and a +command word @`cmd` still run as commands (docs/fs.md). Pane and column command text leave a small gap after their aligned drag grips. GUI pane mode symbols are centered by their visible ink; changing the font or its size refreshes the cached measurements. diff --git a/src/File.zig b/src/File.zig index af538385..8ba58fbc 100644 --- a/src/File.zig +++ b/src/File.zig @@ -1130,7 +1130,7 @@ pub fn drawGutter(p: *Pardes, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, bod const goff = pane.scroll(); const gcur = Terminal.gridCursor(pane); const gcrow = if (pane.body.cur_pinned) pane.body.cur_row else @as(i32, gcur.y) + goff; - const typing_body = pane.focus == .body and (pane.prompt == .none or pane.prompt == .del_side); + const typing_body = pane.focus == .body and (pane.prompt == .none or pane.prompt == .del_side or pane.prompt == .repl_choice); const cur_line: i32 = if (active and typing_body) gcrow else std.math.minInt(i32); // the body's first row, the way renderPane derives it (Tagbottom) const body_y = p.bodyTop(pane, r); diff --git a/src/Messages.zig b/src/Messages.zig index 00352afe..f8178629 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -180,6 +180,7 @@ fn showMessage(p: *Pardes, id: usize, text: []const u8, stack: bool) void { pane.pushOlderMessage(); if (pane.msg_len == 0) pane.msg_slot = pane.freeMessageSlot(); pane.msg_announcement = false; + pane.msg_sent = false; pane.msg_status = !stack; const arrives = pane.msg_len == 0 or pane.msg_life.phase == .leaving; for (text[0..n], pane.msg[0..n]) |c, *cell| cell.* = if (c < 0x20 or c == 0x7f) ' ' else c; diff --git a/src/body_layer.zig b/src/body_layer.zig index c468bd5f..c8e229c4 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -479,7 +479,7 @@ pub fn renderBody(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id // cursor: tracks the shell cursor until pinned by a click or a key // (the tag's or a prompt's cursor wins while that is being typed into) - if (active and pane.focus == .body and (pane.prompt == .none or pane.prompt == .del_side)) { + if (active and pane.focus == .body and (pane.prompt == .none or pane.prompt == .del_side or pane.prompt == .repl_choice)) { if (pane.body.mode != .tty) { const cur = panes.Terminal.gridCursor(pane); const goff = panes.Terminal.gridOffset(pane); @@ -797,12 +797,12 @@ pub fn renderTagLayers(p: *Pardes, arena: std.mem.Allocator) !void { .y = first + @as(u16, pane.notices.row[i]), .w = chip, .h = BOX_H, - }, line, Messages.blendRgb(chrome.tag_bg, page, fade), Messages.blendRgb(chrome.tag_fg, page, fade)); + }, line, Messages.blendRgb(chrome.tag_bg, page, fade), Messages.blendRgb(if (kind == .message and pane.msg_sent) chrome.tag_name_fg else chrome.tag_fg, page, fade)); p.surface.tag_layers[layer_index].slide = motion.slide; p.surface.tag_layers[layer_index].fade = fade; // The caret rides the band, where the prompt's glyphs are, // at the same place in the text the grid pass puts it. - if (kind != .prompt or id != p.active or pane.prompt == .del_side) continue; + if (kind != .prompt or id != p.active or pane.prompt == .del_side or pane.prompt == .repl_choice) continue; const typed = panes.File.displayWidth(text[0..@min(@as(usize, @intCast(@max(0, pane.input.cur_col))), text.len)]); const dropped = shown - panes.File.displayWidth(kept); if (typed < dropped) continue; diff --git a/src/builtins.zig b/src/builtins.zig index 5273cf37..be0956e0 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -852,6 +852,61 @@ pub const Tty9p = struct { /// Fold the active pane's column into the one on its right, keeping its panes. /// The horizontal mirror of the vertical stacking `New` does. +/// Binds this terminal as a language's REPL, by the language's name as the +/// syntax table has it: an exec made on the body of a file in that +/// language -- a middle click, the execute key, a single word like `ls` +/// as much as a selection -- and one made on this terminal's own body, is +/// typed into it (bracketed paste if its program asked for that, else line +/// by line, then Enter) instead of run. `Repl python` binds (again, it is +/// already); `Repl -` unbinds; `Repl` bare says what it is bound as. With +/// several bound for a language, the exec asks which. +/// Still commands, whatever is bound: a word in a tag, `Exec ` run by +/// name (typed, a 2-1 chord onto Exec, a ctl line), and a command word +/// @`cmd` in the text, looked at or clicked. +pub const Repl = struct { + pub const takes_arg = true; + pub fn run(c: Ctx) void { + const pane = c.pane; + if (!pane.isTerminal()) return c.p.reportFailure(c.id, "Repl: only a terminal is a REPL"); + const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + var buf: [320]u8 = undefined; + var idbuf: [48]u8 = undefined; + if (arg.len == 0) { + if (pane.repl == null) return c.p.setMessage(c.id, "Repl: not bound"); + return c.p.setMessage(c.id, std.fmt.bufPrint(&buf, "Repl: {s}", .{exec.replId(&idbuf, pane)}) catch "Repl"); + } + if (std.mem.eql(u8, arg, "-")) { + pane.repl = null; + return c.p.setMessage(c.id, "Repl: unbound"); + } + const grammars = @import("grammar_manifest.zig").all; + const lang: u8 = for (grammars, 0..) |g, i| { + if (g.exts.len > 0 and std.mem.eql(u8, g.name, arg)) break @intCast(i); + } else { + var w = std.Io.Writer.fixed(&buf); + w.print("Repl: no language \"{s}\"; one of", .{arg[0..@min(arg.len, 32)]}) catch {}; + for (grammars) |g| if (g.exts.len > 0) w.print(" {s}", .{g.name}) catch break; + return c.p.reportFailure(c.id, w.buffered()); + }; + if (pane.repl) |r| if (r.lang == lang) + return c.p.setMessage(c.id, std.fmt.bufPrint(&buf, "Repl: {s}", .{exec.replId(&idbuf, pane)}) catch "Repl"); + // The lowest letter no other REPL of the language has: freed ones + // come back. + var letter: u8 = 'a'; + while (letter <= 'z') : (letter += 1) { + const taken = for (c.p.panes) |slot| { + const other = slot orelse continue; + if (other != pane) if (other.repl) |r| if (r.lang == lang and r.letter == letter) break true; + } else false; + if (!taken) break; + } + if (letter > 'z') return c.p.reportFailure(c.id, "Repl: every letter of the language is taken"); + pane.repl = .{ .lang = lang, .letter = letter }; + pane.repl_warned = false; + c.p.setMessage(c.id, std.fmt.bufPrint(&buf, "Repl: {s}", .{exec.replId(&idbuf, pane)}) catch "Repl"); + } +}; + pub const Joincol = struct { pub const scope: Scope = .session; pub fn run(c: Ctx) void { diff --git a/src/config.zig b/src/config.zig index 1a505334..9ad9cc7e 100644 --- a/src/config.zig +++ b/src/config.zig @@ -48,6 +48,7 @@ pub const leader_path = paths: { .Mode = null, .Togglettymode = null, .Collapse = null, + .Repl = null, .Kill = null, .Exit = null, .ClipYank = "y", diff --git a/src/edit.zig b/src/edit.zig index b2d71ed2..3cbbc28c 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -87,7 +87,7 @@ pub fn applyPaste(p: *Pardes, bytes: []const u8) void { const pane = p.panes[id] orelse return; if (req) |r| if (pane.serial != r.serial) return; p.active = id; - if (pane.prompt != .none and pane.prompt != .del_side) { + if (pane.prompt != .none and pane.prompt != .del_side and pane.prompt != .repl_choice) { // an answer is one line: a newline in it would only be submitting it const line = p.scratch.allocator().alloc(u8, bytes.len) catch return; var n: usize = 0; diff --git a/src/exec.zig b/src/exec.zig index 8b058a12..1b82d2a8 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -16,6 +16,7 @@ const colors = @import("colors.zig"); const themes = colors.themes; const builtins = @import("builtins.zig"); const config = @import("config.zig"); +const grammars = @import("grammar_manifest.zig").all; const pdf_enabled = panes.Pdf.enabled; const font_picker = pardes.font_picker; const hosted = pardes.hosted; @@ -369,6 +370,96 @@ pub fn replaceStillborn(p: *Pardes) void { if (was_active) p.active = new_id; } +// ---- REPLs ---- +// +// A terminal is bound as a language's REPL by `Repl python` (builtins.zig). +// An exec made by a gesture on the body of a file in that language -- or on +// the REPL's own body -- is sent to it as input rather than run: all of it, +// a word like `ls` too. The tag's words, `Exec` by name and a command word +// `@`...`` still run as commands. + +/// A file pane's language, as grammar_manifest names it, by its index. +pub fn langOf(pane: *const Pane) ?u8 { + const f = pane.file orelse return null; + for (grammars, 0..) |g, i| for (g.exts) |ext| { + if (std.mem.endsWith(u8, f.path, ext)) return @intCast(i); + }; + return null; +} + +/// A bound REPL whose program can still take input: a command pane's is +/// gone once its command is done. +pub fn replLive(pane: *const Pane) bool { + return pane.repl != null and pane.isTerminal() and !(pane.command != null and pane.command_done); +} + +/// `python-a`. +pub fn replId(buf: []u8, pane: *const Pane) []const u8 { + const r = pane.repl orelse return ""; + return std.fmt.bufPrint(buf, "{s}-{c}", .{ grammars[r.lang].name, r.letter }) catch ""; +} + +const Routed = union(enum) { none, sent: usize, asked }; + +/// Where an exec from `from`'s body goes when a REPL is bound for it: the +/// one there is, or a question when there are several. +fn routeToRepl(p: *Pardes, from: usize, text: []const u8) Routed { + const src = p.panes[from] orelse return .none; + if (src.repl != null and replLive(src)) { + sendToRepl(p, from, from, text); + return .{ .sent = from }; + } + const lang = langOf(src) orelse return .none; + var bound: [26]usize = undefined; + var n: usize = 0; + for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.repl) |r| if (r.lang == lang and replLive(pane) and n < bound.len) { + bound[n] = i; + n += 1; + }; + if (n == 0) return .none; + if (n == 1) { + sendToRepl(p, from, bound[0], text); + return .{ .sent = bound[0] }; + } + // Several: asked on the pane's notice band, as Del asks, one key + // answering; nothing is remembered of the answer. + const owned = p.gpa.dupe(u8, text) catch return .none; + if (p.repl_ask) |old| p.gpa.free(old.text); + p.repl_ask = .{ .from = src.serial, .lang = lang, .text = owned }; + var w = std.Io.Writer.fixed(&src.question); + w.print("send to {s}:", .{grammars[lang].name}) catch {}; + for (bound[0..n]) |i| w.print(" {c}", .{p.panes[i].?.repl.?.letter}) catch {}; + w.writeAll(" (Esc: none)") catch {}; + src.question_len = @intCast(w.buffered().len); + src.prompt = .repl_choice; + p.active = from; + return .asked; +} + +/// Types `text` into the REPL in `to`, bracketed if its program asked for +/// that, then Enter; says so on `from`'s message row and in the log. +pub fn sendToRepl(p: *Pardes, from: usize, to: usize, text: []const u8) void { + const dst = p.panes[to] orelse return; + const src = p.panes[from] orelse return; + var idbuf: [48]u8 = undefined; + const id = replId(&idbuf, dst); + edit.typeToTty(p, to, dst, text); + p.emitWrite(to, "\r"); + // Line by line, a blank line inside a Python block ends the block. + if (!panes.Terminal.bracketedPaste(dst) and !dst.repl_warned and std.mem.startsWith(u8, id, "python") and + std.mem.indexOfScalar(u8, text, '\n') != null) + { + dst.repl_warned = true; + var warn: [128]u8 = undefined; + p.setMessage(from, std.fmt.bufPrint(&warn, "Repl: {s} takes no bracketed paste; a blank line in a block ends it", .{id}) catch "Repl: no bracketed paste"); + } + var said: [64]u8 = undefined; + p.setMessage(from, std.fmt.bufPrint(&said, "\u{2192} {s}", .{id}) catch "sent"); + src.msg_sent = true; + var rec: [96]u8 = undefined; + pardes.ctlfs.events.notePath(p, "send", std.fmt.bufPrint(&rec, "{d} {d} {s}", .{ src.serial, dst.serial, id }) catch return); +} + /// The longest line a command pane runs. pub const command_max = 1024; @@ -381,6 +472,11 @@ const max_exec_depth = 8; /// done, and which Kill signals. Answers the pane it went to. pub fn execute(p: *Pardes, id: usize, txt: []const u8) ?usize { const pane = p.panes[id] orelse return null; + // Made by a gesture on a body, it may be a bound REPL's; run by name + // (`Exec ...`, which runs through here again) or written in a command + // word, it never is. + const gesture = p.exec_from_body and config.commandWord(std.mem.trim(u8, txt, " \t\r\n")) == null; + p.exec_from_body = false; const cmd = commandText(txt); if (cmd.len == 0) return null; if (p.exec_depth == 0) p.noteHaptic(.exec); @@ -388,6 +484,11 @@ pub fn execute(p: *Pardes, id: usize, txt: []const u8) ?usize { if (p.exec_depth >= max_exec_depth) return null; p.exec_depth += 1; defer p.exec_depth -= 1; + if (gesture) switch (routeToRepl(p, id, cmd)) { + .none => {}, + .sent => |to| return to, + .asked => return null, + }; if (!takesCommandLine(p, id)) return runCommand(p, id, cmd); panes.Terminal.padOutputBelowEdits(p, id); panes.Terminal.noteCommand(pane, cmd); diff --git a/src/fs-help.txt b/src/fs-help.txt index 0e87f40e..79701628 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -41,5 +41,5 @@ Pitfalls, one each: A terminal's body is a history snapshot frozen per open; pty/data is the live stream. exec: a non-builtin line runs as a command pane ($SHELL -c; exit N shown, logged), a shell's typed in. Through a mount a malformed write is EINVAL, a well-formed one that fails EIO: log's err says why. - lock/unlock on a pane's ctl need a held fd (exec 3>ctl); a lock someone holds fails: retry. - Closing a column's last pane leaves a +New in its place; Delcol closes the column. + lock/unlock need a held ctl fd (exec 3>ctl), a held lock fails: retry. A column's last pane -> +New. + Repl python on a terminal's ctl: a .py body's clicks go to it; tag words, Exec x, @`x` stay commands. diff --git a/src/mouse.zig b/src/mouse.zig index 0ec20df2..f222b5da 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -190,7 +190,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { else => false, }) for (p.panes) |slot| { const pane = slot orelse continue; - if (pane.prompt == .del_side) pane.prompt = .none; + if (pane.prompt == .del_side or pane.prompt == .repl_choice) pane.prompt = .none; }; if (m.button == .back or m.button == .forward) { if (m.kind == .press) p.jumpBy(if (m.button == .back) -1 else 1); @@ -719,6 +719,9 @@ fn dispatchPointerBuiltin( // nothing, as acme's look3 and execute return on an empty expansion. const operand = text orelse return; if (gesture) |g| if (reportGesture(p, id, cmd, operand, g.on_tag, g.operand, arg != null)) return; + // A middle click on a body is the exec a bound REPL may take. + p.exec_from_body = cmd == config.exec_cmd and gesture != null and !gesture.?.on_tag; + defer p.exec_from_body = false; exec.runBuiltin(p, cmd, id, "", exec.withArg(p, operand, arg)); } diff --git a/src/panes.zig b/src/panes.zig index 2f8b6b56..9234912f 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -72,6 +72,10 @@ pub const Pane = struct { /// Del from the keyboard with open panes both above and below: which /// one takes the rows. Nothing is typed; one key answers. del_side, + /// An exec from a file's body with several REPLs bound for its + /// language: which one takes it (exec.zig routeToRepl). One key + /// answers, the question being in `question`. + repl_choice, /// A new name for the file, drafted in place of the path on the /// tagline after a click there; Enter commits it, as a buffer name /// and never a disk rename. @@ -116,6 +120,18 @@ pub const Pane = struct { /// (Pardes.acknowledgeShell); empty until the host says which it ran. shell_tail: [96]u8 = undefined, shell_tail_len: u8 = 0, + /// A terminal bound as a language's REPL (`Repl python`): an exec from + /// the body of a file in that language is sent to it (exec.zig + /// routeToRepl). `letter` makes its id, `python-a`, with the language's + /// name from grammar_manifest. + repl: ?struct { lang: u8, letter: u8 } = null, + /// It has been told that its program takes no bracketed paste. + repl_warned: bool = false, + /// A question with its answers in it (`repl_choice`). + question: [96]u8 = undefined, + question_len: u8 = 0, + /// The newest message says where an exec was sent: it is tinted. + msg_sent: bool = false, /// The revision an Exit or a Restore last warned this pane was modified /// at, and which of them: only that word goes ahead on the warning /// (builtins.zig warnModified). @@ -360,6 +376,7 @@ pub const Pane = struct { return switch (p.prompt) { .none, .name => null, .del_side => config.del_question, + .repl_choice => p.question[0..p.question_len], else => p.input.own orelse "", }; } diff --git a/src/pardes.zig b/src/pardes.zig index 5ba95be3..9821839f 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -1391,6 +1391,100 @@ test "a spawn is for the pane it was made for, not whatever took the slot since" try std.testing.expectEqualStrings("second", Count.command[0.."second".len]); } +test "a REPL bound for a language takes the exec made on a body in it; tags, Exec by name and command words still run" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .shells = 3, .cols = 100, .rows = 30 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const file = try p.setTestFile("print(1)\nls\n"); + gpa.free(file.file.?.path); + file.file.?.path = try gpa.dupe(u8, "/x.py"); + const Sent = struct { + var to: [MAX_PANES][128]u8 = undefined; + var len: [MAX_PANES]usize = @splat(0); + var spawned: bool = false; + fn drain(pp: *Pardes) void { + len = @splat(0); + spawned = false; + while (pp.nextEffect()) |effect| switch (effect) { + .write => |w| { + @memcpy(to[w.pane][len[w.pane]..][0..w.bytes.slice().len], w.bytes.slice()); + len[w.pane] += w.bytes.slice().len; + }, + .spawn => spawned = true, + else => {}, + }; + } + fn said(pane: usize) []const u8 { + return to[pane][0..len[pane]]; + } + }; + // Only a terminal is a REPL; a language's name is the syntax table's. + try std.testing.expect(p.executeBuiltinLine(0, "Repl python")); + try std.testing.expect(file.repl == null); + try std.testing.expect(p.executeBuiltinLine(1, "Repl pithon")); + try std.testing.expect(p.panes[1].?.repl == null); + try std.testing.expect(std.mem.indexOf(u8, p.panes[1].?.msg[0..p.panes[1].?.msg_len], "python") != null); + try std.testing.expect(p.executeBuiltinLine(1, "Repl python")); + try std.testing.expect(p.executeBuiltinLine(1, "Repl python")); // again: no change + var idbuf: [48]u8 = undefined; + try std.testing.expectEqualStrings("python-a", exec.replId(&idbuf, p.panes[1].?)); + try std.testing.expect(std.mem.endsWith(u8, try tagline.tagPrefix(p, p.panes[1].?), " python-a")); + Sent.drain(p); + + // A click on the file's body, a single word: typed into the REPL. + p.exec_from_body = true; + try std.testing.expectEqual(@as(?usize, 1), exec.execute(p, 0, "ls")); + Sent.drain(p); + try std.testing.expectEqualStrings("ls\r", Sent.said(1)); + try std.testing.expect(!Sent.spawned); + try std.testing.expect(file.msg_sent); + try std.testing.expectEqualStrings("\u{2192} python-a", file.msg[0..file.msg_len]); + // Its own body too. + p.exec_from_body = true; + try std.testing.expectEqual(@as(?usize, 1), exec.execute(p, 1, "x = 1")); + Sent.drain(p); + try std.testing.expectEqualStrings("x = 1\r", Sent.said(1)); + + // Escapes: a tag's word, Exec by name, a command word. Each a command. + _ = exec.execute(p, 0, "ls"); + Sent.drain(p); + try std.testing.expect(Sent.spawned and Sent.len[1] == 0); + try std.testing.expect(p.executeBuiltinLine(0, "Exec ls")); + Sent.drain(p); + try std.testing.expect(Sent.spawned and Sent.len[1] == 0); + p.exec_from_body = true; + _ = exec.execute(p, 0, "@`ls`"); + Sent.drain(p); + try std.testing.expect(Sent.spawned and Sent.len[1] == 0); + + // Two bound: it asks, one key answers, Esc sends nowhere. + try std.testing.expect(p.executeBuiltinLine(2, "Repl python")); + try std.testing.expectEqualStrings("python-b", exec.replId(&idbuf, p.panes[2].?)); + Sent.drain(p); + p.exec_from_body = true; + try std.testing.expectEqual(@as(?usize, null), exec.execute(p, 0, "print(2)")); + try std.testing.expectEqual(Pane.Prompt.repl_choice, file.prompt); + try std.testing.expect(std.mem.indexOf(u8, file.promptText().?, "a b") != null); + p.update(.{ .key = .{ .cp = 'b' } }); + Sent.drain(p); + try std.testing.expectEqualStrings("print(2)\r", Sent.said(2)); + try std.testing.expect(Sent.len[1] == 0 and file.prompt == .none); + p.exec_from_body = true; + _ = exec.execute(p, 0, "print(3)"); + p.update(.{ .key = .{ .cp = Key.escape } }); + Sent.drain(p); + try std.testing.expect(Sent.len[1] == 0 and Sent.len[2] == 0); + + // Unbound, its letter is free again; bare, it says what it is. + try std.testing.expect(p.executeBuiltinLine(1, "Repl -")); + try std.testing.expect(p.panes[1].?.repl == null); + try std.testing.expect(p.executeBuiltinLine(1, "Repl python")); + try std.testing.expectEqualStrings("python-a", exec.replId(&idbuf, p.panes[1].?)); + try std.testing.expect(p.executeBuiltinLine(2, "Repl")); + try std.testing.expectEqualStrings("Repl: python-b", p.panes[2].?.msg[0..p.panes[2].?.msg_len]); +} + test "Tty+fish, one word a tag can hold, opens a terminal on that shell" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); @@ -3929,6 +4023,13 @@ pub const Pardes = struct { chord_arg: ?[]u8 = null, /// how many `execute` calls are on the stack — see max_exec_depth exec_depth: u8 = 0, + /// The exec under way was made by a gesture on a pane's body -- a + /// middle click, the execute key -- and so may go to a REPL bound for + /// the text's language; one run by name, `Exec ...`, never does. + exec_from_body: bool = false, + /// An exec waiting on the REPL question (`Pane.Prompt.repl_choice`): + /// the pane it came from, the language, and the text, owned. + repl_ask: ?struct { from: u32, lang: u8, text: []u8 } = null, /// A key press is being handled: someone is at the keyboard to answer, /// so a builtin may ask rather than guess. Nothing else sets it -- not /// a click, a 9P write, a startup line or a pane's shell exiting. @@ -4138,6 +4239,7 @@ pub const Pardes = struct { pub fn deinit(p: *Pardes) void { look.cancelLookHover(p); + if (p.repl_ask) |ask| p.gpa.free(ask.text); for (0..MAX_PANES) |id| p.dropPendingWrite(id); for (&p.panes) |*slot| if (slot.*) |pane| { p.teardownPane(pane); @@ -5015,6 +5117,18 @@ pub const Pardes = struct { // pane or a header edit is in: that key is its answer. for (p.panes, 0..) |slot, id| { const asked = slot orelse continue; + if (asked.prompt == .repl_choice) { + asked.prompt = .none; + const ask = p.repl_ask orelse return; + p.repl_ask = null; + defer p.gpa.free(ask.text); + // Its letter sends it there; anything else takes it back. + if (key.ctrl or key.alt or key.cp > 'z' or key.cp < 'a') return; + for (p.panes, 0..) |target, to| if (target) |repl| if (repl.repl) |r| + if (r.lang == ask.lang and r.letter == key.cp and exec.replLive(repl)) + return exec.sendToRepl(p, id, to, ask.text); + return; + } if (asked.prompt != .del_side) continue; asked.prompt = .none; if (hit(key, config.del_above)) exec.runBuiltin(p, .Del, id, "", "k"); @@ -5126,7 +5240,7 @@ pub const Pardes = struct { look.submitSearch(p, p.active) else if (normal.selRegexArmed(pane)) |_| if (target) |answered| normal.applySelRegex(p, pane, answered, "", false), - .none, .del_side, .name => unreachable, + .none, .del_side, .repl_choice, .name => unreachable, } pane.closePrompt(); if (target) |answered| { @@ -5164,6 +5278,9 @@ pub const Pardes = struct { return; } edit.pinPaneCursor(p, &pane.body); + // The execute key on a body is the exec a bound REPL may take. + p.exec_from_body = cmd == config.exec_cmd; + defer p.exec_from_body = false; const explicit = (p.native_images and pane.hasPdfSelection()) or (pane.body.vsel.active and pane.body.vsel.explicit) or pane.body.msel.active; if (explicit) { @@ -5999,12 +6116,16 @@ pub const Pardes = struct { // A message coming or going blends toward the page it sits // on; a grid cannot move it by less than a row. var style = msg_style; + // Where an exec was sent to a REPL reads in the tag's name + // tint, set apart from what the editor says. + const ink = if (kind == .message and pane.msg_sent) chrome.tag_name_fg else chrome.tag_fg; + if (kind == .message and pane.msg_sent) style.fg = .{ .rgb = ink }; if (Messages.noticeLife(pane, i)) |life| { // No page colour to fade to (a terminal's own default): // the text dissolves into its chip instead. const alpha = Messages.messageMotion(p, life).alpha; const page = th.bg orelse chrome.tag_bg; - style.fg = .{ .rgb = Messages.blendRgb(chrome.tag_fg, page, alpha) }; + style.fg = .{ .rgb = Messages.blendRgb(ink, page, alpha) }; style.bg = .{ .rgb = Messages.blendRgb(chrome.tag_bg, page, alpha) }; } s.fill(cx, row, chip, 1, .{ .bg = style.bg, .font_role = .tagline }); @@ -6014,7 +6135,7 @@ pub const Pardes = struct { // the detached wire will encode -- which drops every frame for // as long as the prompt is up. const printed = Messages.printRight(s, cx, row, chip -| 1, text, style); - if (kind != .prompt or id != p.active or pane.prompt == .del_side) continue; + if (kind != .prompt or id != p.active or pane.prompt == .del_side or pane.prompt == .repl_choice) continue; // The cursor follows the text to wherever it landed; a caret // in the part a narrow band dropped has nowhere to be. const prompt_col = panes.File.displayWidth(text[0..@min(@as(usize, @intCast(@max(0, pane.input.cur_col))), text.len)]); diff --git a/src/tagline.zig b/src/tagline.zig index 8c1efa7b..14bf5677 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -7,6 +7,7 @@ const modal = @import("modal.zig"); const ctlfs = @import("ninep/tree.zig"); const panes = @import("panes.zig"); const edit = @import("edit.zig"); +const exec = @import("exec.zig"); const config = @import("config.zig"); const pdf_enabled = panes.Pdf.enabled; const dump = @import("dump.zig"); @@ -114,9 +115,17 @@ pub fn pathPrefix(arena: std.mem.Allocator, pane: *Pane) ![]const u8 { if (pane.command) |line| { const shown = line[0..@min(line.len, 48)]; const more = if (shown.len < line.len) "..." else ""; - if (!pane.command_done) return std.fmt.allocPrint(arena, "{s} ({s}{s}) running", .{ pane.cwdSlice(), shown, more }); - if (pane.command_status) |n| return std.fmt.allocPrint(arena, "{s} ({s}{s}) exit {d}", .{ pane.cwdSlice(), shown, more, n }); - return std.fmt.allocPrint(arena, "{s} ({s}{s}) exit ?", .{ pane.cwdSlice(), shown, more }); + var idbuf: [48]u8 = undefined; + const id = exec.replId(&idbuf, pane); + const gap = if (id.len > 0) " " else ""; + if (!pane.command_done) return std.fmt.allocPrint(arena, "{s} ({s}{s}) running{s}{s}", .{ pane.cwdSlice(), shown, more, gap, id }); + if (pane.command_status) |n| return std.fmt.allocPrint(arena, "{s} ({s}{s}) exit {d}{s}{s}", .{ pane.cwdSlice(), shown, more, n, gap, id }); + return std.fmt.allocPrint(arena, "{s} ({s}{s}) exit ?{s}{s}", .{ pane.cwdSlice(), shown, more, gap, id }); + } + // A bound REPL says what it is bound as, beside its Tty word. + if (pane.repl != null) { + var idbuf: [48]u8 = undefined; + return std.fmt.allocPrint(arena, "{s} {s}", .{ pane.cwdSlice(), exec.replId(&idbuf, pane) }); } if (pane.file) |f| { const name = if (pane.prompt == .name) pane.input.own orelse f.path else f.path; diff --git a/test/snapshots/builtins.snap b/test/snapshots/builtins.snap index 9a58502f..84de680f 100644 --- a/test/snapshots/builtins.snap +++ b/test/snapshots/builtins.snap @@ -26,6 +26,7 @@ wheel up 110 50 wheel up 110 50 wheel up 110 50 wheel up 110 50 +wheel up 110 50 wait 10000 Look enter, right-click wait 10000 Exec tab, middle-click wait 10000 Filter -- cgit v1.3 From e87e16547a17864b2a0cd574c1aa42d44125bc6c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 16:35:27 -0300 Subject: Alt-o, Alt-i and the other tree-sitter keys walk the file's syntax tree helix's expand/shrink, previous/next sibling, all siblings, all children and parent-node end/start (Alt-o/up, Alt-i/down, Alt-p/left, Alt-right, Alt-a, Alt-I, Alt-e, Alt-b; Alt-n stays the new terminal) walk a whole-file parse the file keeps (File.node_tree), made on the first such key after an edit and reused until the next, never per key. syntax.walkNodes follows helix's TreeCursor over every node, anonymous ones included, and Alt-i goes back to what Alt-o grew from while the selection still holds it. The harness runs without grammars, so the cases prove the plain-text no-op; a test replays eleven JSON walks whose results were taken from the installed hx. Co-Authored-By: Claude Opus 5.5 --- docs/helix-keys.md | 4 +- src/File.zig | 13 +++++ src/config.zig | 10 ++++ src/modal.zig | 20 ++++++++ src/normal.zig | 124 +++++++++++++++++++++++++++++++++++++++++++++ src/syntax.zig | 90 ++++++++++++++++++++++++++++++++ test/hxcases/cases.jsonl | 1 + test/hxcases/goldens.jsonl | 1 + 8 files changed, 261 insertions(+), 2 deletions(-) (limited to 'src/File.zig') diff --git a/docs/helix-keys.md b/docs/helix-keys.md index 5c3972a5..f2901b92 100644 --- a/docs/helix-keys.md +++ b/docs/helix-keys.md @@ -127,7 +127,7 @@ language-backend queries, and the shell pipe. | `:` (normal, body or tag) | in the body, focuses the pane's tag in normal mode at its remembered cursor (the first time, on `Save`); in the tag, goes back to the body; in a column or workspace tag, back to the active pane. The tag's normal and insert modes ARE the body's: every motion, selection, edit and undo works there, and `0` goes to the line's start, the path's. Tab runs the word under the cursor or the selection and Enter looks it up (in a column or workspace tag Enter runs it too), and either hands the keyboard back to the body first. Clicks choose a new cursor position and type into the tag. | Each tag keeps its own cursor during the session. The computed path/marker/page is reachable and yankable but read-only: an edit into it is refused, and typing into a file's path drafts a new name. File-name changes are staged as described in [editable tags](tags.md). | pardes-specific | | `Ctrl-w k` / `SPC w k` (pane with nothing above) | focuses its column's tag, then the workspace tag; with `ColumnTags` disabled it goes directly to the workspace. `Ctrl-w j` walks back to the panes, `Ctrl-w h`/`l` walk the column tags. Headers edit exactly as a pane tag does. | Column commands target that column's active pane, or its first pane when coming from elsewhere. Workspace and column text are independently editable and persist in dumps. See [editable tags](tags.md). | pardes-specific | | `Ctrl-w` + `h/j/k/l`/arrows | directional pane focus prefix — editor normal mode only | pardes' own window handling (helix window mode skipped, section C). Runs the SAME `Left`/`Down`/`Up`/`Right` builtins `SPC w h/j/k/l` runs; Raw **tty** mode forwards Ctrl-w to the child. Insert mode owns `Ctrl-w` = delete-word-back, so a tag being TYPED into swallows it; from a tag in normal mode it moves focus to the neighbour's BODY, as from a body, and from the top pane `Up` reaches the column and workspace tags | pardes-specific | -| `Alt-n` | new terminal below (outside raw tty) | shadows helix `Alt-n` TS sibling-select — skipped anyway (tree-sitter) | pardes-specific | +| `Alt-n` | new terminal below (outside raw tty) | shadows helix `Alt-n` (select next sibling), which pardes spells `Alt-right` alone | pardes-specific | | `Alt-c` | move active terminal to a fresh column (outside raw tty) | helix `Alt-c` is change-noyank; the pardes window op wins (do-not-touch contract). `Alt-d` + `i` covers the behavior | waived (`alt-c-window-op`) | | `Space` (normal, body) | starts the pardes LEADER: a key path runs the same builtin words used by tags and the topbar. The main groups are `f` files, `h` docs, `c` columns, `t` toggles/effects, `a` panel animations, `s` session, `j` jumps, `l` language, and `w` directional focus; `SPC ?` lists every path and ` ?` lists one group in `+Help`. Neither `Exit` (quits the editor, acme's Exit) nor `Kill` (stops the commands pardes typed into terminals, acme's Kill) has a leader path: both are the topbar's and the root `ctl`'s. The pending path appears on the active pane's transient body/message row. Esc or an unmapped key abandons it. Paths, Help rows, and dispatch are all generated from the builtin registry at comptime; the leader applies only to a BODY in normal mode because tags and tty programs own their input | pardes-specific; helix spends Space on pickers/LSP (section C), while pardes uses acme-style executable words | | `SPC y` `SPC Y` `SPC p` `SPC P` `SPC R` | helix's clipboard menu on helix's own letters: yank the selection to the system clipboard (`ClipYank`) or the PRIMARY selection alone (`ClipYankMain`), paste the system clipboard after (`ClipPaste`) / before (`ClipPasteBefore`) the selection, replace the selection with it (`ClipReplace`) | the same as `"+y`, `"+p`, `"+P`, `"+R`: register `+` (and `*`) IS the desktop's clipboard, the only register that reaches it. `SPC y` writes `+` alone, as helix's does, not the default register too. Builtins rather than bare chords because a leader path names a builtin: they land in Help's index and are executable words like every other verb. The clipboard holds one text, so N values go out joined by newlines, as helix sends them. On a tty the write is OSC 52 out and the READ is OSC 52 back, which many terminals refuse or gate — so `SPC y` works there and `SPC p` can be a no-op | out of corpus | @@ -213,6 +213,7 @@ found. Pure text math in `modal.zig`: `findChar`, `matchBracket`, | `;` | collapse selection to cursor | drops vsel/msel, cursor stays | helix-verified (phase 5) | | `Alt-;` | flip anchor and head | vsel: swap cursor ↔ anchor; msel: cursor to the other end (r0/r1 swapped to keep the cursor-at-r1 invariant) | helix-verified (phase 5) | | `Alt-:` | make every range point forward | helix `ensure_selections_forward` | helix-verified | +| `Alt-o`/`Alt-up`, `Alt-i`/`Alt-down`, `Alt-p`/`Alt-left`, `Alt-right`, `Alt-a`, `Alt-I`, `Alt-e`, `Alt-b` | walk the file's syntax tree from every range: grow to the enclosing node (and remember what it grew from), shrink back to that or to the first child, the previous / next sibling (anonymous ones included, so often a comma), every named sibling or child, the enclosing named node's end / start (stretching to it in select mode) | helix `expand_selection` and kin, on a whole-file parse (`File.node_tree`) made on the first such key after an edit and reused until the next; a range the tree says nothing about, and every range of a file without a grammar, stays. Checked against the installed hx on JSON (`normal.zig` test): the harness runs without grammars, so it only proves the plain-text no-op | helix-verified (plain text), hx-checked (JSON) | | `%` | select whole buffer | vsel anchor 0,0, cursor on the buffer's last char | helix-verified (phase 5) | | `X` | snap selection to line bounds | vsel → msel over its row span; bare cursor → 1-line msel; msel: already line-wise, no-op | helix-verified (phase 5) | | `Alt-x` | shrink selection to line bounds | vsel only: partial first/last lines drop out; nothing left collapses the selection; msel: no-op | helix-verified (phase 5) | @@ -352,7 +353,6 @@ text. | `gw` | word-label jump | label-jump overlay machinery, not core editing | | `g.` | goto last modification | jumplist/history position tracking | | Window mode table: `Ctrl-w` + `w v s t f F h j k l q o H J K L ns nv` (+ Ctrl variants) | splits/window management | window mode — pardes has its own Ctrl-w focus + Alt-n/Alt-c + mouse layout drags | -| `Alt-o`/`Alt-up`, `Alt-i`/`Alt-down`, `Alt-p`/`Alt-left`, `Alt-n`/`Alt-right`, `Alt-a`, `Alt-I`, `Alt-e`, `Alt-b` | syntax-node selection | tree-sitter | | `]f [f ]t [t ]a [a ]c [c ]e [e ]T [T ]x [x` | TS unimpaired jumps | tree-sitter | | `]g [g ]G [G` | git change jumps | needs VCS diff state | | insert `Ctrl-x` | completion menu | completion exists, but not as a popup: insert-mode Tab straight after a `.` opens a buffer of candidate DECLARATIONS (section A). helix's menu itself is skipped | diff --git a/src/File.zig b/src/File.zig index 8ba58fbc..2c4f0aec 100644 --- a/src/File.zig +++ b/src/File.zig @@ -69,9 +69,19 @@ pub const State = struct { tree_context: bool = false, context_declarations: []syntax.ContextDeclaration = &.{}, context_revision: ?u32 = null, + /// The whole file's parse for the keys that walk its nodes (Alt-o and + /// kin), made on the first of them after an edit and kept until the next + /// one: `syntax.parseTree`'s, opaque here. + node_tree: ?*anyopaque = null, + node_tree_revision: u32 = 0, + /// helix's object_selections: what Alt-o grew from, for Alt-i to go back + /// to; gpa-owned ranges and the primary's index. + node_history: std.ArrayList(NodeStep) = .empty, history: *History, }; +pub const NodeStep = struct { ranges: []modal.Selection, primary: usize }; + pub fn dumpPane( arena: std.mem.Allocator, pane: *const Pane, @@ -816,6 +826,9 @@ pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { if (file.highlights.len > 0) p.tree_sitter_gpa.free(file.highlights); locations.freeRows(p.gpa, file.location_rows); if (file.context_declarations.len > 0) p.tree_sitter_gpa.free(file.context_declarations); + if (file.node_tree) |tree| syntax.freeTree(tree); + for (file.node_history.items) |step| p.gpa.free(step.ranges); + file.node_history.deinit(p.gpa); for (file.history.undo[0..file.history.undo_len]) |snap| p.gpa.free(snap.content); for (file.history.redo[0..file.history.redo_len]) |snap| p.gpa.free(snap.content); p.gpa.destroy(file.history); diff --git a/src/config.zig b/src/config.zig index 8c5c9771..959f4c4a 100644 --- a/src/config.zig +++ b/src/config.zig @@ -537,6 +537,16 @@ pub const split_regex: []const Chord = &.{.{ .cp = 'S' }}; pub const keep_regex: []const Chord = &.{.{ .cp = 'K' }}; pub const remove_regex: []const Chord = &.{.{ .cp = 'K', .alt = true }}; pub const ensure_forward: []const Chord = &.{.{ .cp = ':', .alt = true }}; +// helix's tree-sitter selection; Alt-n stays the new terminal, so the next +// sibling is Alt-right alone +pub const expand_node: []const Chord = &.{ .{ .cp = 'o', .alt = true }, .{ .cp = Key.up, .alt = true } }; +pub const shrink_node: []const Chord = &.{ .{ .cp = 'i', .alt = true }, .{ .cp = Key.down, .alt = true } }; +pub const prev_sibling: []const Chord = &.{ .{ .cp = 'p', .alt = true }, .{ .cp = Key.left, .alt = true } }; +pub const next_sibling: []const Chord = &.{.{ .cp = Key.right, .alt = true }}; +pub const all_siblings: []const Chord = &.{.{ .cp = 'a', .alt = true }}; +pub const all_children: []const Chord = &.{.{ .cp = 'I', .alt = true }}; +pub const parent_node_end: []const Chord = &.{.{ .cp = 'e', .alt = true }}; +pub const parent_node_start: []const Chord = &.{.{ .cp = 'b', .alt = true }}; pub const delete: []const Chord = &.{.{ .cp = 'd' }}; pub const delete_noyank: []const Chord = &.{.{ .cp = 'd', .alt = true }}; diff --git a/src/modal.zig b/src/modal.zig index f5f3081e..ae008f60 100644 --- a/src/modal.zig +++ b/src/modal.zig @@ -100,6 +100,14 @@ pub const Normal = struct { keep_regex, remove_regex, ensure_forward, + expand_node, + shrink_node, + next_sibling, + prev_sibling, + all_siblings, + all_children, + parent_node_end, + parent_node_start, delete, delete_noyank, @@ -213,6 +221,8 @@ pub const Normal = struct { } }; + /// helix's tree-sitter selection keys: where a range goes in the tree + pub const NodeWalk = enum { expand, shrink, next_sibling, prev_sibling, all_siblings, all_children, parent_end, parent_start }; /// what the s/S/K/Alt-K prompt does with its pattern's matches pub const RegexMode = enum { select, split, keep, remove }; pub const Scope = enum { once, per_selection }; @@ -331,6 +341,7 @@ pub const Normal = struct { search_step: Direction, macro_record, macro_replay: u32, + node: NodeWalk, repeat_insert: u32, pub fn scope(value: Action) Scope { @@ -345,6 +356,7 @@ pub const Normal = struct { .search_step, .macro_record, .macro_replay, + .node, .repeat_insert, => .once, .edit => |edit| switch (edit.kind) { @@ -588,6 +600,14 @@ pub const Normal = struct { if (key.has(.keep_regex)) return resultAction(.{ .select_regex = .keep }); if (key.has(.remove_regex)) return resultAction(.{ .select_regex = .remove }); if (key.has(.ensure_forward)) return resultAction(.{ .multi = .{ .kind = .ensure_forward, .count = count } }); + if (key.has(.expand_node)) return resultAction(.{ .node = .expand }); + if (key.has(.shrink_node)) return resultAction(.{ .node = .shrink }); + if (key.has(.next_sibling)) return resultAction(.{ .node = .next_sibling }); + if (key.has(.prev_sibling)) return resultAction(.{ .node = .prev_sibling }); + if (key.has(.all_siblings)) return resultAction(.{ .node = .all_siblings }); + if (key.has(.all_children)) return resultAction(.{ .node = .all_children }); + if (key.has(.parent_node_end)) return resultAction(.{ .node = .parent_end }); + if (key.has(.parent_node_start)) return resultAction(.{ .node = .parent_start }); if (key.has(.delete)) return resultAction(.{ .edit = .{ .kind = .delete, .count = count } }); if (key.has(.delete_noyank)) return resultAction(.{ .edit = .{ .kind = .delete_noyank, .count = count } }); diff --git a/src/normal.zig b/src/normal.zig index d6c646ef..bc450581 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -7,6 +7,7 @@ const exec = @import("exec.zig"); const look = @import("look.zig"); const std = @import("std"); const regexp = @import("regexp.zig"); +const syntax = @import("syntax.zig"); const modal = @import("modal.zig"); const panes = @import("panes.zig"); const edit = @import("edit.zig"); @@ -166,6 +167,83 @@ pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, mode: m t.setRanges(text, out[0..m], &.{}, 0, true); // helix keeps primary 0 (its own TODO) } +/// helix's tree-sitter selection keys: every range walks the file's parse, +/// which is made on the first of these keys after an edit and kept, never +/// made again for a key that changed nothing. A range the tree has nothing +/// to say about stays as it was; a text without a grammar, all of them. +fn nodeSelect(p: *Pardes, pane: *Pane, t: *Text, walk: modal.Normal.NodeWalk) void { + if (t.what != .body) return; + const f = if (pane.file) |*file| file else return; + if (f.node_tree == null or f.node_tree_revision != f.revision) { + if (f.node_tree) |old| syntax.freeTree(old); + f.node_tree = syntax.parseTree(f.path, f.content); + f.node_tree_revision = f.revision; + for (f.node_history.items) |step| p.gpa.free(step.ranges); + f.node_history.clearRetainingCapacity(); + } + const tree = f.node_tree orelse return; + const text = f.content; + const expl = (t.vsel.active and t.vsel.explicit) or t.msel.active; + const arena = p.scratch.allocator(); + const rs = arena.alloc(modal.Selection, Text.max_selections) catch return; + const got = t.ranges(text, 0, rs[0..Text.max_selections]); + if (walk == .shrink) if (f.node_history.pop()) |prev| { + defer p.gpa.free(prev.ranges); + // back to what Alt-o grew from, while the selection still holds it + const holds = for (prev.ranges) |pr| { + const pf = @min(pr.anchor, pr.head); + const pt = @max(pr.anchor, pr.head); + if (for (rs[0..got.n]) |r| { + if (@min(r.anchor, r.head) <= pf and pt <= @max(r.anchor, r.head)) break true; + } else false) continue; + break false; + } else true; + if (holds) return t.setRanges(text, prev.ranges, &.{}, prev.primary, expl); + for (f.node_history.items) |step| p.gpa.free(step.ranges); + f.node_history.clearRetainingCapacity(); + }; + const out = arena.alloc(modal.Selection, Text.max_selections) catch return; + const spans = arena.alloc(syntax.Span, Text.max_selections) catch return; + var m: usize = 0; + for (rs[0..got.n]) |r| { + if (m == out.len) break; + const from = @min(r.anchor, r.head); + const to = @max(r.anchor, r.head); + const back = r.head < r.anchor; + const n = syntax.walkNodes(tree, walk, from, to, modal.selectionCursor(text, r), spans[0 .. out.len - m]); + if (n == 0) { + out[m] = r; + m += 1; + continue; + } + for (spans[0..n]) |s| { + out[m] = switch (walk) { + .next_sibling => .{ .anchor = s.from, .head = s.to }, + .prev_sibling => .{ .anchor = s.to, .head = s.from }, + // helix move_parent_node_end: a one-character range on the + // bound, or stretched to it in select mode + .parent_end, .parent_start => bound: { + const head = s.from; + if (t.select) { + const anchor = r.anchor; + break :bound .{ .anchor = anchor, .head = if (head >= anchor) modal.nextGrapheme(text, head) else head }; + } + const next = modal.nextGrapheme(text, head); + break :bound if (back) .{ .anchor = next, .head = head } else .{ .anchor = head, .head = next }; + }, + else => if (back) .{ .anchor = s.to, .head = s.from } else .{ .anchor = s.from, .head = s.to }, + }; + m += 1; + } + } + const same = m == got.n and std.mem.eql(u8, std.mem.sliceAsBytes(out[0..m]), std.mem.sliceAsBytes(rs[0..m])); + if (walk == .expand and !same) remember: { + const ranges = p.gpa.dupe(modal.Selection, rs[0..got.n]) catch break :remember; + f.node_history.append(p.gpa, .{ .ranges = ranges, .primary = got.pri }) catch p.gpa.free(ranges); + } + t.setRanges(text, out[0..m], &.{}, @min(got.pri, m - 1), expl); +} + const KeyState = struct { mode: Text.Mode, select: bool, @@ -613,6 +691,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void p, if (direction == .forward) @as(i32, 1) else -1, ), + .node => |walk| return nodeSelect(p, pane, t, walk), .macro_record => { const m = &p.macro; if (m.recording == 0) { @@ -840,3 +919,48 @@ test "s and S search a multi-line selection as addr does: ^ and $ per line, . wi } } } + +test "tree-sitter selection keys do in a JSON file what hx 25.07.1 does" { + if (!syntax.supportsPath("a.json")) return; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const text = "{\"a\": [1, 2, 3], \"b\": true}\n"; + // each checked against the installed hx through a pty: the keys, then + // the text it saved + const Case = struct { keys: []const u8, want: []const u8 }; + for ([_]Case{ + .{ .keys = "10l\x1bo" ++ "d", .want = "{\"a\": , \"b\": true}\n" }, + .{ .keys = "10l\x1bo\x1bod", .want = "{, \"b\": true}\n" }, + .{ .keys = "10l\x1bo\x1bo\x1bod", .want = "\n" }, + .{ .keys = "10l\x1bo\x1bIix\x1b", .want = "{\"a\": [x1, x2, x3], \"b\": true}\n" }, + .{ .keys = "10l\x1bo\x1bo\x1b>d", .want = "{\"a\": [1, 2, 3] \"b\": true}\n" }, + .{ .keys = "10l\x1bpd", .want = "{\"a\": [1 2, 3], \"b\": true}\n" }, + .{ .keys = "10l\x1baix\x1b", .want = "{\"a\": [x1, x2, x3], \"b\": true}\n" }, + .{ .keys = "10l\x1bo\x1bo\x1bid", .want = "{\"a\": , \"b\": true}\n" }, + .{ .keys = "6lx\x1bid", .want = "\n" }, + .{ .keys = "10l\x1beiX\x1b", .want = "{\"a\": [1, 2X, 3], \"b\": true}\n" }, + .{ .keys = "10l\x1bb\x1bbiX\x1b", .want = "{X\"a\": [1, 2, 3], \"b\": true}\n" }, + }) |c| { + const pane = try p.setTestFile(text); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, "/test.json"); + // ESC before a key is Alt on it; a lone ESC is Esc; `>` is Alt-right + var i: usize = 0; + while (i < c.keys.len) : (i += 1) { + const ch = c.keys[i]; + if (ch == 0x1b and i + 1 < c.keys.len) { + i += 1; + const k = c.keys[i]; + p.update(.{ .key = if (k == '>') .{ .cp = Key.right, .alt = true } else .{ .cp = k, .alt = true } }); + } else if (ch == 0x1b) { + p.update(.{ .key = .{ .cp = Key.escape } }); + } else p.update(.{ .key = .{ .cp = ch, .text = c.keys[i..][0..1] } }); + while (p.nextEffect()) |_| {} + } + std.testing.expectEqualStrings(c.want, pane.file.?.content) catch |err| { + std.debug.print("keys {s}\n", .{c.keys}); + return err; + }; + } +} diff --git a/src/syntax.zig b/src/syntax.zig index 9c1a4f4b..89fc4198 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -337,6 +337,96 @@ pub fn supportsPath(path: []const u8) bool { return false; } +/// A whole file's parse, kept by the file for the keys that walk its nodes +/// (helix's Alt-o and kin). Opaque outside this file; null without a grammar. +pub fn parseTree(path: []const u8, content: []const u8) ?*anyopaque { + if (!enabled) return null; + const selected = (forExt(std.fs.path.extension(path)) catch return null) orelse return null; + const tree = selected.parser.parseString(content, null) orelse return null; + return @ptrCast(tree); +} + +pub fn freeTree(tree: *anyopaque) void { + if (!enabled) return; + const t: *ts.Tree = @ptrCast(@alignCast(tree)); + t.destroy(); +} + +/// Where a node walk goes from a range (helix object.rs and movement.rs). +pub const NodeWalk = @import("modal.zig").Normal.NodeWalk; +pub const Span = struct { from: usize, to: usize }; + +/// The spans `walk` takes the byte range [from, to) to, into `out`; `at` is +/// the range's cursor. None when the tree has nothing to say there. +pub fn walkNodes(tree_ptr: *anyopaque, walk: NodeWalk, from: usize, to: usize, at: usize, out: []Span) usize { + if (!enabled or out.len == 0) return 0; + const tree: *const ts.Tree = @ptrCast(@alignCast(tree_ptr)); + const lo: u32 = @intCast(@min(from, std.math.maxInt(u32))); + const hi: u32 = @intCast(@min(to, std.math.maxInt(u32))); + if (walk == .parent_end or walk == .parent_start) { + var node = tree.rootNode().namedDescendantForByteRange(lo, hi) orelse return 0; + if (walk == .parent_end) { + out[0] = .{ .from = node.endByte(), .to = node.endByte() }; + return 1; + } + // already at the node's lo: its first ancestor that starts earlier + if (node.startByte() == at) { + const first = node.startByte(); + while (node.startByte() >= first or !node.isNamed()) node = node.parent() orelse break; + } + out[0] = .{ .from = node.startByte(), .to = node.startByte() }; + return 1; + } + var cursor = tree.walk(); + defer cursor.destroy(); + // helix TreeCursor.reset_to_byte_range: the smallest node holding the range + while (true) { + const node = cursor.node(); + if (lo < node.startByte() or hi > node.endByte()) { + _ = cursor.gotoParent(); + break; + } + if (cursor.gotoFirstChildForByte(lo) == null) break; + } + switch (walk) { + .expand => while (cursor.node().startByte() == lo and cursor.node().endByte() == hi) { + if (!cursor.gotoParent()) break; + }, + .shrink => _ = cursor.gotoFirstChild(), + .next_sibling => while (!cursor.gotoNextSibling()) { + if (!cursor.gotoParent()) break; + }, + .prev_sibling => while (!cursor.gotoPreviousSibling()) { + if (!cursor.gotoParent()) break; + }, + .all_siblings, .all_children => { + if (walk == .all_siblings) { + while (true) { + if (!cursor.gotoParent()) return 0; + if (cursor.node().childCount() > 1) break; + } + } + // the named children, or nothing to say + var n: usize = 0; + if (!cursor.gotoFirstChild()) return 0; + while (true) { + const child = cursor.node(); + if (child.isNamed() and n < out.len) { + out[n] = .{ .from = child.startByte(), .to = child.endByte() }; + n += 1; + } + if (!cursor.gotoNextSibling()) break; + } + return n; + }, + .parent_end, .parent_start => unreachable, + } + const node = cursor.node(); + out[0] = .{ .from = node.startByte(), .to = node.endByte() }; + return 1; +} + + /// Owned source analysis. Both slices use the allocator passed to analyzeSource. /// The parsed tree is released before returning; callers can cache this result. pub const SourceAnalysis = struct { diff --git a/test/hxcases/cases.jsonl b/test/hxcases/cases.jsonl index 43cbbf11..8a8f8a94 100644 --- a/test/hxcases/cases.jsonl +++ b/test/hxcases/cases.jsonl @@ -440,6 +440,7 @@ {"name": "keep-regex-lines", "pane": "file", "text": "foo\nbar\nbaz\n", "keys": "%K^b"} {"name": "ensure-forward", "pane": "file", "text": "ab cd\n", "keys": "%s\\w+"} {"name": "ensure-forward-one", "pane": "file", "text": "abc\n", "keys": "vll"} +{"name": "node-keys-plain-text", "pane": "file", "text": "ab cd\n", "keys": "w"} {"name": "msel-align-basic", "pane": "file", "text": "a=1\nbbb=2\n", "keys": "%s=&"} {"name": "msel-align-columns", "pane": "file", "text": "a,b,c\nccc,d,e\n", "keys": "%s,&"} {"name": "msel-align-uneven", "pane": "file", "text": "a,b\nccc,d,eee,f\n", "keys": "%s,&"} diff --git a/test/hxcases/goldens.jsonl b/test/hxcases/goldens.jsonl index 9839335a..f1df5c0a 100644 --- a/test/hxcases/goldens.jsonl +++ b/test/hxcases/goldens.jsonl @@ -440,6 +440,7 @@ {"name":"keep-regex-lines","text":"foo\nbar\nbaz\n","mode":"normal","cursor":{"row":1,"col":2},"anchor":{"row":1,"col":0},"sels":[{"cursor":{"row":1,"col":2},"anchor":{"row":1,"col":0}},{"cursor":{"row":2,"col":2},"anchor":{"row":2,"col":0}}],"primary":0} {"name":"ensure-forward","text":"ab cd\n","mode":"normal","cursor":{"row":0,"col":1},"anchor":{"row":0,"col":0},"sels":[{"cursor":{"row":0,"col":1},"anchor":{"row":0,"col":0}},{"cursor":{"row":0,"col":4},"anchor":{"row":0,"col":3}}],"primary":0} {"name":"ensure-forward-one","text":"abc\n","mode":"select","cursor":{"row":0,"col":2},"anchor":{"row":0,"col":0}} +{"name":"node-keys-plain-text","text":"ab cd\n","mode":"normal","cursor":{"row":0,"col":2},"anchor":{"row":0,"col":0}} {"name":"msel-align-basic","text":"a =1\nbbb=2\n","mode":"normal","cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3},"sels":[{"cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3}},{"cursor":{"row":1,"col":3},"anchor":{"row":1,"col":3}}],"primary":0} {"name":"msel-align-columns","text":"a ,b,c\nccc,d,e\n","mode":"normal","cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3},"sels":[{"cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3}},{"cursor":{"row":0,"col":5},"anchor":{"row":0,"col":5}},{"cursor":{"row":1,"col":3},"anchor":{"row":1,"col":3}},{"cursor":{"row":1,"col":5},"anchor":{"row":1,"col":5}}],"primary":0} {"name":"msel-align-uneven","text":"a ,b\nccc,d,eee,f\n","mode":"normal","cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3},"sels":[{"cursor":{"row":0,"col":3},"anchor":{"row":0,"col":3}},{"cursor":{"row":1,"col":3},"anchor":{"row":1,"col":3}},{"cursor":{"row":1,"col":5},"anchor":{"row":1,"col":5}},{"cursor":{"row":1,"col":9},"anchor":{"row":1,"col":9}}],"primary":0} -- cgit v1.3 From cbb6f821c29ede01648cdd41d2f1d2259a387645 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 17:59:09 -0300 Subject: Text brought back to what was saved is clean again dirty compared revisions only, so undoing to the save point, or typing the text back, left the pane dirty. The saved text's hash is kept from the first edit after a save or load, and an edit that makes the text equal to it marks the pane saved again, as undo to the save point does in acme. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 9 +++++++++ src/ninep/ctl.zig | 14 ++++++++++++++ test/snapshots/chordcut.golden | 1 - test/snapshots/lsp-client-edit.golden | 3 +++ test/snapshots/lsp-rename.golden | 2 ++ test/snapshots/pipe.golden | 1 + test/snapshots/selregex.golden | 1 + 7 files changed, 30 insertions(+), 1 deletion(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index b8368482..929e33bf 100644 --- a/src/File.zig +++ b/src/File.zig @@ -53,6 +53,10 @@ pub const State = struct { /// Revision last known to match disk, after Save or an external reload. /// Equal means the screen matches disk. saved_revision: u32 = 0, + /// The text at `saved_revision`, hashed as the first edit after it + /// replaces it: an edit that brings the text back to it is clean again, + /// as an undo to the save point is in acme. + saved_hash: ?u64 = null, watch_after_save: bool = false, /// Seconds of the last content change, for the filesystem's stat; zero until edited. mtime: u32 = 0, @@ -859,9 +863,14 @@ pub fn setContent(p: *Pardes, f: *State, new: []u8) void { if (f.mini) |*mini| mini.deinit(p.gpa); f.mini = null; const starts: []usize = if (f.line_starts.len > 0) editedLineStarts(p.gpa, f.line_starts, f.content, new) catch &.{} else &.{}; + // ponytail: a whole-text hash per edit; a rolling hash when files grow large. + if (f.revision == f.saved_revision or f.saved_hash == null) f.saved_hash = std.hash.Wyhash.hash(0, f.content); p.gpa.free(f.content); f.content = new; f.revision +%= 1; + if (f.saved_hash) |h| if (std.hash.Wyhash.hash(0, new) == h) { + f.saved_revision = f.revision; + }; f.mtime = pardes.ctlfs.events.now(); if (f.line_starts.len > 0) p.gpa.free(f.line_starts); f.line_starts = starts; diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index bb562672..16935f41 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -744,6 +744,20 @@ test "a second lock is refused until the holder unlocks or closes, and binds nob for (p.fs.opens) |o| try testing.expect(o.node == 0); } +test "dirty goes back to 0 when the text is the saved text again" { + const p = try withFile(testing.allocator, "one\n"); + defer p.deinit(); + const serial = serialOf(p); + const dirty = Node.of(serial, .dirty); + try testing.expectEqualStrings("0\n", rd(p, dirty, 0, 8).bytes); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .body), "two\n").reply.status); + try testing.expectEqualStrings("1\n", rd(p, dirty, 0, 8).bytes); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Undo").reply.status); + try testing.expectEqualStrings("0\n", rd(p, dirty, 0, 8).bytes); + try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Redo").reply.status); + try testing.expectEqualStrings("1\n", rd(p, dirty, 0, 8).bytes); +} + test "a message from a root ctl write is the session's in the log" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); diff --git a/test/snapshots/chordcut.golden b/test/snapshots/chordcut.golden index d5266717..120b261f 100644 --- a/test/snapshots/chordcut.golden +++ b/test/snapshots/chordcut.golden @@ -77,7 +77,6 @@ |13: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-59 d,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, |14: 0-0 d,#608269, 1-1 d,#0d1410, 2-6 #616f64,#0d1410,b 7-12 #e5eee5,#0d1410, 13-59 d,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, == snap ttyprobe grid=120x31 cursor=42,22 -|12: /tmp/pardes-snap/chordcut/cwd/g.txt * Save Tty Collapse D |17: $ /tmp/pardes-snap/chordcut/cwd Tty+bash Save Mode Filter C |18: $ ls |20: $ stty -icanon -echo; printf '\x1b[?2004h\x1b[?1000h\x1b[? diff --git a/test/snapshots/lsp-client-edit.golden b/test/snapshots/lsp-client-edit.golden index c75bae4c..81079615 100644 --- a/test/snapshots/lsp-client-edit.golden +++ b/test/snapshots/lsp-client-edit.golden @@ -12,6 +12,7 @@ | 8 } | 9 == snap unformatted grid=100x25 cursor=7,3 +|2: /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext |3: 1 mod lib; |4: 2 |5: 3 fn main() { @@ -22,10 +23,12 @@ |10: 8 |11: == snap renamed grid=100x25 cursor=12,5 +|2: /tmp/pardes-snap/lsp-client-edit/cwd/main.rs * Save Tty Collapse Del TreeContext |3: 1 mod lib; renamed 2 range(s) |6: 4 let x = sum(1, 2); |7: 5 let y = sum(3, 4); == snap unrenamed grid=100x25 cursor=12,5 +|2: /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext |3: 1 mod lib; |6: 4 let x = add(1, 2); |7: 5 let y = add(3, 4); diff --git a/test/snapshots/lsp-rename.golden b/test/snapshots/lsp-rename.golden index f6dc8358..26571b26 100644 --- a/test/snapshots/lsp-rename.golden +++ b/test/snapshots/lsp-rename.golden @@ -18,9 +18,11 @@ | 14 } | 15 == snap undone grid=110x25 cursor=17,10 +|2: /tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse Del TreeContext |3: 1 const std = @import("std"); |5: 3 fn helper(x: u32) u32 { |10: 8 _ = helper(41); == snap redone grid=110x25 cursor=17,10 +|2: /tmp/pardes-snap/lsp-rename/cwd/rename.zig * Save Tty Collapse Del TreeContext |5: 3 fn renamed_helper(x: u32) u32 { |10: 8 _ = renamed_helper(41); diff --git a/test/snapshots/pipe.golden b/test/snapshots/pipe.golden index 14353ebf..6b7347bf 100644 --- a/test/snapshots/pipe.golden +++ b/test/snapshots/pipe.golden @@ -8,4 +8,5 @@ |2: /tmp/pardes-snap/pipe/cwd/pipe.txt * Save Tty Collapse Del |3: 1 ALPHA BETA == snap undone grid=180x13 cursor=17,3 +|2: /tmp/pardes-snap/pipe/cwd/pipe.txt Save Tty Collapse Del |3: 1 alpha beta diff --git a/test/snapshots/selregex.golden b/test/snapshots/selregex.golden index 8b45ae43..7362a85a 100644 --- a/test/snapshots/selregex.golden +++ b/test/snapshots/selregex.golden @@ -56,6 +56,7 @@ |4: 2 // const two = 2; |5: 3 // const three = 3; == snap uncommented grid=160x25 cursor=11,3 +|2: /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse Del TreeContext |3: 1 const one = 1; |4: 2 const two = 2; |5: 3 const three = 3; -- cgit v1.3 From e988d4e24bfc0b80285754359b4b86f1b15b33f6 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 00:54:58 -0300 Subject: Restore keeps each pane's dot, as acme's dump does A restored text pane came back with its caret at its view's top, whatever had been selected. The dump now keeps each text pane's dot, q0 and q1 as acme's keeps a window's, and Restore puts it back without moving the view it kept. Two look-walk tests that restored and walked on now start from the match they were on. Co-Authored-By: Claude Opus 5.5 --- docs/config.md | 4 +++- src/File.zig | 8 ++++++++ src/dump.zig | 24 ++++++++++++++++++++++++ test/output.zig | 15 ++++++++++----- 4 files changed, 45 insertions(+), 6 deletions(-) (limited to 'src/File.zig') diff --git a/docs/config.md b/docs/config.md index 43b289cb..88f809ed 100644 --- a/docs/config.md +++ b/docs/config.md @@ -637,7 +637,9 @@ uses the argument as a path as before. Absolute paths and argument-free Restore retain their existing behavior. `Dump` still honors `$PARDES_DUMP` and otherwise writes a timestamped file in the default directory. -A dump keeps the settings that differ from a fresh session's (`Placement +A dump keeps each text pane's dot (its selection, or the caret), as acme's +keeps a window's q0 and q1, and a Restore puts it back where the kept view +shows it. It keeps the settings that differ from a fresh session's (`Placement pardes`, `Verbose off`, a shader), as the root ctl reads them, and a Restore sets them again; the theme is kept with the layout, and the font stays the frontend's. REPL bindings are not kept. diff --git a/src/File.zig b/src/File.zig index 929e33bf..6a1ac319 100644 --- a/src/File.zig +++ b/src/File.zig @@ -814,6 +814,14 @@ pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { pane.file.?.tree_context = saved.tree_context and supportsContext(pane); pane.body.cur_pinned = true; pane.body.cur_row = @intCast(src.scroll); + // Its dot as it was, where the view the dump kept shows it. + if (saved.dot) |dot| if (dot[0] <= dot[1] and dot[1] <= content.len) { + const a = modal.positionAt(content, dot[0]); + const h = modal.positionAt(content, if (dot[1] > dot[0]) modal.prevGrapheme(content, dot[1]) else dot[0]); + pane.body.vsel = .{ .active = dot[1] > dot[0], .row = @intCast(a.row), .col = @intCast(a.col), .explicit = true }; + pane.body.cur_row = @intCast(h.row); + pane.body.cur_col = @intCast(h.col); + }; pane.cols = @max(1, src.cols); pane.rows = @max(1, src.rows); if (output == null and filesystem.localPath(path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true, .mode = .baseline_disk } }); diff --git a/src/dump.zig b/src/dump.zig index 5b0983ad..7101b708 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -142,6 +142,9 @@ pub const File = struct { origin_arg: []const u8 = "", mini_source: []const u8 = "", mini_colors_b64: []const u8 = "", + /// Its dot, q0 and q1 in bytes, as acme's dump keeps a window's; null + /// in older dumps. + dot: ?[2]u32 = null, }; pub const ImagePalette = enum { @@ -653,6 +656,10 @@ pub fn dumpState(p: *Pardes) !void { else try pardes.panes.Terminal.dumpPane(pane, arena, tag, body, scroll); dp.tag_tail = pane.tag.own; + if (dp.file) |*df| { + const dot = ctlfs.pane.dotOf(pane); + df.dot = .{ dot.q0, dot.q1 }; + } dp.serial = pane.serial; dump_panes[panes_len] = dp; panes_len += 1; @@ -918,3 +925,20 @@ test "a dump keeps the settings that differ from a fresh session's, and a restor try std.testing.expectEqual(config.Runtime.Placement.pardes, restored.settings.placement); try std.testing.expect(!restored.settings.verbose); } + +test "a restored pane keeps its dot, as acme's dump keeps a window's" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("one two three\nfour\n"); + ctlfs.pane.setDot(pane, .{ .q0 = 4, .q1 = 7 }); + try dumpState(p); + const restored = try initFromDump(gpa, .{ .tty_only = true }, p.dump_out.?); + defer restored.deinit(); + const again = for (restored.panes) |slot| { + if (slot) |candidate| if (candidate.file != null) break candidate; + } else return error.FileLost; + const dot = ctlfs.pane.dotOf(again); + try std.testing.expectEqual(@as(u32, 4), dot.q0); + try std.testing.expectEqual(@as(u32, 7), dot.q1); +} diff --git a/test/output.zig b/test/output.zig index e49ec4ff..95cdbfb7 100644 --- a/test/output.zig +++ b/test/output.zig @@ -799,13 +799,16 @@ test "n/N skips formatted context and selects comment match locations" { defer restored.deinit(); pardes.look.armLookWalk(restored, id); const restored_result = restored.panes[id].?; - restored.update(.{ .key = .{ .cp = 'n' } }); + // The dot came back on the match it was on (the first), so the + // walk goes on from there. try std.testing.expectEqual(@as(i32, @intCast(matches[0])), restored_result.body.cur_row); - restored.update(.{ .key = .{ .cp = 'N' } }); + restored.update(.{ .key = .{ .cp = 'n' } }); try std.testing.expectEqual(@as(i32, @intCast(matches[1])), restored_result.body.cur_row); + restored.update(.{ .key = .{ .cp = 'N' } }); + try std.testing.expectEqual(@as(i32, @intCast(matches[0])), restored_result.body.cur_row); const restored_file = &restored_result.file.?; - const last = modal.lineSlice(restored_file.content, matches[1]); - try std.testing.expectEqualStrings(last[0..restored_file.location_rows[matches[1]].location_end], selectedOutputText(restored_result) orelse ""); + const last = modal.lineSlice(restored_file.content, matches[0]); + try std.testing.expectEqualStrings(last[0..restored_file.location_rows[matches[0]].location_end], selectedOutputText(restored_result) orelse ""); } } } @@ -1587,7 +1590,9 @@ test "stacked search and LSP results retain source tint navigation and dump owne } restored.active = id; pardes.look.armLookWalk(restored, id); - restored.update(.{ .key = .{ .cp = 'N' } }); + // The dot came back on the match it was on; the walk goes on. + try std.testing.expectEqual(@as(i32, @intCast(matches[0])), restored.panes[id].?.body.cur_row); + restored.update(.{ .key = .{ .cp = 'n' } }); try std.testing.expectEqual(@as(i32, @intCast(matches[1])), restored.panes[id].?.body.cur_row); try std.testing.expectEqualStrings(source_text, source.file.?.content); } -- cgit v1.3 From 3e941015ebd2da88a296479f407e9bbf06287234 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 03:31:23 -0300 Subject: A pane restored with unsaved text is asked about before it is thrown away Exit, Restore, Del and get warn only about a pane edited since it was opened, which its saved hash says (set at its first edit). A pane a Dump kept dirty came back with no hash, so a restored session quit at once over it. Restoring one dirty now gives it a hash its text does not match. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 4 ++++ src/dump.zig | 34 ++++++++++++++++++++++++++++++++++ 2 files changed, 38 insertions(+) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index 6a1ac319..810bc766 100644 --- a/src/File.zig +++ b/src/File.zig @@ -809,6 +809,10 @@ pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { .location_rows = location_rows, .scroll = src.scroll, .revision = @intFromBool(saved.dirty), + // Restored with unsaved text, it has text to lose as an edited pane + // has: a hash its text does not match, so Exit, Restore, Del and + // get ask first (builtins.warnModifiedIn reads only edited panes). + .saved_hash = if (saved.dirty) std.hash.Wyhash.hash(0, content) +% 1 else null, .history = history, }; pane.file.?.tree_context = saved.tree_context and supportsContext(pane); diff --git a/src/dump.zig b/src/dump.zig index 88a95994..54b77451 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -949,3 +949,37 @@ test "a restored pane keeps its dot, as acme's dump keeps a window's" { try std.testing.expectEqual(@as(u32, 4), dot.q0); try std.testing.expectEqual(@as(u32, 7), dot.q1); } + +test "a pane restored with unsaved text is asked about by Exit, Restore, Del and get" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("saved\n"); + _ = ctlfs.pane.spliceBody(p, pane, 0, 0, "unsaved ").?; + try std.testing.expect(pane.file.?.revision != pane.file.?.saved_revision); + try dumpState(p); + // Restore reads its dump before it warns: one it can read. + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "d.zon", .data = p.dump_out.? }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var restore_line: [4200]u8 = undefined; + for ([_][]const u8{ "Exit", "Restore", "Del", "get" }) |word| { + const restored = try initFromDump(gpa, .{ .tty_only = true }, p.dump_out.?); + defer restored.deinit(); + const id = for (restored.panes, 0..) |slot, i| { + if (slot) |candidate| if (candidate.file != null and candidate.file.?.output == null) break i; + } else return error.FileLost; + const th = @import("ninep/testing.zig"); + const node = if (std.mem.eql(u8, word, "Del") or std.mem.eql(u8, word, "get")) + ctlfs.Node.of(restored.panes[id].?.serial, .ctl) + else + @intFromEnum(ctlfs.TopFile.ctl); + const line = if (std.mem.eql(u8, word, "Restore")) try std.fmt.bufPrint(&restore_line, "Restore {s}/d.zon\n", .{dir}) else if (std.mem.eql(u8, word, "Exit")) "Exit\n" else if (std.mem.eql(u8, word, "Del")) "Del\n" else "get\n"; + const answer = th.wr(restored, node, line); + try std.testing.expectEqual(ctlfs.Status.err, answer.reply.status); + try std.testing.expect(std.mem.indexOf(u8, answer.reply.ename, "Modified") != null); + try std.testing.expect(!restored.quit and restored.panes[id] != null); + } +} -- cgit v1.3 From 35e72930c11af5563da9d62df2b74a7439f36653 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 04:18:04 -0300 Subject: A file changed on disk never reloads over unsaved edits A watched file rewritten on disk was loaded over a buffer's unsaved edits and its dirty flag cleared, so Exit and Del no longer asked about them. A clean buffer still reloads; one with edits keeps its text and stays dirty, says changed on disk (get reloads it, Save overwrites it), logs changed , and its Save warns once before overwriting the newer file, as acme's Put refuses a file modified since read (exec.c:577); get asks as ever (winclean, exec.c:513). The restored-watch test's dirty case now keeps the snapshot, and the filewatch snapshot script (re-recorded by name) checks both halves: the edited pane keeps its edit and says so, the clean one reloads. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 8 +++++++- src/File.zig | 28 ++++++++++++++++++++++++++-- src/exec.zig | 10 ++++++++++ src/file_watch.zig | 7 +++++++ src/ninep/ctl.zig | 27 +++++++++++++++++++++++++++ test/snapshots/filewatch.golden | 31 ++----------------------------- test/snapshots/filewatch.snap | 19 +++++++------------ 7 files changed, 86 insertions(+), 44 deletions(-) (limited to 'src/File.zig') diff --git a/docs/fs.md b/docs/fs.md index cf90aadc..3baac9c4 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -466,7 +466,13 @@ tab width — followed by rio's `current` or `notcurrent` (rio(4), `wctl`): whether the pane has the keyboard. It takes the pane's builtins (below), `get`, which reloads the buffer from the name it carries (unsaved edits are refused once, `: Modified (get again to -discard)`, as acme's get asks winclean, exec.c:513), `answer ` +discard)`, as acme's get asks winclean, exec.c:513). A file that changes on +disk reloads by itself only into a buffer with no unsaved edits; one with +them keeps its text and stays dirty, says ` changed on disk (get +reloads it, Save overwrites it)` and logs `changed `, and then its +`Save` warns once, ` modified on disk since read (Save again to +overwrite)`, as acme's Put does (exec.c:577) -- acme reloads nothing by +itself. `answer ` for the question the pane asks on its notice band, which the log names as `ask ` -- `ask 4 del k j` for Del's side from the keyboard (`k` the pane above takes the rows, `j` the one below), `ask 4 diff --git a/src/File.zig b/src/File.zig index 810bc766..4011301a 100644 --- a/src/File.zig +++ b/src/File.zig @@ -58,6 +58,12 @@ pub const State = struct { /// as an undo to the save point is in acme. saved_hash: ?u64 = null, watch_after_save: bool = false, + /// The file changed on disk under unsaved edits, which were kept (see + /// `changed`): its hash, so the same change is said once, until a Save + /// or get settles it. A Save warns once before overwriting it, as acme's + /// Put does (exec.c:577, "modified since last read"). + disk_newer: ?u64 = null, + disk_newer_warned: bool = false, /// Seconds of the last content change, for the filesystem's stat; zero until edited. mtime: u32 = 0, /// Non-null for a generated output buffer rather than an on-disk file. @@ -964,12 +970,30 @@ pub fn redo(p: *Pardes, pane: *Pane) void { restoreSnap(pane, f, next); } -/// Commit an externally rewritten file onto the same undo history as typed -/// edits. Unsaved work remains one `u` away; there is no third merge state. +/// A file rewritten on disk. A clean buffer takes the new text, committed +/// onto the same undo history as typed edits. A buffer with unsaved edits +/// is never reloaded under them: it keeps its text and stays dirty, and +/// says so once (` changed on disk (get reloads it, Save overwrites +/// it)`, logged `changed `); get then asks before throwing +/// the edits away and Save before overwriting the newer file. acme reloads +/// nothing by itself: its get asks (winclean) and its Put refuses a file +/// modified since it was read (exec.c:577). pub fn changed(p: *Pardes, id: u8, bytes: []const u8) void { const pane = p.panes[id] orelse return; const f = if (pane.file) |*file| file else return; if (std.mem.eql(u8, f.content, bytes)) return; + if (f.saved_hash) |saved| if (f.revision != f.saved_revision and std.hash.Wyhash.hash(0, f.content) != saved) { + const disk = std.hash.Wyhash.hash(0, bytes); + if (f.disk_newer == disk) return; + f.disk_newer = disk; + f.disk_newer_warned = false; + var said: [limits.host_path_cap + 64]u8 = undefined; + p.setMessage(id, std.fmt.bufPrint(&said, "{s} changed on disk (get reloads it, Save overwrites it)", .{f.path}) catch "changed on disk (get reloads it, Save overwrites it)"); + var rec: [16]u8 = undefined; + pardes.ctlfs.events.notePath(p, "changed", std.fmt.bufPrint(&rec, "{d}", .{pane.serial}) catch ""); + return; + }; + f.disk_newer = null; const new = p.gpa.dupe(u8, bytes) catch return; pushUndo(p, pane); setContent(p, f, new); diff --git a/src/exec.zig b/src/exec.zig index b8312a21..953ae0f3 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -249,6 +249,16 @@ pub fn saveFile(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; const f = if (pane.file) |*file| file else return; if (f.output != null) return; // nothing behind it yet: saveTo, with a path + // Its file changed on disk under these edits: once, as acme's Put says + // "modified since last read" (exec.c:577), and the next Save writes. + if (f.disk_newer != null) { + if (!f.disk_newer_warned) { + f.disk_newer_warned = true; + var said: [Pardes.SavePath.cap + 64]u8 = undefined; + return p.reportFailure(id, std.fmt.bufPrint(&said, "{s} modified on disk since read (Save again to overwrite)", .{f.path}) catch "modified on disk since read (Save again to overwrite)"); + } + f.disk_newer = null; + } p.emit(.{ .save_file = .{ .pane = @intCast(id) } }); } diff --git a/src/file_watch.zig b/src/file_watch.zig index 5d998470..b262e8ce 100644 --- a/src/file_watch.zig +++ b/src/file_watch.zig @@ -665,6 +665,13 @@ test "restored file watches preserve snapshots and accept later disk changes" { try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "later disk save\n" }); _ = reloadChanged(core, io, gpa, &watches); + // A snapshot restored with unsaved text keeps it: a later disk + // change is said, never loaded over it (File.changed). + if (case.dirty) { + try std.testing.expectEqualStrings("restored snapshot\n", pane.file.?.content); + try std.testing.expect(pane.file.?.disk_newer != null); + continue; + } try std.testing.expectEqualStrings("later disk save\n", pane.file.?.content); pardes.panes.File.undo(core, pane); try std.testing.expectEqualStrings("restored snapshot\n", pane.file.?.content); diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 19ca949e..1b1288a1 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -713,6 +713,7 @@ fn get(p: *Pardes, pane: *Pane) u16 { panes.File.setContent(p, f, bytes); f.saved_revision = f.revision; f.saved_hash = std.hash.Wyhash.hash(0, f.content); + f.disk_newer = null; return 0; } @@ -1558,3 +1559,29 @@ test "a 10k-line Edit text block is taken in linear time and memory" { try testing.expect(p.scratch.queryCapacity() < 50 * 1024 * 1024); try testing.expectEqual(@as(usize, 10_001), std.mem.count(u8, p.panes[0].?.file.?.content, "\n")); } + +test "a file changed on disk under unsaved edits is not reloaded: it says so, get asks, Save warns once" { + const p = try withFile(testing.allocator, "one\n"); + defer p.deinit(); + const serial = serialOf(p); + const f = &p.panes[0].?.file.?; + // Clean, it takes the new text. + pardes.panes.File.changed(p, 0, "two\n"); + try testing.expectEqualStrings("two\n", f.content); + // Edited, it keeps its text and stays dirty. + _ = wr(p, Node.of(serial, .body), "mine\n"); + pardes.panes.File.changed(p, 0, "three\n"); + try testing.expectEqualStrings("two\nmine\n", f.content); + try testing.expect(f.revision != f.saved_revision); + try testing.expect(th.logHas(p, "changed on disk (get reloads it, Save overwrites it)")); + var want: [32]u8 = undefined; + try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "changed {d}\n", .{serial}))); + // Exit and get still ask about the edits. + try testing.expectEqual(Status.err, wr(p, @intFromEnum(tree.TopFile.ctl), "Exit\n").reply.status); + try testing.expect(std.mem.indexOf(u8, wr(p, Node.of(serial, .ctl), "get\n").reply.ename, "Modified") != null); + // Save warns once before overwriting the newer file, then writes. + const first = wr(p, Node.of(serial, .ctl), "Save\n"); + try testing.expectEqual(Status.err, first.reply.status); + try testing.expect(std.mem.indexOf(u8, first.reply.ename, "modified on disk since read") != null); + try testing.expect(wr(p, Node.of(serial, .ctl), "Save\n").saved); +} diff --git a/test/snapshots/filewatch.golden b/test/snapshots/filewatch.golden index f19168b1..589cfc3a 100644 --- a/test/snapshots/filewatch.golden +++ b/test/snapshots/filewatch.golden @@ -28,20 +28,8 @@ | 7 line 7 | 8 line 8 | 9 -== snap reloaded grid=210x31 cursor=15,7 -|6: /tmp/pardes-snap/filewatch/cwd/w.txt Save Tty Collapse Del -|7: 1 EXTERNAL --:--:-- reloaded /tmp/pardes-snap/filewatch/cwd/w.txt -|8: 2 -|9: -|10: -|11: -|12: -|13: -|14: -|15: -|16: -|17: -|18: +== snap kept grid=210x31 cursor=15,7 +|7: 1 liMYEDITne 1 /tmp/pardes-snap/filewatch/cwd/w.txt changed on disk (get reloads it, Save overwrites it) == snap reloaded_sub grid=210x31 cursor=15,7 |20: 1 RENAMED --:--:-- reloaded /tmp/pardes-snap/filewatch/cwd/sub/s.txt |21: 2 @@ -52,18 +40,3 @@ |26: |27: |28: -== snap undone grid=210x31 cursor=15,7 -|6: * /tmp/pardes-snap/filewatch/cwd/w.txt Save Tty Collapse Del -|7: 1 liMYEDITne 1 -|8: 2 line 2 -|9: 3 /tmp/pardes-snap/filewatch/cwd/sub/s.txt -|10: 4 line 4 -|11: 5 line 5 -|12: 6 line 6 -|13: 7 line 7 -|14: 8 line 8 -|15: 9 line 9 -|16: 10 line 10 -|17: 11 line 11 -|18: 12 line 12 -|20: 1 RENAMED diff --git a/test/snapshots/filewatch.snap b/test/snapshots/filewatch.snap index 9e6e6a13..6664519f 100644 --- a/test/snapshots/filewatch.snap +++ b/test/snapshots/filewatch.snap @@ -1,6 +1,6 @@ -# external file updates: a write from outside pardes lands in the open pane, -# and Undo brings the unsaved edit back. That is the whole contract — the -# update is committed like any other edit, so nothing has to be merged. +# external file updates: a write from outside pardes lands in an open pane +# that has no unsaved edits, committed like any other edit; a pane WITH +# unsaved edits keeps them and says the file changed on disk (File.changed). # # The writer must be a STRANGER to the editor. This script used to have a # pardes PANE run the write, which proved much less than it looked: that @@ -54,18 +54,13 @@ settle 100 stable 400 5000 snap edited # ---- from here to `snap reloaded_sub`, pardes is sent NOTHING ---- +# w.txt has the unsaved edit: it is kept, and the change is said run printf 'EXTERNAL\n' > w.txt -wait 10000 EXTERNAL +wait 10000 changed on disk stable 700 10000 -snap reloaded +snap kept +# sub/s.txt has none: it takes the new text run printf 'RENAMED\n' > sub/t && mv sub/t sub/s.txt wait 10000 RENAMED stable 700 10000 snap reloaded_sub -# back in the file pane: one undo and the unsaved edit is there again -press left 10 8 -release left 10 8 -stable 400 5000 -key u -stable 400 5000 -snap undone -- cgit v1.3 From 430d482c16101ce85b5c0f80f6bdd882c09a3272 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 04:52:38 -0300 Subject: Refusals and records say more: get quotes its line, a bare answer lists the choices, a clean reload is logged get's refusal now quotes the line as a builtin's (Save's) does; a bare answer while a question stands says what it takes (answer takes k j or -); and a clean buffer reloaded from disk logs changed reloaded, as the kept dirty case logs changed . (A failed Save already says why: Save : .) Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 3 +++ src/ninep/ctl.zig | 20 ++++++++++++++++++-- src/pardes.zig | 2 ++ 3 files changed, 23 insertions(+), 2 deletions(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index 4011301a..17399d8b 100644 --- a/src/File.zig +++ b/src/File.zig @@ -994,6 +994,9 @@ pub fn changed(p: *Pardes, id: u8, bytes: []const u8) void { return; }; f.disk_newer = null; + // Logged as the dirty case is, with what became of it. + var rec: [32]u8 = undefined; + pardes.ctlfs.events.notePath(p, "changed", std.fmt.bufPrint(&rec, "{d} reloaded", .{pane.serial}) catch ""); const new = p.gpa.dupe(u8, bytes) catch return; pushUndo(p, pane); setContent(p, f, new); diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index f40825e3..eb8ed292 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -648,7 +648,15 @@ pub fn writePane(p: *Pardes, req: Req, pane: *Pane) Reply { if (apply and p.paneBySerial(serial) == null) return Reply.fail(req.tag, E.NOENT); if (std.mem.eql(u8, line, "get")) { if (!apply) continue; - if (getRefused(p, pane)) |said| return tree.failText(req.tag, E.IO, said); + // Quoting the line, as a builtin's refusal (Save's) does. + if (getRefused(p, pane)) |said_in_ename| { + // refuse writes ename, where the words are: copy them out. + var said_buf: [320]u8 = undefined; + const said = said_buf[0..said_in_ename.len]; + @memcpy(said, said_in_ename); + const r = refuse(p, req, said, line); + return .{ .tag = req.tag, .status = .err, .errno = E.IO, .ename = r.ename }; + } const errno = get(p, pane); if (errno != 0) return Reply.fail(req.tag, errno); } else if (std.mem.eql(u8, line, "lock")) { @@ -661,6 +669,12 @@ pub fn writePane(p: *Pardes, req: Req, pane: *Pane) Reply { held = false; if (apply) pane.fs.lock = null; } else if (std.mem.eql(u8, line, "answer")) { + // With a question up, what it offers. + var offered: [64]u8 = undefined; + if (p.questionChoices(p.paneBySerial(serial).?, &offered)) |choices| { + var why: [96]u8 = undefined; + return tree.failText(req.tag, E.INVAL, std.fmt.bufPrint(&p.fs.ename, "answer takes {s} or -", .{choices}) catch std.fmt.bufPrint(&why, "answer takes a choice or -", .{}) catch "answer takes a choice or -"); + } return tree.failText(req.tag, E.INVAL, "answer takes a choice or -"); } else if (std.mem.startsWith(u8, line, "answer ")) { // The pane's question (its `ask` in the log), answered. @@ -1280,7 +1294,7 @@ test "get reloads the pane from disk and reports a missing file without losing d // Unsaved text is asked about once, as acme's get asks winclean. const asked = wr(p, ctl_node, "get\n"); try testing.expectEqual(E.IO, asked.errno()); - try testing.expect(std.mem.endsWith(u8, asked.reply.ename, ": Modified (get again to discard)")); + try testing.expect(std.mem.endsWith(u8, asked.reply.ename, ": Modified (get again to discard) \"get\"")); try testing.expectEqual(E.NOENT, wr(p, ctl_node, "get\n").errno()); try testing.expect(p.paneBySerial(serial) != null); try testing.expectEqualStrings("from disk\nunsaved\n", pane.file.?.content); @@ -1571,6 +1585,8 @@ test "a file changed on disk under unsaved edits is not reloaded: it says so, ge // Clean, it takes the new text. pardes.panes.File.changed(p, 0, "two\n"); try testing.expectEqualStrings("two\n", f.content); + var reloaded: [32]u8 = undefined; + try testing.expect(th.logHas(p, try std.fmt.bufPrint(&reloaded, "changed {d} reloaded\n", .{serial}))); // Edited, it keeps its text and stays dirty. _ = wr(p, Node.of(serial, .body), "mine\n"); pardes.panes.File.changed(p, 0, "three\n"); diff --git a/src/pardes.zig b/src/pardes.zig index 289dcee0..5d709679 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -7977,6 +7977,8 @@ test "a pane closed while its question stands ends the question in the log" { p.update(.{ .key = .{ .cp = ' ' } }); p.update(.{ .key = .{ .cp = 'd' } }); try std.testing.expectEqual(Pane.Prompt.del_side, p.panes[closing].?.prompt); + // A bare answer says what this question takes. + try std.testing.expectEqualStrings("answer takes k j or -", th.wr(p, ctlfs.Node.of(serial, .ctl), "answer\n").reply.ename); try p.removePane(closing, null); var want: [64]u8 = undefined; try std.testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "answer {d} -\ndel {d}", .{ serial, serial }))); -- cgit v1.3 From 24729dbbf8b32966a3f33c9bc20599b185856dd3 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 05:29:45 -0300 Subject: get and a deleted file say what happened: the path, changed deleted, reloaded get on a file gone from disk failed with a bare ENOENT; it now says get: : no such file. A watched file deleted on disk was silent; the pane keeps its text and says deleted on disk (Save writes it again) once, logged changed deleted (only a path the watch has read: a pane renamed to a name never on disk is not deleted). A get that throws a dirty buffer's state away logs changed reloaded, as the watch's reload does. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 18 ++++++++++++++++++ src/file_watch.zig | 12 +++++++++++- src/ninep/ctl.zig | 38 +++++++++++++++++++++++++++++++++++++- src/pardes.zig | 1 + 4 files changed, 67 insertions(+), 2 deletions(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index 17399d8b..5f6d7097 100644 --- a/src/File.zig +++ b/src/File.zig @@ -64,6 +64,9 @@ pub const State = struct { /// Put does (exec.c:577, "modified since last read"). disk_newer: ?u64 = null, disk_newer_warned: bool = false, + /// Its file was deleted on disk: said once (`deleted`) until it is + /// written or found again. + disk_gone: bool = false, /// Seconds of the last content change, for the filesystem's stat; zero until edited. mtime: u32 = 0, /// Non-null for a generated output buffer rather than an on-disk file. @@ -970,6 +973,20 @@ pub fn redo(p: *Pardes, pane: *Pane) void { restoreSnap(pane, f, next); } +/// A pane's file deleted on disk: the text stays, and it says so once, +/// ` deleted on disk (Save writes it again)`, logged `changed +/// deleted`. +pub fn deleted(p: *Pardes, id: u8) void { + const pane = p.panes[id] orelse return; + const f = if (pane.file) |*file| file else return; + if (f.disk_gone) return; + f.disk_gone = true; + var said: [limits.host_path_cap + 64]u8 = undefined; + p.setMessage(id, std.fmt.bufPrint(&said, "{s} deleted on disk (Save writes it again)", .{f.path}) catch "deleted on disk (Save writes it again)"); + var rec: [32]u8 = undefined; + pardes.ctlfs.events.notePath(p, "changed", std.fmt.bufPrint(&rec, "{d} deleted", .{pane.serial}) catch ""); +} + /// A file rewritten on disk. A clean buffer takes the new text, committed /// onto the same undo history as typed edits. A buffer with unsaved edits /// is never reloaded under them: it keeps its text and stays dirty, and @@ -981,6 +998,7 @@ pub fn redo(p: *Pardes, pane: *Pane) void { pub fn changed(p: *Pardes, id: u8, bytes: []const u8) void { const pane = p.panes[id] orelse return; const f = if (pane.file) |*file| file else return; + f.disk_gone = false; if (std.mem.eql(u8, f.content, bytes)) return; if (f.saved_hash) |saved| if (f.revision != f.saved_revision and std.hash.Wyhash.hash(0, f.content) != saved) { const disk = std.hash.Wyhash.hash(0, bytes); diff --git a/src/file_watch.zig b/src/file_watch.zig index b262e8ce..71a4680d 100644 --- a/src/file_watch.zig +++ b/src/file_watch.zig @@ -60,6 +60,10 @@ pub const Watch = struct { kq: c_int = -1, serial: u32, generation: Generation, + /// The path last read while watched (its hash): its going away later is + /// a deletion to say, where a path never there (a pane renamed to a new + /// name) is not. + existed: ?u64 = null, }; /// The final slot is the one non-pane watched payload: the active ThemeFile. @@ -440,7 +444,12 @@ pub fn reloadPane( } if (pane.file) |file| { - const bytes = filesystem.read(core, file.path) catch return false; + const bytes = filesystem.read(core, file.path) catch |err| { + // Gone from under the pane: said once, the text kept. + if (err == error.FileNotFound and watched.existed == std.hash.Wyhash.hash(0, file.path)) pardes.panes.File.deleted(core, @intCast(id)); + return false; + }; + if (watches[id]) |*live| live.existed = std.hash.Wyhash.hash(0, file.path); defer core.gpa.free(bytes); const hash = std.hash.Wyhash.hash(0, bytes); switch (watched.generation) { @@ -517,6 +526,7 @@ pub fn applyEffect( const bytes = filesystem.read(core, file.path) catch return false; defer core.gpa.free(bytes); watched.generation = .{ .text = std.hash.Wyhash.hash(0, bytes) }; + watched.existed = std.hash.Wyhash.hash(0, file.path); return false; }; return on and watches[id] != null and reloadPane(core, io, watches, id, false); diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 7d5f0ca0..112df099 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -722,7 +722,11 @@ pub fn writePane(p: *Pardes, req: Req, pane: *Pane) Reply { return .{ .tag = req.tag, .status = .err, .errno = E.IO, .ename = r.ename }; } const errno = get(p, pane); - if (errno != 0) return Reply.fail(req.tag, errno); + // Naming the path, in words 9ns reads as the errno. + if (errno != 0) { + const path = if (pane_files.fileOf(pane)) |f| f.path else ""; + return tree.failText(req.tag, errno, std.fmt.bufPrint(&p.fs.ename, "get: {s}: {s}", .{ path[0..@min(path.len, 256)], if (errno == E.NOENT) "no such file" else "cannot be read" }) catch "get: no such file"); + } } else if (std.mem.eql(u8, line, "lock")) { if (mine == null) return tree.failText(req.tag, E.INVAL, tree.e_bad_ctl); if (other) return tree.failText(req.tag, E.BUSY, e_locked); @@ -799,11 +803,19 @@ fn get(p: *Pardes, pane: *Pane) u16 { error.FileNotFound => E.NOENT, else => E.IO, }; + // Throwing unsaved edits away for it is a reload the log hears of, as a + // clean one from the watch is. + const discarded = f.revision != f.saved_revision; panes.File.pushUndo(p, pane); panes.File.setContent(p, f, bytes); f.saved_revision = f.revision; f.saved_hash = std.hash.Wyhash.hash(0, f.content); f.disk_newer = null; + f.disk_gone = false; + if (discarded) { + var rec: [32]u8 = undefined; + pardes.ctlfs.events.notePath(p, "changed", std.fmt.bufPrint(&rec, "{d} reloaded", .{pane.serial}) catch ""); + } return 0; } @@ -1363,6 +1375,9 @@ test "get reloads the pane from disk and reports a missing file without losing d try testing.expectEqualStrings("from disk\n", pane.file.?.content); try testing.expect(!pane_files.dirtyOf(pane)); try testing.expect(pane.file.?.history.undo_len > 0); + // What it had (renamed, so dirty) was thrown away for it: logged. + var reloaded: [32]u8 = undefined; + try testing.expect(th.logHas(p, try std.fmt.bufPrint(&reloaded, "changed {d} reloaded\n", .{serial}))); _ = wr(p, Node.of(serial, .name), try std.fmt.bufPrint(&name, "{s}/missing.txt\n", .{directory})); _ = wr(p, Node.of(serial, .body), "unsaved\n"); @@ -1784,3 +1799,24 @@ test "Save on a terminal asked over 9P is an ask in the log, answered with a pat try testing.expect(p.panes[id].?.prompt == .none); try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "answer {d} /tmp/pardes-ask-save.txt\n", .{serial}))); } + +test "get names the path it could not read, logs the edits it threw away, and a deleted file is said once" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + const serial = serialOf(p); + const f = &p.panes[0].?.file.?; + const path = f.path; + // Its file is not on disk: get names it. + const missing = wr(p, Node.of(serial, .ctl), "get\n"); + try testing.expectEqual(E.NOENT, missing.errno()); + var want: [512]u8 = undefined; + try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "get: {s}: no such file", .{path}), missing.reply.ename); + // Deleted on disk: said once. + pardes.panes.File.deleted(p, 0); + pardes.panes.File.deleted(p, 0); + var rec: [32]u8 = undefined; + const log = @intFromEnum(tree.TopFile.log); + const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; + try testing.expectEqual(@as(usize, 1), std.mem.count(u8, call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes, try std.fmt.bufPrint(&rec, "changed {d} deleted\n", .{serial}))); + _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h }); +} diff --git a/src/pardes.zig b/src/pardes.zig index 59e8670f..dd9d91c8 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -5277,6 +5277,7 @@ pub const Pardes = struct { // A save the host could not do (saveFailed) is its err // record alone, not a `save`. if (saved.saved_revision != saved.revision) return; + saved.disk_gone = false; ctlfs.events.noteLog(p, .save, saved_pane); if (!saved.watch_after_save) return; saved.watch_after_save = false; -- cgit v1.3 From 4e224b7c7e67fafcbe7359fcf534048e254b701d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 13:19:08 -0300 Subject: The theme's chrome is worked out once, not per grapheme; still post passes let the GUI rest; a perf gate somtrmsz's contrast floors made ChromeTheme.fromTheme run its focus-tint and separator searches (pow calls each), and Output's RowDecoration.styleAt called it for every grapheme of every highlighted row: the 50k-line file's render went from 0.11 ms to 13 ms. Pardes.bodyChrome now keeps the theme's chrome, worked out again only when the theme differs; recolorSyntax asks for it once a decorated row, and a plain row (nearly every row of a file) never asks. ReleaseFast, medium fixture, median us, before -> after (main): render 13150 -> 76 (111), key-down 14658 -> 79 (110), wheel 13589 -> 76 (109), open 14891 -> 2095 (2055), edit-char 16703 -> 3006 (1251; the rest of that gap is editing and tree-sitter, not this). Post.animating asked for frames whenever the window had focus and any pass was ready, so a still pass kept the GUI drawing at the display's rate (Bloom: 49% of a core idle, in a hidden test window). A pass now says whether it moves on its own: the CRT (its hum and dither) and a Shadertoy file whose source reads iTime, iFrame or iDate (shader_build.readsTime; the flag rides the wire's post message); Bloom, Vignette and Grain are still. Bloom idle: 49% -> 1.2%, as with no pass. zig build perf-gate: the 50k-line file's gestures, each's fastest sample within 3x of the recorded baseline's (test/perf-baseline-- .json, recorded from this build), run with every unit-test. On the regressed code it fails at 180x for render. --- build.zig | 15 ++++++++++ src/File.zig | 3 +- src/Output.zig | 15 +++++++--- src/detached/wire.zig | 11 +++++-- src/gui/Post.zig | 27 +++++++++++++++-- src/pardes.zig | 12 ++++++++ src/shader_build.zig | 34 ++++++++++++++++++--- test/perf-baseline-gui-Debug.json | 1 + test/perf-baseline-tty-Debug.json | 1 + test/perf-baseline-tty-ReleaseFast.json | 1 + test/perf.zig | 52 ++++++++++++++++++++++++++++++--- 11 files changed, 155 insertions(+), 17 deletions(-) create mode 100644 test/perf-baseline-gui-Debug.json create mode 100644 test/perf-baseline-tty-Debug.json create mode 100644 test/perf-baseline-tty-ReleaseFast.json (limited to 'src/File.zig') diff --git a/build.zig b/build.zig index 48987edf..79de8a81 100644 --- a/build.zig +++ b/build.zig @@ -1282,6 +1282,18 @@ pub fn build(b: *std.Build) void { run_perf.setCwd(b.path(".")); const perf_step = b.step("perf", "gesture latency or bounded terminal stress (-- [--json] [--reps N] [--base old.json] [--terminal-mib N])"); perf_step.dependOn(&run_perf.step); + // The gate: the 50k-line file's gestures against the baseline this + // build shape recorded, each within 3x of its best. Record one with + // `zig build perf -Dplatform=P [-Doptimize=O] -- --only medium + // --reps 10 --json > test/perf-baseline-P-O.json` (a build that is + // known good). ponytail: the numbers are this machine's; another + // machine records its own. + const perf_gate = b.addRunArtifact(perf); + perf_gate.has_side_effects = true; + perf_gate.setCwd(b.path(".")); + perf_gate.addArgs(&.{ "--only", "medium", "--reps", "10", "--base", b.fmt("test/perf-baseline-{t}-{t}.json", .{ platform, optimize }), "--max-ratio", "3" }); + const perf_gate_step = b.step("perf-gate", "fail when a gesture on the 50k-line file takes over 3x its recorded baseline (test/perf-baseline--.json)"); + perf_gate_step.dependOn(&perf_gate.step); const perf_tests = b.addTest(.{ .root_module = b.createModule(.{ .target = target, @@ -1430,6 +1442,9 @@ pub fn build(b: *std.Build) void { b.step("history", "compare command output and test/build runtime across jj revisions").dependOn(&run_history.step); const unit_step = b.step("unit-test", "run native shell and module unit tests"); + // The perf gate runs with every unit-test (a regression like a + // contrast search per grapheme costs 100x, far past the gate). + unit_step.dependOn(perf_gate_step); const unit_match = testMatch(b, unit_profile, test_filters, unit_step); const lspbench_tests = b.addTest(.{ .root_module = lspbench.root_module, .filters = test_filters }); const run_lspbench_tests = b.addRunArtifact(lspbench_tests); diff --git a/src/File.zig b/src/File.zig index 5f6d7097..1d838c4f 100644 --- a/src/File.zig +++ b/src/File.zig @@ -1293,6 +1293,7 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. const row_index: usize = @intCast(@max(0, pane.wrapAt(vr).line)); const metadata: ?locations.Row = if (row_index < f.location_rows.len) f.location_rows[row_index] else null; const decoration = Output.decorateRow(f.output, line, metadata); + const chrome: ?*const pardes.ChromeTheme = if (decoration.plain()) null else p.bodyChrome(); var c: usize = 0; var screen_c: usize = 0; while (hs + c < limit and prefix_width + screen_c < tw) { @@ -1315,7 +1316,7 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. } // Results keep their exact live text. Only the location, // matched source range and diagnostic label gain emphasis. - if (decoration.styleAt(p, hs + c)) |style| { + if (if (chrome) |ch| decoration.styleAt(ch, hs + c) else null) |style| { var fill: usize = 0; while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) { const cell = s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr); diff --git a/src/Output.zig b/src/Output.zig index b8dd5e34..6ea81924 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -54,10 +54,17 @@ const RowDecoration = struct { mark_end: usize = 0, severity: enum { none, err, warning, info, hint } = .none, - pub fn styleAt(row: RowDecoration, p: *const Pardes, byte: usize) ?pardes.CellStyle { - // Body paper changes immediately, so its ink must change with it - // even while the surrounding tags are still fading. - const chrome = pardes.ChromeTheme.fromTheme(p.theme()); + /// Nothing in the row is decorated: most rows of most files. + pub fn plain(row: RowDecoration) bool { + return !row.declaration and row.location_end == 0 and row.prefix_end == 0 and row.mark_end <= row.mark_start; + } + + /// `chrome` is the theme's own (Pardes.bodyChrome): body paper changes + /// immediately, so its ink must change with it even while the + /// surrounding tags are still fading. Once a frame, never a grapheme: + /// working it out takes the contrast searches' pow calls. + pub fn styleAt(row: RowDecoration, chrome: *const pardes.ChromeTheme, byte: usize) ?pardes.CellStyle { + if (row.plain()) return null; if (row.declaration or byte < @max(row.location_end, row.prefix_end)) return .{ .fg = .{ .rgb = chrome.lineno } }; if (byte < row.mark_start or byte >= row.mark_end) return null; diff --git a/src/detached/wire.zig b/src/detached/wire.zig index ee8c72fb..15d3641c 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -1178,6 +1178,7 @@ pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { // 0 a file, else a bundled scene and one. try w.putByte(if (pass.scene) |scene| @as(u8, @intFromEnum(scene)) + 1 else 0); try w.putByte(pass.level); + try w.putByte(@intFromBool(pass.animated)); try w.putU32(pass.revision); try w.putSlice16(pass.path); try w.putSlice32(pass.spirv); @@ -1206,7 +1207,7 @@ pub fn serverBound(msg: ServerMsg) usize { .open_link => |u| u.len, .post => |p| blk: { var n: usize = 0; - for (p.list()) |pass| n += 12 + pass.path.len + pass.spirv.len; + for (p.list()) |pass| n += 13 + pass.path.len + pass.spirv.len; break :blk n; }, }; @@ -1280,6 +1281,11 @@ pub fn decodeServer(tag: u8, payload: []const u8) Error!ServerMsg { pass.* = .{ .scene = if (kind == 0) null else std.enums.fromInt(Scene, kind - 1) orelse return error.BadValue, .level = try r.getByte(), + .animated = switch (try r.getByte()) { + 0 => false, + 1 => true, + else => return error.BadValue, + }, .revision = try r.getU32(), .path = try r.getSlice16(), .spirv = try r.getSlice32(), @@ -1406,7 +1412,7 @@ test "detached wire: every server message round-trips" { try testing.expectEqualStrings("https://x", (try roundServer(&buf, .{ .open_link = "https://x" })).open_link); var chain: Post = .{ .animation = .always, .len = 2 }; chain.passes[0] = .{ .scene = .bloom, .level = 3 }; - chain.passes[1] = .{ .path = "~/wave.glsl", .spirv = "\x03\x02\x23\x07spirv", .revision = 7 }; + chain.passes[1] = .{ .path = "~/wave.glsl", .spirv = "\x03\x02\x23\x07spirv", .revision = 7, .animated = true }; const back = (try roundServer(&buf, .{ .post = chain })).post; try testing.expectEqual(ShaderAnimation.always, back.animation); try testing.expectEqual(@as(u8, 2), back.len); @@ -1416,6 +1422,7 @@ test "detached wire: every server message round-trips" { try testing.expectEqualStrings("~/wave.glsl", back.passes[1].path); try testing.expectEqualStrings("\x03\x02\x23\x07spirv", back.passes[1].spirv); try testing.expectEqual(@as(u32, 7), back.passes[1].revision); + try testing.expect(back.passes[1].animated and !back.passes[0].animated); } test "detached wire: only the display's own effects are on the wire" { diff --git a/src/gui/Post.zig b/src/gui/Post.zig index 06310b7f..602b2790 100644 --- a/src/gui/Post.zig +++ b/src/gui/Post.zig @@ -94,6 +94,8 @@ pub const Pass = struct { pipeline: ?*Pipeline = null, /// The SPIR-V revision `pipeline` was made from (shader_build.Pass). revision: u32 = 0, + /// It moves on its own (shader_build.Pass). + animated: bool = false, }; passes: [max]Pass = @splat(.{}), @@ -140,7 +142,7 @@ pub fn sync(post: *Post, gpa: std.mem.Allocator, device: *c.SDL_GPUDevice, forma post.bloom_down = makePipeline(device, bloom_format, bloom_down_spv, 1, 1) catch null; post.bloom_up = makePipeline(device, bloom_format, bloom_up_spv, 1, 1) catch null; } - next[i] = .{ .scene = scene, .level = entry.level, .pipeline = post.bundled.get(scene) }; + next[i] = .{ .scene = scene, .level = entry.level, .pipeline = post.bundled.get(scene), .animated = entry.animated }; continue; } // A file already in the chain keeps its pipeline and its path. @@ -151,6 +153,7 @@ pub fn sync(post: *Post, gpa: std.mem.Allocator, device: *c.SDL_GPUDevice, forma break; } else next[i] = .{ .path = gpa.dupe(u8, entry.path) catch &.{} }; const pass = &next[i]; + pass.animated = entry.animated; if (pass.revision == entry.revision or entry.spirv.len == 0) continue; pass.revision = entry.revision; const made = makePipeline(device, format, entry.spirv, 1, 4) catch { @@ -200,8 +203,14 @@ pub fn ready(post: *const Post) bool { } /// The chain redraws on its own (level A) as ShaderAnimation says. +/// Only a pass that moves on its own (shader_build.Pass.animated) asks for +/// frames while idle: a still one (Bloom, Vignette, Grain, a file that reads +/// no clock) is drawn again only with a frame of the core's. pub fn animating(post: *const Post, mode: pardes.config.Runtime.ShaderAnimation) bool { - return post.ready() and switch (mode) { + const moving = for (post.passes[0..post.len]) |pass| { + if (pass.pipeline != null and pass.animated) break true; + } else false; + return moving and switch (mode) { .off => false, .on => post.uniforms.focus != 0, .always => true, @@ -664,3 +673,17 @@ test "a moved cursor becomes the previous one, stamped with the time of the move try std.testing.expectEqual([4]f32{ 1.0 / 255.0, 2.0 / 255.0, 3.0 / 255.0, 1 }, post.uniforms.selection_foreground_color); } + +test "a still pass asks for no idle frames; one that reads the clock does" { + var post: Post = .{}; + const fake: *Pipeline = @ptrFromInt(0x1000); + post.passes[0] = .{ .scene = .bloom, .level = 2, .pipeline = fake }; + post.len = 1; + try std.testing.expect(!post.animating(.on) and !post.animating(.always)); + post.passes[1] = .{ .scene = .crt, .level = 2, .pipeline = fake, .animated = true }; + post.len = 2; + try std.testing.expect(post.animating(.on) and post.animating(.always) and !post.animating(.off)); + // Unfocused, `on` rests. + post.uniforms.focus = 0; + try std.testing.expect(!post.animating(.on) and post.animating(.always)); +} diff --git a/src/pardes.zig b/src/pardes.zig index 1f136f2b..ae04b4e7 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -4380,6 +4380,8 @@ pub const Pardes = struct { tty_filter_palette: panes.Terminal.FilterPalette = .{}, font_request_taken: bool = false, custom_theme: ?Theme = null, + /// bodyChrome's: the theme it was worked out for, and it. + body_chrome: ?struct { theme: Theme, chrome: ChromeTheme } = null, theme_file_path: config.Runtime.Text(limits.host_path_cap) = .{}, theme_file_generation: u32 = 0, theme_file_pane: u8 = 0, @@ -7063,6 +7065,16 @@ pub const Pardes = struct { return &p.chrome_animation.displayed; } + /// The theme's own chrome, not a fade's (`theme()`'s, worked out once + /// per theme: its contrast searches take pow calls, too many for a + /// grapheme or a row). + pub fn bodyChrome(p: *Pardes) *const ChromeTheme { + const th = p.theme(); + if (p.body_chrome) |*cached| if (std.meta.eql(cached.theme, th.*)) return &cached.chrome; + p.body_chrome = .{ .theme = th.*, .chrome = ChromeTheme.fromTheme(th) }; + return &p.body_chrome.?.chrome; + } + /// When core animation next needs a frame, on the `stepped_ns` /// timeline: a frame from now while anything moves, the end of the /// wait while something only waits (a message lingering, a look-hover diff --git a/src/shader_build.zig b/src/shader_build.zig index 8aa7eb5e..c2610fd7 100644 --- a/src/shader_build.zig +++ b/src/shader_build.zig @@ -32,8 +32,24 @@ pub const Pass = struct { path: []const u8 = &.{}, spirv: []const u8 = &.{}, revision: u32 = 0, + /// It moves on its own (reads the clock or the frame count), so the + /// chain redraws while idle; a still pass draws only with a new frame. + animated: bool = false, }; +/// The bundled passes that move on their own: the CRT's hum and dither. +pub fn sceneAnimated(scene: Scene) bool { + return scene == .crt; +} + +/// Whether a Shadertoy source moves on its own: it reads the time +/// (iTime, iTimeDelta and the times of a cursor move or a focus change), +/// the frame count or the date. A mention in a comment counts too. +pub fn readsTime(source: []const u8) bool { + for ([_][]const u8{ "iTime", "iFrame", "iDate" }) |name| if (std.mem.indexOf(u8, source, name) != null) return true; + return false; +} + /// Who to wake when a compile is done: the host's loop. pub const Wake = struct { ctx: ?*anyopaque = null, @@ -47,6 +63,7 @@ const File = struct { source: ?u64 = null, spirv: []u8 = &.{}, revision: u32 = 0, + animated: bool = false, /// Wants a compile: new to the chain, or its directory changed. stale: bool = true, }; @@ -56,7 +73,7 @@ const Result = union(enum) { unchanged, missing, failed: struct { text: []u8, source: u64 }, - spirv: struct { bytes: []u8, source: u64 }, + spirv: struct { bytes: []u8, source: u64, animated: bool }, }; /// One compile of the stale files, on its own thread. @@ -148,8 +165,8 @@ pub fn recheck(b: *Build) void { /// The chain as passes, in its order. pub fn view(b: *const Build, chain: *const Chain, out: *[max]Pass) []const Pass { for (chain.list(), 0..) |entry, i| { - out[i] = if (entry.scene) |scene| .{ .scene = scene, .level = entry.level } else for (b.files[0..b.len]) |file| { - if (std.mem.eql(u8, file.path, entry.path.get())) break .{ .path = file.path, .spirv = file.spirv, .revision = file.revision }; + out[i] = if (entry.scene) |scene| .{ .scene = scene, .level = entry.level, .animated = sceneAnimated(scene) } else for (b.files[0..b.len]) |file| { + if (std.mem.eql(u8, file.path, entry.path.get())) break .{ .path = file.path, .spirv = file.spirv, .revision = file.revision, .animated = file.animated }; } else .{ .path = entry.path.get() }; } return out[0..chain.len]; @@ -211,6 +228,7 @@ fn collect(b: *Build, gpa: std.mem.Allocator, core: *pardes.Pardes, job: *Job) v gpa.free(f.spirv); f.spirv = r.bytes; f.source = r.source; + f.animated = r.animated; f.revision +%= 1; b.revision +%= 1; }, @@ -291,7 +309,7 @@ fn compileOne(gpa: std.mem.Allocator, io: std.Io, path: []const u8, known: ?u64) .exited => |code| code == 0, else => false, }; - if (clean) return .{ .spirv = .{ .bytes = reader.toOwnedSlice(0) catch return .none, .source = source } }; + if (clean) return .{ .spirv = .{ .bytes = reader.toOwnedSlice(0) catch return .none, .source = source, .animated = readsTime(body) } }; const said = reader.toOwnedSlice(1) catch return .none; // glslc calls its input ; the file is what a person knows. defer gpa.free(said); @@ -400,3 +418,11 @@ test "a save that changes a file compiles it again, a failed one keeps the last const second = b.view(&core.settings.post, &out)[0]; try std.testing.expect(second.revision != first.revision and b.revision != at); } + +test "a pass animates when it reads the clock or the frame count, and only the CRT of the bundled ones" { + try std.testing.expect(readsTime("o = vec4(sin(iTime));")); + try std.testing.expect(readsTime("float f = float(iFrame % 64);")); + try std.testing.expect(readsTime("x = iTimeCursorChange;")); + try std.testing.expect(!readsTime("o = texture(iChannel0, p / iResolution.xy);")); + for (std.enums.values(Scene)) |scene| try std.testing.expectEqual(scene == .crt, sceneAnimated(scene)); +} diff --git a/test/perf-baseline-gui-Debug.json b/test/perf-baseline-gui-Debug.json new file mode 100644 index 00000000..fd64ebf9 --- /dev/null +++ b/test/perf-baseline-gui-Debug.json @@ -0,0 +1 @@ +{"harness":"67f85bf9692f1778","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1768,"med_us":2025,"p90_us":2122,"max_us":2125},{"op":"render","fixture":"medium","min_us":72,"med_us":75,"p90_us":76,"max_us":83},{"op":"key-down","fixture":"medium","min_us":73,"med_us":76,"p90_us":80,"max_us":84},{"op":"key-right","fixture":"medium","min_us":74,"med_us":77,"p90_us":81,"max_us":84},{"op":"page-down","fixture":"medium","min_us":73,"med_us":74,"p90_us":77,"max_us":79},{"op":"wheel","fixture":"medium","min_us":71,"med_us":75,"p90_us":81,"max_us":81},{"op":"edit-char","fixture":"medium","min_us":2413,"med_us":2674,"p90_us":2943,"max_us":3111}]} diff --git a/test/perf-baseline-tty-Debug.json b/test/perf-baseline-tty-Debug.json new file mode 100644 index 00000000..682ea028 --- /dev/null +++ b/test/perf-baseline-tty-Debug.json @@ -0,0 +1 @@ +{"harness":"67f85bf9692f1778","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1944,"med_us":2130,"p90_us":2232,"max_us":2394},{"op":"render","fixture":"medium","min_us":71,"med_us":75,"p90_us":76,"max_us":91},{"op":"key-down","fixture":"medium","min_us":72,"med_us":79,"p90_us":93,"max_us":102},{"op":"key-right","fixture":"medium","min_us":73,"med_us":76,"p90_us":78,"max_us":81},{"op":"page-down","fixture":"medium","min_us":72,"med_us":73,"p90_us":76,"max_us":76},{"op":"wheel","fixture":"medium","min_us":71,"med_us":85,"p90_us":96,"max_us":102},{"op":"edit-char","fixture":"medium","min_us":2612,"med_us":3112,"p90_us":3238,"max_us":3618}]} diff --git a/test/perf-baseline-tty-ReleaseFast.json b/test/perf-baseline-tty-ReleaseFast.json new file mode 100644 index 00000000..4fd96d92 --- /dev/null +++ b/test/perf-baseline-tty-ReleaseFast.json @@ -0,0 +1 @@ +{"harness":"67f85bf9692f1778","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1971,"med_us":2259,"p90_us":2308,"max_us":2339},{"op":"render","fixture":"medium","min_us":71,"med_us":75,"p90_us":78,"max_us":79},{"op":"key-down","fixture":"medium","min_us":73,"med_us":77,"p90_us":79,"max_us":95},{"op":"key-right","fixture":"medium","min_us":72,"med_us":77,"p90_us":80,"max_us":88},{"op":"page-down","fixture":"medium","min_us":72,"med_us":76,"p90_us":81,"max_us":83},{"op":"wheel","fixture":"medium","min_us":71,"med_us":75,"p90_us":80,"max_us":91},{"op":"edit-char","fixture":"medium","min_us":2662,"med_us":2999,"p90_us":3375,"max_us":3622}]} diff --git a/test/perf.zig b/test/perf.zig index 8eec1ed0..e244091c 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -323,6 +323,9 @@ const Options = struct { mini: bool = false, terminal_mib: ?usize = null, self_test: bool = false, + /// A gate: fail when a cell's fastest sample is more than this many + /// times the baseline's fastest (--base's). + max_ratio: ?f64 = null, fn parse(args: []const []const u8) !Options { var opts: Options = .{}; @@ -330,7 +333,7 @@ const Options = struct { while (i < args.len) : (i += 1) { const arg = args[i]; if (!std.mem.startsWith(u8, arg, "--")) return error.UnknownOption; - const option = std.meta.stringToEnum(enum { json, creation, startup, mini, @"terminal-mib", @"self-test", reps, cols, rows, base, only }, arg[2..]) orelse + const option = std.meta.stringToEnum(enum { json, creation, startup, mini, @"terminal-mib", @"self-test", reps, cols, rows, base, only, @"max-ratio" }, arg[2..]) orelse return error.UnknownOption; switch (option) { .json => opts.json = true, @@ -349,6 +352,7 @@ const Options = struct { .base => opts.base = value, .only => opts.only = value, .@"terminal-mib" => opts.terminal_mib = std.fmt.parseInt(usize, value, 10) catch return error.InvalidNumber, + .@"max-ratio" => opts.max_ratio = std.fmt.parseFloat(f64, value) catch return error.InvalidNumber, else => unreachable, } }, @@ -363,6 +367,10 @@ const Options = struct { if (opts.creation or opts.only != null or opts.base != null) return error.IncompatibleOptions; } if (opts.base) |path| if (path.len == 0) return error.MissingValue; + if (opts.max_ratio) |ratio| { + if (opts.base == null) return error.IncompatibleOptions; + if (!(ratio >= 1)) return error.InvalidMeasurement; + } if (opts.mini and (opts.creation or opts.terminal_mib != null or opts.only != null or opts.base != null)) return error.IncompatibleOptions; if (opts.only) |name| { @@ -431,8 +439,28 @@ pub fn main(init: std.process.Init) !void { } } - if (opts.json) return reportJson(init.io, &cells, &term_cells, &bytes, opts); - reportText(&cells, &term_cells, &bytes, reps, opts.base, base); + if (opts.json) try reportJson(init.io, &cells, &term_cells, &bytes, opts) else reportText(&cells, &term_cells, &bytes, reps, opts.base, base); + if (opts.max_ratio) |ratio| try gate(&cells, &base.?, ratio); +} + +/// The performance gate (zig build perf-gate): every measured cell's +/// fastest sample against the baseline's fastest. The fastest, not the +/// median: a loaded machine slows the median, rarely the best of a run, +/// while a regression slows every sample. +fn gate(cells: *const [std.enums.values(Op).len][fixtures.len]Cell, base: *const Base, ratio: f64) !void { + var failed = false; + for (std.enums.values(Op), 0..) |op, oi| for (fixtures, 0..) |fx, fi| { + const then = base.min[oi][fi]; + const now = cells[oi][fi].min_us; + if (then == 0 or now == 0) continue; + const x = @as(f64, @floatFromInt(now)) / @as(f64, @floatFromInt(then)); + if (x > ratio) { + std.debug.print("perf gate: {s} on {s} took {d} us at best, {d:.1}x the baseline's {d} us (limit {d:.1}x)\n", .{ op.label(), fx.name, now, x, then, ratio }); + failed = true; + } + }; + if (failed) return error.PerformanceRegression; + std.debug.print("perf gate: every cell within {d:.1}x of the baseline\n", .{ratio}); } fn measure(op: Op, fx: Fixture, path: []const u8, expected_bytes: usize, reps: usize) !Cell { @@ -1378,6 +1406,7 @@ fn writeJson( const Base = struct { med: [std.enums.values(Op).len][fixtures.len]u64, + min: [std.enums.values(Op).len][fixtures.len]u64 = @splat(@splat(0)), term_med: [std.enums.values(TermOp).len][term_fixtures.len]u64, }; @@ -1443,6 +1472,7 @@ fn parseBase(src: []const u8, opts: Options, bytes: *const [fixtures.len]usize) if (file_seen[oi][index]) return error.BaselineCoverage; file_seen[oi][index] = true; base.med[oi][index] = cell.med_us; + base.min[oi][index] = cell.min_us; } else { if (opts.only != null) return error.BaselineCoverage; const ti = for (term_fixtures, 0..) |fixture, index| { @@ -1487,8 +1517,22 @@ fn selfTest() !void { &.{ "--terminal-mib", "1", "--only", "small" }, &.{ "--terminal-mib", "1", "--creation" }, &.{ "--terminal-mib", "1", "--base", "old.json" }, &.{ "--mini", "--creation" }, &.{ "--mini", "--terminal-mib", "1" }, &.{ "--mini", "--base", "old.json" }, - &.{ "--mini", "--only", "small" }, + &.{ "--mini", "--only", "small" }, &.{ "--max-ratio", "3" }, }) |args| try testing.expectError(error.IncompatibleOptions, Options.parse(args)); + try testing.expectError(error.InvalidMeasurement, Options.parse(&.{ "--base", "old.json", "--max-ratio", "0.5" })); + const gated = try Options.parse(&.{ "--only", "medium", "--base", "old.json", "--max-ratio", "3" }); + try testing.expectEqual(@as(f64, 3), gated.max_ratio.?); + { + // A cell three and a half times its baseline's best fails; the + // rest pass. + var cells: [std.enums.values(Op).len][fixtures.len]Cell = @splat(@splat(.{})); + var base: Base = .{ .med = @splat(@splat(0)), .term_med = @splat(@splat(0)) }; + base.min[1][1] = 100; + cells[1][1] = .{ .min_us = 290, .med_us = 300, .p90_us = 300, .max_us = 300 }; + try gate(&cells, &base, 3); + cells[1][1].min_us = 350; + try testing.expectError(error.PerformanceRegression, gate(&cells, &base, 3)); + } const selected = try Options.parse(&.{ "--only", "small", "--reps", "2", "--cols", "80", "--rows", "24" }); try testing.expectEqual(@as(usize, 2), selected.reps); try testing.expectEqual(@as(u16, 80), selected.cols); -- cgit v1.3 From b6f07ba4e84e6d8474a118bee6e69e4b554417f1 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 17:56:54 -0300 Subject: An invalid byte in a grapheme is one cell, and never reaches vaxis's width uucode joins a stray lead byte (as U+FFFD) to a following e and combining mark into one grapheme; vaxis's gwidth then counts back the replacement rune's three bytes over the one byte it stood for and overflows (gwidth.zig:62), panicking the next frame after a write of \xee e \xcc\x81 to xdata (the 9P monkey's crash-b2417c49). graphemeDisplayWidth now gives each invalid byte one cell, as surface.zig draws it, and measures the valid runs between alone. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index 1d838c4f..99fccea8 100644 --- a/src/File.zig +++ b/src/File.zig @@ -266,7 +266,36 @@ test "stacked location metadata requires matching adjacent preview ownership" { pub fn graphemeDisplayWidth(grapheme: []const u8) usize { if (std.mem.eql(u8, grapheme, "\t")) return config.tab_width; if (grapheme.len == 1 and grapheme[0] >= 0x20 and grapheme[0] < 0x7f) return 1; - return @max(1, @as(usize, vaxis.gwidth.gwidth(grapheme, .unicode))); + if (std.unicode.utf8ValidateSlice(grapheme)) return @max(1, @as(usize, vaxis.gwidth.gwidth(grapheme, .unicode))); + // vaxis's gwidth counts back a replacement rune's 3 bytes over the one + // invalid byte it stood for (`\xee` before `e\u{301}` overflowed it): + // each invalid byte is a cell, as surface.zig draws it, and each valid + // run between is measured alone. + var width: usize = 0; + var run: usize = 0; + var i: usize = 0; + while (i < grapheme.len) { + const n = std.unicode.utf8ByteSequenceLength(grapheme[i]) catch 0; + if (n > 0 and i + n <= grapheme.len and std.unicode.utf8ValidateSlice(grapheme[i .. i + n])) { + i += n; + continue; + } + if (run < i) width += vaxis.gwidth.gwidth(grapheme[run..i], .unicode); + width += 1; + i += 1; + run = i; + } + if (run < grapheme.len) width += vaxis.gwidth.gwidth(grapheme[run..], .unicode); + return @max(1, width); +} + +test "an invalid byte in a grapheme is one cell, and never reaches vaxis's width" { + try std.testing.expectEqual(@as(usize, 2), graphemeDisplayWidth("\xeee\xcc\x81")); + try std.testing.expectEqual(@as(usize, 3), graphemeDisplayWidth("\xee\xffe")); + try std.testing.expectEqual(@as(usize, 3), graphemeDisplayWidth("\u{4e16}\x80")); + // The whole path the 9P fuzzer took: a body holding it, fitted to a width. + const text = "\xeee\xcc\x81"; + try std.testing.expectEqual(@as(usize, 4), fitEnd(text, 0, 10)); } pub fn byteDisplayWidth(byte: u8) usize { -- cgit v1.3 From b608fc54c40ff3dff6057569bd65d3f729c6d4f9 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 18:38:54 -0300 Subject: The grapheme width test expects two cells for two invalid bytes, as qsltkuom draws them Its reference list compared \xe4\xb8 with vaxis's own gwidth, which counts the pair one cell; since qsltkuom each invalid byte is a cell, one U+FFFD each, as surface.zig draws it, so the pair is two. The unit suite failed on it. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index 99fccea8..9f0f329c 100644 --- a/src/File.zig +++ b/src/File.zig @@ -462,8 +462,11 @@ test "the ASCII arm of graphemeDisplayWidth matches the gwidth it skips" { } for ([_][]const u8{ "e\u{301}", "a\u{903}", "1\u{fe0f}\u{20e3}", "\u{4e16}", - "\u{1f642}", "\u{1f1e6}\u{1f1e7}", "\xff", "\xe4\xb8", + "\u{1f642}", "\u{1f1e6}\u{1f1e7}", "\xff", }) |g| try std.testing.expectEqual(ref(g), graphemeDisplayWidth(g)); + // Two invalid bytes are two cells, as surface.zig draws them, where + // vaxis's own count gives the pair one. + try std.testing.expectEqual(@as(usize, 2), graphemeDisplayWidth("\xe4\xb8")); } test "the ASCII run in fitEnd survives an exhaustive byte sweep" { -- cgit v1.3 From 2b388888348860097967ae04d03f68c00a70472c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 20:25:28 -0300 Subject: Mini.zig is mini.zig: a file of functions and no fields takes a namespace's lowercase name The naming the split agreed on, deferred until now; panes.mini is its name at its importers. File.zig keeps its alias line (const Mini = panes.mini) so the file another agent is working in changes by that line alone. The served sources list and docs/design.typ name the new file. No behaviour changes; test/perf.zig's two references change, and since the perf harness is keyed by its own text, its three baselines are recorded again (under other agents' builds, so a little slower). Co-Authored-By: Claude Opus 5.5 --- docs/design.typ | 2 +- src/File.zig | 2 +- src/Mini.zig | 321 -------------------------------- src/builtins.zig | 2 +- src/fs.zig | 2 +- src/mini.zig | 321 ++++++++++++++++++++++++++++++++ src/panes.zig | 4 +- test/output.zig | 6 +- test/perf-baseline-gui-Debug.json | 2 +- test/perf-baseline-tty-Debug.json | 2 +- test/perf-baseline-tty-ReleaseFast.json | 2 +- test/perf.zig | 10 +- 12 files changed, 338 insertions(+), 338 deletions(-) delete mode 100644 src/Mini.zig create mode 100644 src/mini.zig (limited to 'src/File.zig') diff --git a/docs/design.typ b/docs/design.typ index ed2bbb94..20085706 100644 --- a/docs/design.typ +++ b/docs/design.typ @@ -526,7 +526,7 @@ verbatim by right-click and the delayed hover preview; that policy stays beside input because it also observes live pane selections and wrapped grid coordinates. Each pane kind keeps its storage and operations together in its own file -(`File.zig`, `Terminal.zig`, `Output.zig`, `Mini.zig`, `pdf_view.zig`, and the +(`File.zig`, `Terminal.zig`, `Output.zig`, `mini.zig`, `pdf_view.zig`, and the image pane in `image.zig`), reached through `panes.zig` beside `Pane`. `layout.zig` owns placement and presentation state. `pardes.zig` handles input and cross-pane state directly, without a pane vtable; the rest of the editor diff --git a/src/File.zig b/src/File.zig index 9f0f329c..c4040863 100644 --- a/src/File.zig +++ b/src/File.zig @@ -16,7 +16,7 @@ const limits = @import("memory.zig").limits; const locations = @import("locations.zig"); const Pane = panes.Pane; const Output = panes.Output; -const Mini = panes.Mini; +const Mini = panes.mini; const Terminal = panes.Terminal; const Text = panes.Text; diff --git a/src/Mini.zig b/src/Mini.zig deleted file mode 100644 index a6aef15a..00000000 --- a/src/Mini.zig +++ /dev/null @@ -1,321 +0,0 @@ -//! The Mini minimap: a file drawn four rows to a cell in braille dots. -const panes = @import("panes.zig"); -const std = @import("std"); -const pardes = @import("pardes.zig"); -const exec = @import("exec.zig"); -const config = @import("config.zig"); -const Pardes = pardes.Pardes; -const modal = @import("modal.zig"); -const filesystem = @import("fs.zig"); -const syntax = @import("syntax.zig"); -const File = panes.File; -const Output = panes.Output; - -pub const max_input_bytes = 4 * 1024 * 1024; -pub const max_output_bytes = 4 * 1024 * 1024; - -pub const State = struct { - source: []u8, - colors: []u8, - - pub fn deinit(state: *State, gpa: std.mem.Allocator) void { - gpa.free(state.source); - gpa.free(state.colors); - state.* = undefined; - } -}; - -pub const Result = struct { - content: []u8, - colors: []u8, - - pub fn deinit(result: Result, gpa: std.mem.Allocator) void { - gpa.free(result.content); - gpa.free(result.colors); - } -}; - -const Row = struct { - text: []const u8 = "", - base: usize = 0, - at: usize = 0, - left: usize = 0, - ink: bool = false, - color: u8 = 0, - - fn dot(row: *Row, styles: []const u8) ?u8 { - if (row.left == 0) { - if (row.at == row.text.len) return null; - const end = modal.nextGrapheme(row.text, row.at); - const grapheme = row.text[row.at..end]; - row.left = File.graphemeDisplayWidth(grapheme); - // unreachable below: `generate` refuses a source that is no UTF-8 - const n = std.unicode.utf8ByteSequenceLength(grapheme[0]) catch unreachable; - const cp = std.unicode.utf8Decode(grapheme[0..n]) catch unreachable; - const blank = switch (cp) { - '\t'...'\r', ' ', 0x85, 0xa0, 0x1680, 0x2000...0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000 => true, - else => false, - }; - row.ink = !blank or grapheme.len != n; - row.color = if (styles.len == 0) 0 else styles[row.base + row.at]; - row.at = end; - } - row.left -= 1; - return if (row.ink) row.color else null; - } -}; - -fn render(output: ?Result, source: []const u8, styles: []const u8) !usize { - if (source.len == 0) return 0; - const end = source.len - @intFromBool(source[source.len - 1] == '\n'); - var lines = std.mem.splitScalar(u8, source[0..end], '\n'); - var offset: usize = 0; - while (lines.peek() != null) { - var rows: [4]Row = @splat(.{}); - for (&rows) |*row| { - const line = lines.next() orelse break; - row.text = std.mem.trimEnd(u8, line, "\r"); - row.base = @intFromPtr(line.ptr) - @intFromPtr(source.ptr); - } - var spaces: usize = 0; - while (true) { - var more = false; - for (rows) |row| more = more or row.at < row.text.len or row.left > 0; - if (!more) break; - const bits = [4][2]u3{ .{ 0, 3 }, .{ 1, 4 }, .{ 2, 5 }, .{ 6, 7 } }; - var mask: u8 = 0; - var counts: [5]u8 = @splat(0); - for (&rows, 0..) |*row, y| { - for (0..2) |x| { - if (row.dot(styles)) |color| { - mask |= @as(u8, 1) << bits[y][x]; - counts[color] += 1; - } - } - } - if (mask == 0) { - spaces += 1; - continue; - } - if (spaces + 3 > max_output_bytes - offset) return error.MiniTooLarge; - var color: u8 = 0; - var most: u8 = 0; - for (counts[1..], 1..) |count, i| { - if (count > most) { - color = @intCast(i); - most = count; - } - } - if (output) |out| { - @memset(out.content[offset..][0..spaces], ' '); - @memset(out.colors[offset..][0..spaces], 0); - // unreachable: U+2800 plus a u8 mask is a braille codepoint, always three bytes - _ = std.unicode.utf8Encode(@as(u21, 0x2800) + mask, out.content[offset + spaces ..][0..3]) catch unreachable; - @memset(out.colors[offset + spaces ..][0..3], color); - } - offset += spaces + 3; - spaces = 0; - } - if (offset == max_output_bytes) return error.MiniTooLarge; - if (output) |out| { - out.content[offset] = '\n'; - out.colors[offset] = 0; - } - offset += 1; - } - return offset; -} - -pub fn generate(gpa: std.mem.Allocator, source: []const u8, styles: []const u8) !Result { - if (source.len > max_input_bytes) return error.MiniTooLarge; - if (!std.unicode.utf8ValidateSlice(source)) return error.InvalidUtf8; - if (styles.len != 0 and styles.len != source.len) return error.InvalidMiniColors; - for (styles) |color| if (color > @intFromEnum(syntax.Syn.comment)) return error.InvalidMiniColors; - const len = try render(null, source, styles); - const content = try gpa.alloc(u8, len); - errdefer gpa.free(content); - const colors = try gpa.alloc(u8, len); - errdefer gpa.free(colors); - const result: Result = .{ .content = content, .colors = colors }; - const written = try render(result, source, styles); - std.debug.assert(written == len); - return result; -} - -pub fn open(p: *Pardes, id: usize, argument: []const u8) !void { - const caller = p.panes[id] orelse return error.MissingPane; - const word = std.mem.trim(u8, argument, " \t\r\n"); - if (word.len == 0) return error.MissingPath; - var path_buf: [4096]u8 = undefined; - const target = filesystem.resolve(p, word, Pardes.paneDir(caller), &path_buf) orelse return error.FileNotFound; - if (target.dir) return error.NotAFile; - const source = try p.gpa.dupe(u8, target.path); - errdefer p.gpa.free(source); - const input = try filesystem.readLimit(p, source, max_input_bytes); - defer p.gpa.free(input); - const styles = try syntax.highlightFileRange(p.tree_sitter_gpa, source, input, 0, input.len); - defer p.tree_sitter_gpa.free(styles); - const result = try generate(p.gpa, input, styles); - errdefer result.deinit(p.gpa); - for (p.panes, 0..) |slot, i| { - const pane = slot orelse continue; - const file = if (pane.file) |*f| f else continue; - const old = file.mini orelse continue; - if (!std.mem.eql(u8, old.source, source)) continue; - if (std.mem.eql(u8, file.content, result.content) and std.mem.eql(u8, old.colors, result.colors)) { - p.gpa.free(source); - result.deinit(p.gpa); - } else { - File.setContent(p, file, result.content); - file.mini = .{ .source = source, .colors = result.colors }; - file.syntax_dirty = false; - Output.resetBody(p, pane); - } - p.active = i; - return; - } - const free = p.freeSlot() orelse return error.NoPaneSlots; - const dir = std.fs.path.dirname(source) orelse "/"; - const path = try std.fmt.allocPrint(p.gpa, "{s}/Mini {s}", .{ std.mem.trimEnd(u8, dir, "/"), std.fs.path.basename(source) }); - errdefer p.gpa.free(path); - const history = try File.History.create(p.gpa); - errdefer p.gpa.destroy(history); - const pane = try p.newDocPane(free); - pane.file = .{ - .path = path, - .content = result.content, - .output = .{ .from = .{ .cmd = .Mini } }, - .mini = .{ .source = source, .colors = result.colors }, - .history = history, - .syntax_dirty = false, - }; - pane.body.cur_pinned = true; - exec.placeNew(p, id, id, free, .doc); - p.active = free; -} - -test "Mini maps every braille dot and partial line group" { - const gpa = std.testing.allocator; - const bits = [4][2]u3{ .{ 0, 3 }, .{ 1, 4 }, .{ 2, 5 }, .{ 6, 7 } }; - for (0..256) |mask| { - var source: [12]u8 = undefined; - for (0..4) |row| { - for (0..2) |col| source[row * 3 + col] = if (mask & (@as(usize, 1) << bits[row][col]) != 0) 'x' else ' '; - source[row * 3 + 2] = '\n'; - } - const result = try generate(gpa, &source, ""); - defer result.deinit(gpa); - var expected: [4]u8 = undefined; - const len: usize = if (mask == 0) 0 else try std.unicode.utf8Encode(@as(u21, 0x2800) + @as(u21, @intCast(mask)), &expected); - expected[len] = '\n'; - try std.testing.expectEqualStrings(expected[0 .. len + 1], result.content); - try std.testing.expectEqual(result.content.len, result.colors.len); - for (result.colors) |color| try std.testing.expectEqual(@as(u8, 0), color); - } - for ([_]struct { source: []const u8, expected: []const u8 }{ - .{ .source = "", .expected = "" }, - .{ .source = "x", .expected = "⠁\n" }, - .{ .source = "xx\n", .expected = "⠉\n" }, - .{ .source = "x \n", .expected = "⠁\n" }, - .{ .source = "\n\n\n\nx", .expected = "\n⠁\n" }, - .{ .source = "x\r\nx\r\n", .expected = "⠃\n" }, - }) |case| { - const result = try generate(gpa, case.source, ""); - defer result.deinit(gpa); - try std.testing.expectEqualStrings(case.expected, result.content); - } -} - -test "Mini uses display cells for tabs combining text and wide characters" { - const gpa = std.testing.allocator; - for ([_]struct { source: []const u8, expected: []const u8 }{ - .{ .source = "e\u{301}界\n", .expected = "⠉⠁\n" }, - .{ .source = " x\n", .expected = " ⠁\n" }, - .{ .source = "\u{a0}x\n", .expected = "⠈\n" }, - }) |case| { - const result = try generate(gpa, case.source, ""); - defer result.deinit(gpa); - try std.testing.expectEqualStrings(case.expected, result.content); - } - const tabs = try generate(gpa, "\tx\n", ""); - defer tabs.deinit(gpa); - const spaces = config.tab_width / 2; - for (tabs.content[0..spaces]) |byte| try std.testing.expectEqual(@as(u8, ' '), byte); - try std.testing.expectEqualStrings(if (config.tab_width % 2 == 0) "⠁\n" else "⠈\n", tabs.content[spaces..]); -} - -test "Mini chooses highlighted dots over plain ink with stable color ties" { - const gpa = std.testing.allocator; - const source = "xx\nxx\nxx\nxx\n"; - var styles: [source.len]u8 = @splat(0); - styles[0] = @intFromEnum(syntax.Syn.keyword); - const rare = try generate(gpa, source, &styles); - defer rare.deinit(gpa); - try std.testing.expectEqualStrings("⣿\n", rare.content); - try std.testing.expectEqualSlices(u8, &.{ 1, 1, 1, 0 }, rare.colors); - styles[0] = @intFromEnum(syntax.Syn.string); - styles[1] = @intFromEnum(syntax.Syn.number); - const tied = try generate(gpa, source, &styles); - defer tied.deinit(gpa); - try std.testing.expectEqualSlices(u8, &.{ 2, 2, 2, 0 }, tied.colors); - styles[3] = @intFromEnum(syntax.Syn.number); - const majority = try generate(gpa, source, &styles); - defer majority.deinit(gpa); - try std.testing.expectEqualSlices(u8, &.{ 3, 3, 3, 0 }, majority.colors); -} - -test "Mini generation bounds and allocation failures leave no partial result" { - const Case = struct { - fn run(gpa: std.mem.Allocator) !void { - const result = try generate(gpa, "alpha\nbeta\ngamma\ndelta\nepsilon\n", ""); - defer result.deinit(gpa); - } - }; - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{}); - try std.testing.expectError(error.InvalidMiniColors, generate(std.testing.allocator, "x", &.{5})); - try std.testing.expectError(error.InvalidMiniColors, generate(std.testing.allocator, "xx", &.{0})); - var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 }); - const source = try std.testing.allocator.alloc(u8, max_input_bytes + 1); - defer std.testing.allocator.free(source); - try std.testing.expectError(error.MiniTooLarge, generate(allocator.allocator(), source, "")); - for (source[0..max_input_bytes], 0..) |*byte, i| byte.* = if (i % 2 == 0) 'x' else ' '; - try std.testing.expectError(error.MiniTooLarge, generate(allocator.allocator(), source[0..max_input_bytes], "")); - try std.testing.expect(!allocator.has_induced_failure); -} - -test "Mini publishes only complete snapshots and content replacement drops metadata" { - const Case = struct { - fn run(gpa: std.mem.Allocator, path: []const u8) !void { - const p = try Pardes.init(gpa, .{ .tty_only = true }); - defer p.deinit(); - const source = try p.setTestFile("untouched\n"); - const free = p.freeSlot(); - open(p, 0, path) catch |err| { - try std.testing.expectEqual(@as(usize, 0), p.active); - try std.testing.expectEqual(free, p.freeSlot()); - try std.testing.expectEqual(source, p.panes[0].?); - try std.testing.expectEqualStrings("untouched\n", source.file.?.content); - return err; - }; - const file = &p.panes[p.active].?.file.?; - try std.testing.expectEqualStrings("⠉\n", file.content); - try std.testing.expectEqualStrings(path, file.mini.?.source); - const replacement = try gpa.dupe(u8, "plain\n"); - File.setContent(p, file, replacement); - try std.testing.expect(file.mini == null); - try std.testing.expectEqualStrings("plain\n", file.content); - } - }; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "mini.txt", .data = "xx\n" }); - var dir_buf: [4096]u8 = undefined; - const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; - var path_buf: [4096]u8 = undefined; - const path = try std.fmt.bufPrint(&path_buf, "{s}/mini.txt", .{dir}); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{path}); -} - -test "Mini refuses a file that is no UTF-8, before its decoding could panic" { - try std.testing.expectError(error.InvalidUtf8, generate(std.testing.allocator, "ok \xff\xfe bad\n\xc3", "")); -} diff --git a/src/builtins.zig b/src/builtins.zig index 8a01b3d6..cc86067e 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1379,7 +1379,7 @@ pub const Mini = struct { pub const output: OutputTraits = .{ .name = "Mini", .doc = true }; pub fn run(c: Ctx) void { - panes.Mini.open(c.p, c.id, c.arg orelse "") catch |err| + panes.mini.open(c.p, c.id, c.arg orelse "") catch |err| c.p.reportError(c.id, "Mini", err); } }; diff --git a/src/fs.zig b/src/fs.zig index edead0ff..a2e8daf8 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -55,7 +55,7 @@ const source_files = [_]Source{ .{ .path = "src/Pipe.zig", .contents = @embedFile("Pipe.zig") }, .{ .path = "src/File.zig", .contents = @embedFile("File.zig") }, .{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") }, - .{ .path = "src/Mini.zig", .contents = @embedFile("Mini.zig") }, + .{ .path = "src/mini.zig", .contents = @embedFile("mini.zig") }, .{ .path = "src/image.zig", .contents = @embedFile("image.zig") }, .{ .path = "src/Terminal.zig", .contents = @embedFile("Terminal.zig") }, .{ .path = "src/pdf_view.zig", .contents = @embedFile("pdf_view.zig") }, diff --git a/src/mini.zig b/src/mini.zig new file mode 100644 index 00000000..a6aef15a --- /dev/null +++ b/src/mini.zig @@ -0,0 +1,321 @@ +//! The Mini minimap: a file drawn four rows to a cell in braille dots. +const panes = @import("panes.zig"); +const std = @import("std"); +const pardes = @import("pardes.zig"); +const exec = @import("exec.zig"); +const config = @import("config.zig"); +const Pardes = pardes.Pardes; +const modal = @import("modal.zig"); +const filesystem = @import("fs.zig"); +const syntax = @import("syntax.zig"); +const File = panes.File; +const Output = panes.Output; + +pub const max_input_bytes = 4 * 1024 * 1024; +pub const max_output_bytes = 4 * 1024 * 1024; + +pub const State = struct { + source: []u8, + colors: []u8, + + pub fn deinit(state: *State, gpa: std.mem.Allocator) void { + gpa.free(state.source); + gpa.free(state.colors); + state.* = undefined; + } +}; + +pub const Result = struct { + content: []u8, + colors: []u8, + + pub fn deinit(result: Result, gpa: std.mem.Allocator) void { + gpa.free(result.content); + gpa.free(result.colors); + } +}; + +const Row = struct { + text: []const u8 = "", + base: usize = 0, + at: usize = 0, + left: usize = 0, + ink: bool = false, + color: u8 = 0, + + fn dot(row: *Row, styles: []const u8) ?u8 { + if (row.left == 0) { + if (row.at == row.text.len) return null; + const end = modal.nextGrapheme(row.text, row.at); + const grapheme = row.text[row.at..end]; + row.left = File.graphemeDisplayWidth(grapheme); + // unreachable below: `generate` refuses a source that is no UTF-8 + const n = std.unicode.utf8ByteSequenceLength(grapheme[0]) catch unreachable; + const cp = std.unicode.utf8Decode(grapheme[0..n]) catch unreachable; + const blank = switch (cp) { + '\t'...'\r', ' ', 0x85, 0xa0, 0x1680, 0x2000...0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000 => true, + else => false, + }; + row.ink = !blank or grapheme.len != n; + row.color = if (styles.len == 0) 0 else styles[row.base + row.at]; + row.at = end; + } + row.left -= 1; + return if (row.ink) row.color else null; + } +}; + +fn render(output: ?Result, source: []const u8, styles: []const u8) !usize { + if (source.len == 0) return 0; + const end = source.len - @intFromBool(source[source.len - 1] == '\n'); + var lines = std.mem.splitScalar(u8, source[0..end], '\n'); + var offset: usize = 0; + while (lines.peek() != null) { + var rows: [4]Row = @splat(.{}); + for (&rows) |*row| { + const line = lines.next() orelse break; + row.text = std.mem.trimEnd(u8, line, "\r"); + row.base = @intFromPtr(line.ptr) - @intFromPtr(source.ptr); + } + var spaces: usize = 0; + while (true) { + var more = false; + for (rows) |row| more = more or row.at < row.text.len or row.left > 0; + if (!more) break; + const bits = [4][2]u3{ .{ 0, 3 }, .{ 1, 4 }, .{ 2, 5 }, .{ 6, 7 } }; + var mask: u8 = 0; + var counts: [5]u8 = @splat(0); + for (&rows, 0..) |*row, y| { + for (0..2) |x| { + if (row.dot(styles)) |color| { + mask |= @as(u8, 1) << bits[y][x]; + counts[color] += 1; + } + } + } + if (mask == 0) { + spaces += 1; + continue; + } + if (spaces + 3 > max_output_bytes - offset) return error.MiniTooLarge; + var color: u8 = 0; + var most: u8 = 0; + for (counts[1..], 1..) |count, i| { + if (count > most) { + color = @intCast(i); + most = count; + } + } + if (output) |out| { + @memset(out.content[offset..][0..spaces], ' '); + @memset(out.colors[offset..][0..spaces], 0); + // unreachable: U+2800 plus a u8 mask is a braille codepoint, always three bytes + _ = std.unicode.utf8Encode(@as(u21, 0x2800) + mask, out.content[offset + spaces ..][0..3]) catch unreachable; + @memset(out.colors[offset + spaces ..][0..3], color); + } + offset += spaces + 3; + spaces = 0; + } + if (offset == max_output_bytes) return error.MiniTooLarge; + if (output) |out| { + out.content[offset] = '\n'; + out.colors[offset] = 0; + } + offset += 1; + } + return offset; +} + +pub fn generate(gpa: std.mem.Allocator, source: []const u8, styles: []const u8) !Result { + if (source.len > max_input_bytes) return error.MiniTooLarge; + if (!std.unicode.utf8ValidateSlice(source)) return error.InvalidUtf8; + if (styles.len != 0 and styles.len != source.len) return error.InvalidMiniColors; + for (styles) |color| if (color > @intFromEnum(syntax.Syn.comment)) return error.InvalidMiniColors; + const len = try render(null, source, styles); + const content = try gpa.alloc(u8, len); + errdefer gpa.free(content); + const colors = try gpa.alloc(u8, len); + errdefer gpa.free(colors); + const result: Result = .{ .content = content, .colors = colors }; + const written = try render(result, source, styles); + std.debug.assert(written == len); + return result; +} + +pub fn open(p: *Pardes, id: usize, argument: []const u8) !void { + const caller = p.panes[id] orelse return error.MissingPane; + const word = std.mem.trim(u8, argument, " \t\r\n"); + if (word.len == 0) return error.MissingPath; + var path_buf: [4096]u8 = undefined; + const target = filesystem.resolve(p, word, Pardes.paneDir(caller), &path_buf) orelse return error.FileNotFound; + if (target.dir) return error.NotAFile; + const source = try p.gpa.dupe(u8, target.path); + errdefer p.gpa.free(source); + const input = try filesystem.readLimit(p, source, max_input_bytes); + defer p.gpa.free(input); + const styles = try syntax.highlightFileRange(p.tree_sitter_gpa, source, input, 0, input.len); + defer p.tree_sitter_gpa.free(styles); + const result = try generate(p.gpa, input, styles); + errdefer result.deinit(p.gpa); + for (p.panes, 0..) |slot, i| { + const pane = slot orelse continue; + const file = if (pane.file) |*f| f else continue; + const old = file.mini orelse continue; + if (!std.mem.eql(u8, old.source, source)) continue; + if (std.mem.eql(u8, file.content, result.content) and std.mem.eql(u8, old.colors, result.colors)) { + p.gpa.free(source); + result.deinit(p.gpa); + } else { + File.setContent(p, file, result.content); + file.mini = .{ .source = source, .colors = result.colors }; + file.syntax_dirty = false; + Output.resetBody(p, pane); + } + p.active = i; + return; + } + const free = p.freeSlot() orelse return error.NoPaneSlots; + const dir = std.fs.path.dirname(source) orelse "/"; + const path = try std.fmt.allocPrint(p.gpa, "{s}/Mini {s}", .{ std.mem.trimEnd(u8, dir, "/"), std.fs.path.basename(source) }); + errdefer p.gpa.free(path); + const history = try File.History.create(p.gpa); + errdefer p.gpa.destroy(history); + const pane = try p.newDocPane(free); + pane.file = .{ + .path = path, + .content = result.content, + .output = .{ .from = .{ .cmd = .Mini } }, + .mini = .{ .source = source, .colors = result.colors }, + .history = history, + .syntax_dirty = false, + }; + pane.body.cur_pinned = true; + exec.placeNew(p, id, id, free, .doc); + p.active = free; +} + +test "Mini maps every braille dot and partial line group" { + const gpa = std.testing.allocator; + const bits = [4][2]u3{ .{ 0, 3 }, .{ 1, 4 }, .{ 2, 5 }, .{ 6, 7 } }; + for (0..256) |mask| { + var source: [12]u8 = undefined; + for (0..4) |row| { + for (0..2) |col| source[row * 3 + col] = if (mask & (@as(usize, 1) << bits[row][col]) != 0) 'x' else ' '; + source[row * 3 + 2] = '\n'; + } + const result = try generate(gpa, &source, ""); + defer result.deinit(gpa); + var expected: [4]u8 = undefined; + const len: usize = if (mask == 0) 0 else try std.unicode.utf8Encode(@as(u21, 0x2800) + @as(u21, @intCast(mask)), &expected); + expected[len] = '\n'; + try std.testing.expectEqualStrings(expected[0 .. len + 1], result.content); + try std.testing.expectEqual(result.content.len, result.colors.len); + for (result.colors) |color| try std.testing.expectEqual(@as(u8, 0), color); + } + for ([_]struct { source: []const u8, expected: []const u8 }{ + .{ .source = "", .expected = "" }, + .{ .source = "x", .expected = "⠁\n" }, + .{ .source = "xx\n", .expected = "⠉\n" }, + .{ .source = "x \n", .expected = "⠁\n" }, + .{ .source = "\n\n\n\nx", .expected = "\n⠁\n" }, + .{ .source = "x\r\nx\r\n", .expected = "⠃\n" }, + }) |case| { + const result = try generate(gpa, case.source, ""); + defer result.deinit(gpa); + try std.testing.expectEqualStrings(case.expected, result.content); + } +} + +test "Mini uses display cells for tabs combining text and wide characters" { + const gpa = std.testing.allocator; + for ([_]struct { source: []const u8, expected: []const u8 }{ + .{ .source = "e\u{301}界\n", .expected = "⠉⠁\n" }, + .{ .source = " x\n", .expected = " ⠁\n" }, + .{ .source = "\u{a0}x\n", .expected = "⠈\n" }, + }) |case| { + const result = try generate(gpa, case.source, ""); + defer result.deinit(gpa); + try std.testing.expectEqualStrings(case.expected, result.content); + } + const tabs = try generate(gpa, "\tx\n", ""); + defer tabs.deinit(gpa); + const spaces = config.tab_width / 2; + for (tabs.content[0..spaces]) |byte| try std.testing.expectEqual(@as(u8, ' '), byte); + try std.testing.expectEqualStrings(if (config.tab_width % 2 == 0) "⠁\n" else "⠈\n", tabs.content[spaces..]); +} + +test "Mini chooses highlighted dots over plain ink with stable color ties" { + const gpa = std.testing.allocator; + const source = "xx\nxx\nxx\nxx\n"; + var styles: [source.len]u8 = @splat(0); + styles[0] = @intFromEnum(syntax.Syn.keyword); + const rare = try generate(gpa, source, &styles); + defer rare.deinit(gpa); + try std.testing.expectEqualStrings("⣿\n", rare.content); + try std.testing.expectEqualSlices(u8, &.{ 1, 1, 1, 0 }, rare.colors); + styles[0] = @intFromEnum(syntax.Syn.string); + styles[1] = @intFromEnum(syntax.Syn.number); + const tied = try generate(gpa, source, &styles); + defer tied.deinit(gpa); + try std.testing.expectEqualSlices(u8, &.{ 2, 2, 2, 0 }, tied.colors); + styles[3] = @intFromEnum(syntax.Syn.number); + const majority = try generate(gpa, source, &styles); + defer majority.deinit(gpa); + try std.testing.expectEqualSlices(u8, &.{ 3, 3, 3, 0 }, majority.colors); +} + +test "Mini generation bounds and allocation failures leave no partial result" { + const Case = struct { + fn run(gpa: std.mem.Allocator) !void { + const result = try generate(gpa, "alpha\nbeta\ngamma\ndelta\nepsilon\n", ""); + defer result.deinit(gpa); + } + }; + try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{}); + try std.testing.expectError(error.InvalidMiniColors, generate(std.testing.allocator, "x", &.{5})); + try std.testing.expectError(error.InvalidMiniColors, generate(std.testing.allocator, "xx", &.{0})); + var allocator = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 }); + const source = try std.testing.allocator.alloc(u8, max_input_bytes + 1); + defer std.testing.allocator.free(source); + try std.testing.expectError(error.MiniTooLarge, generate(allocator.allocator(), source, "")); + for (source[0..max_input_bytes], 0..) |*byte, i| byte.* = if (i % 2 == 0) 'x' else ' '; + try std.testing.expectError(error.MiniTooLarge, generate(allocator.allocator(), source[0..max_input_bytes], "")); + try std.testing.expect(!allocator.has_induced_failure); +} + +test "Mini publishes only complete snapshots and content replacement drops metadata" { + const Case = struct { + fn run(gpa: std.mem.Allocator, path: []const u8) !void { + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + const source = try p.setTestFile("untouched\n"); + const free = p.freeSlot(); + open(p, 0, path) catch |err| { + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(free, p.freeSlot()); + try std.testing.expectEqual(source, p.panes[0].?); + try std.testing.expectEqualStrings("untouched\n", source.file.?.content); + return err; + }; + const file = &p.panes[p.active].?.file.?; + try std.testing.expectEqualStrings("⠉\n", file.content); + try std.testing.expectEqualStrings(path, file.mini.?.source); + const replacement = try gpa.dupe(u8, "plain\n"); + File.setContent(p, file, replacement); + try std.testing.expect(file.mini == null); + try std.testing.expectEqualStrings("plain\n", file.content); + } + }; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "mini.txt", .data = "xx\n" }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var path_buf: [4096]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "{s}/mini.txt", .{dir}); + try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{path}); +} + +test "Mini refuses a file that is no UTF-8, before its decoding could panic" { + try std.testing.expectError(error.InvalidUtf8, generate(std.testing.allocator, "ok \xff\xfe bad\n\xc3", "")); +} diff --git a/src/panes.zig b/src/panes.zig index 32ad7b6b..b6fdc31a 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -636,7 +636,7 @@ pub const File = @import("File.zig"); pub const Output = @import("Output.zig"); -pub const Mini = @import("Mini.zig"); +pub const mini = @import("mini.zig"); pub const Image = @import("image.zig"); @@ -649,7 +649,7 @@ test { _ = Text; _ = File; _ = Output; - _ = Mini; + _ = mini; _ = Image; _ = Pdf; _ = Terminal; diff --git a/test/output.zig b/test/output.zig index e5f87fb7..1b1b80c9 100644 --- a/test/output.zig +++ b/test/output.zig @@ -472,7 +472,7 @@ test "Mini syntax colors survive toggles themes and rendering without source acc defer p.deinit(); try p.panes[0].?.setOwnedCwd(dir); p.settings.colors = false; - try panes.Mini.open(p, 0, "demo.zig"); + try panes.mini.open(p, 0, "demo.zig"); const id = p.active; const mini = p.panes[id].?; const keyword = std.mem.indexOfScalar(u8, mini.file.?.mini.?.colors, @intFromEnum(pardes.syntax.Syn.keyword)) orelse return error.MissingKeywordColor; @@ -522,12 +522,12 @@ test "Mini failures leave its existing snapshot and focus unchanged" { const source = try p.setTestFile("abc\n"); var path_buf: [128]u8 = undefined; const path = try std.fmt.bufPrint(&path_buf, "/virtual/pane/{d}/body", .{source.serial}); - try panes.Mini.open(p, 0, path); + try panes.mini.open(p, 0, path); const id = p.active; const mini = p.panes[id].?; const body = mini.file.?.content.ptr; const next = p.freeSlot(); - try std.testing.expectError(error.FileNotFound, panes.Mini.open(p, 0, "/virtual/does-not-exist")); + try std.testing.expectError(error.FileNotFound, panes.mini.open(p, 0, "/virtual/does-not-exist")); try std.testing.expectEqual(id, p.active); try std.testing.expectEqual(body, mini.file.?.content.ptr); try std.testing.expectEqual(next, p.freeSlot()); diff --git a/test/perf-baseline-gui-Debug.json b/test/perf-baseline-gui-Debug.json index 659e49d1..56a5da91 100644 --- a/test/perf-baseline-gui-Debug.json +++ b/test/perf-baseline-gui-Debug.json @@ -1 +1 @@ -{"harness":"b96624a78789195f","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1841,"med_us":2197,"p90_us":2308,"max_us":2328},{"op":"render","fixture":"medium","min_us":72,"med_us":81,"p90_us":84,"max_us":86},{"op":"key-down","fixture":"medium","min_us":74,"med_us":74,"p90_us":80,"max_us":81},{"op":"key-right","fixture":"medium","min_us":74,"med_us":80,"p90_us":85,"max_us":100},{"op":"page-down","fixture":"medium","min_us":74,"med_us":81,"p90_us":84,"max_us":176},{"op":"wheel","fixture":"medium","min_us":71,"med_us":75,"p90_us":79,"max_us":93},{"op":"edit-char","fixture":"medium","min_us":1086,"med_us":1515,"p90_us":1692,"max_us":1822},{"op":"body-2m","fixture":"medium","min_us":9044,"med_us":16111,"p90_us":19782,"max_us":21405}]} +{"harness":"5cbb536cdc74cbcf","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2022,"med_us":2284,"p90_us":2363,"max_us":2431},{"op":"render","fixture":"medium","min_us":80,"med_us":83,"p90_us":90,"max_us":94},{"op":"key-down","fixture":"medium","min_us":79,"med_us":82,"p90_us":87,"max_us":97},{"op":"key-right","fixture":"medium","min_us":82,"med_us":83,"p90_us":91,"max_us":95},{"op":"page-down","fixture":"medium","min_us":79,"med_us":83,"p90_us":84,"max_us":86},{"op":"wheel","fixture":"medium","min_us":79,"med_us":82,"p90_us":85,"max_us":87},{"op":"edit-char","fixture":"medium","min_us":1190,"med_us":1621,"p90_us":1843,"max_us":2008},{"op":"body-2m","fixture":"medium","min_us":9178,"med_us":16872,"p90_us":20886,"max_us":22596}]} diff --git a/test/perf-baseline-tty-Debug.json b/test/perf-baseline-tty-Debug.json index bed59c8c..9c4b5ebe 100644 --- a/test/perf-baseline-tty-Debug.json +++ b/test/perf-baseline-tty-Debug.json @@ -1 +1 @@ -{"harness":"b96624a78789195f","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1800,"med_us":2113,"p90_us":2193,"max_us":2326},{"op":"render","fixture":"medium","min_us":71,"med_us":76,"p90_us":85,"max_us":97},{"op":"key-down","fixture":"medium","min_us":73,"med_us":76,"p90_us":82,"max_us":84},{"op":"key-right","fixture":"medium","min_us":72,"med_us":76,"p90_us":81,"max_us":95},{"op":"page-down","fixture":"medium","min_us":74,"med_us":78,"p90_us":83,"max_us":83},{"op":"wheel","fixture":"medium","min_us":72,"med_us":75,"p90_us":82,"max_us":83},{"op":"edit-char","fixture":"medium","min_us":1027,"med_us":1418,"p90_us":1699,"max_us":1834},{"op":"body-2m","fixture":"medium","min_us":8357,"med_us":17722,"p90_us":20080,"max_us":21699}]} +{"harness":"5cbb536cdc74cbcf","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1902,"med_us":2386,"p90_us":2484,"max_us":2686},{"op":"render","fixture":"medium","min_us":83,"med_us":87,"p90_us":93,"max_us":118},{"op":"key-down","fixture":"medium","min_us":88,"med_us":94,"p90_us":100,"max_us":156},{"op":"key-right","fixture":"medium","min_us":83,"med_us":86,"p90_us":88,"max_us":92},{"op":"page-down","fixture":"medium","min_us":78,"med_us":84,"p90_us":89,"max_us":101},{"op":"wheel","fixture":"medium","min_us":77,"med_us":84,"p90_us":89,"max_us":132},{"op":"edit-char","fixture":"medium","min_us":1177,"med_us":1519,"p90_us":1721,"max_us":1909},{"op":"body-2m","fixture":"medium","min_us":8533,"med_us":15772,"p90_us":21361,"max_us":23276}]} diff --git a/test/perf-baseline-tty-ReleaseFast.json b/test/perf-baseline-tty-ReleaseFast.json index d13442a5..984d480a 100644 --- a/test/perf-baseline-tty-ReleaseFast.json +++ b/test/perf-baseline-tty-ReleaseFast.json @@ -1 +1 @@ -{"harness":"b96624a78789195f","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1819,"med_us":2002,"p90_us":2068,"max_us":2122},{"op":"render","fixture":"medium","min_us":71,"med_us":76,"p90_us":88,"max_us":89},{"op":"key-down","fixture":"medium","min_us":73,"med_us":75,"p90_us":76,"max_us":82},{"op":"key-right","fixture":"medium","min_us":73,"med_us":77,"p90_us":86,"max_us":126},{"op":"page-down","fixture":"medium","min_us":71,"med_us":75,"p90_us":81,"max_us":83},{"op":"wheel","fixture":"medium","min_us":71,"med_us":74,"p90_us":76,"max_us":97},{"op":"edit-char","fixture":"medium","min_us":1036,"med_us":1493,"p90_us":1805,"max_us":1967},{"op":"body-2m","fixture":"medium","min_us":8482,"med_us":17227,"p90_us":20296,"max_us":23040}]} +{"harness":"5cbb536cdc74cbcf","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2061,"med_us":2326,"p90_us":2462,"max_us":2503},{"op":"render","fixture":"medium","min_us":76,"med_us":80,"p90_us":86,"max_us":98},{"op":"key-down","fixture":"medium","min_us":78,"med_us":83,"p90_us":91,"max_us":95},{"op":"key-right","fixture":"medium","min_us":77,"med_us":81,"p90_us":86,"max_us":90},{"op":"page-down","fixture":"medium","min_us":77,"med_us":81,"p90_us":89,"max_us":90},{"op":"wheel","fixture":"medium","min_us":75,"med_us":82,"p90_us":87,"max_us":94},{"op":"edit-char","fixture":"medium","min_us":1277,"med_us":1713,"p90_us":1948,"max_us":2063},{"op":"body-2m","fixture":"medium","min_us":9261,"med_us":17043,"p90_us":23512,"max_us":23722}]} diff --git a/test/perf.zig b/test/perf.zig index c639178f..38c640b4 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -1023,12 +1023,12 @@ const MiniMeasurement = struct { live_after_deinit: usize = 0, }; -fn checkMini(actual: pardes.panes.Mini.Result, expected: pardes.panes.Mini.Result) !void { +fn checkMini(actual: pardes.panes.mini.Result, expected: pardes.panes.mini.Result) !void { if (!std.mem.eql(u8, actual.content, expected.content) or !std.mem.eql(u8, actual.colors, expected.colors)) return error.MiniOutputMismatch; } -fn miniMeasurement(fallback: std.mem.Allocator, probe: MiniProbe, path: []const u8, source: []const u8, styles: []const u8, expected: pardes.panes.Mini.Result, reps: usize) !MiniMeasurement { +fn miniMeasurement(fallback: std.mem.Allocator, probe: MiniProbe, path: []const u8, source: []const u8, styles: []const u8, expected: pardes.panes.mini.Result, reps: usize) !MiniMeasurement { const samples = try gpa.alloc(u64, reps); defer gpa.free(samples); const allocators = pardes.memory.init(fallback); @@ -1059,7 +1059,7 @@ fn miniMeasurement(fallback: std.mem.Allocator, probe: MiniProbe, path: []const defer arena.deinit(); if (core) |p| { pump(p); - try pardes.panes.Mini.open(p, 0, path); + try pardes.panes.mini.open(p, 0, path); for (p.panes, 0..) |slot, id| if (slot != null and id != p.active) try p.removePane(id, null); pump(p); p.settings.colors = true; @@ -1095,7 +1095,7 @@ fn miniMeasurement(fallback: std.mem.Allocator, probe: MiniProbe, path: []const else styles; defer if (probe == .highlight_generate) syntax_allocator.free(highlighted); - const converted = try pardes.panes.Mini.generate(allocator, source, highlighted); + const converted = try pardes.panes.mini.generate(allocator, source, highlighted); const elapsed = nowNs() - begin; defer converted.deinit(allocator); if (index == 0) result.cold_ns = elapsed else samples[index - 1] = elapsed; @@ -1151,7 +1151,7 @@ fn measureMini(io: std.Io, fallback: std.mem.Allocator, reps: usize, json: bool) defer gpa.free(styles); if (styles.len != source.len or std.mem.indexOfScalar(u8, styles, @intFromEnum(pardes.syntax.Syn.comment)) == null) return error.MiniSyntaxUnavailable; - const expected = try pardes.panes.Mini.generate(gpa, source, styles); + const expected = try pardes.panes.mini.generate(gpa, source, styles); defer expected.deinit(gpa); if (expected.content.len == 0 or expected.content.len != expected.colors.len or !std.unicode.utf8ValidateSlice(expected.content)) return error.InvalidMiniOutput; -- cgit v1.3 From 04b047fb366ea2c595708fb62467f690fce4b9ec Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 20:56:14 -0300 Subject: Terminal.zig is terminal.zig: a file of functions and no fields takes a namespace's lowercase name The last of the deferred renames, now that the tty and theme agents have landed: panes.terminal at its importers, the alias lines in Text.zig and File.zig and panes.zig's own uses following. dump.zig's Terminal struct, a dump record, is not this. The served sources list and docs/design.typ name the new file. test/perf.zig's references change, so the three perf baselines take its new harness id with their numbers as recorded. No behaviour changes. Co-Authored-By: Claude Opus 5.5 --- docs/design.typ | 2 +- src/File.zig | 6 +- src/Terminal.zig | 2670 ------------------------------- src/Text.zig | 18 +- src/body_layer.zig | 16 +- src/builtins.zig | 2 +- src/draw.zig | 8 +- src/dump.zig | 4 +- src/edit.zig | 26 +- src/exec.zig | 34 +- src/fs.zig | 2 +- src/host_io.zig | 2 +- src/layout.zig | 4 +- src/mouse.zig | 6 +- src/ninep/ctl.zig | 2 +- src/ninep/pane.zig | 4 +- src/ninep/pty.zig | 24 +- src/ninep/screen.zig | 4 +- src/panes.zig | 20 +- src/pardes.zig | 106 +- src/terminal.zig | 2670 +++++++++++++++++++++++++++++++ src/tty/tty.zig | 2 +- test/mode.zig | 2 +- test/panes.zig | 60 +- test/perf-baseline-gui-Debug.json | 2 +- test/perf-baseline-tty-Debug.json | 2 +- test/perf-baseline-tty-ReleaseFast.json | 2 +- test/perf.zig | 16 +- 28 files changed, 2858 insertions(+), 2858 deletions(-) delete mode 100644 src/Terminal.zig create mode 100644 src/terminal.zig (limited to 'src/File.zig') diff --git a/docs/design.typ b/docs/design.typ index ebbf213a..ec9bd5c4 100644 --- a/docs/design.typ +++ b/docs/design.typ @@ -526,7 +526,7 @@ verbatim by right-click and the delayed hover preview; that policy stays beside input because it also observes live pane selections and wrapped grid coordinates. Each pane kind keeps its storage and operations together in its own file -(`File.zig`, `Terminal.zig`, `Output.zig`, `mini.zig`, `pdf_view.zig`, and the +(`File.zig`, `terminal.zig`, `Output.zig`, `mini.zig`, `pdf_view.zig`, and the image pane in `image.zig`), reached through `panes.zig` beside `Pane`. `layout.zig` owns placement and presentation state. `pardes.zig` handles input and cross-pane state directly, without a pane vtable; the rest of the editor diff --git a/src/File.zig b/src/File.zig index c4040863..8babb27d 100644 --- a/src/File.zig +++ b/src/File.zig @@ -17,7 +17,7 @@ const locations = @import("locations.zig"); const Pane = panes.Pane; const Output = panes.Output; const Mini = panes.mini; -const Terminal = panes.Terminal; +const terminal = panes.terminal; const Text = panes.Text; const SYNTAX_CONTEXT_AFTER_ROWS: usize = 2; @@ -782,7 +782,7 @@ pub fn open(p: *Pardes, id: usize, path: []const u8, line: usize) !*Pane { std.debug.assert(p.panes[id] == null and !p.reserved_slots[id]); const path_copy = try p.gpa.dupe(u8, path); errdefer p.gpa.free(path_copy); - const pane = try Terminal.createDoc(p.gpa, p.screen_w, p.screen_h); + const pane = try terminal.createDoc(p.gpa, p.screen_w, p.screen_h); errdefer p.gpa.destroy(pane); const history = try History.create(p.gpa); errdefer p.gpa.destroy(history); @@ -1239,7 +1239,7 @@ fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) pub fn drawGutter(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, active: bool) void { const prefix_width = gutterWidth(pane); const goff = pane.scroll(); - const gcur = Terminal.gridCursor(pane); + const gcur = terminal.gridCursor(pane); const gcrow = if (pane.body.cur_pinned) pane.body.cur_row else @as(i32, gcur.y) + goff; const typing_body = pane.focus == .body and (pane.prompt == .none or pane.prompt == .del_side or pane.prompt == .repl_choice); const cur_line: i32 = if (active and typing_body) gcrow else std.math.minInt(i32); diff --git a/src/Terminal.zig b/src/Terminal.zig deleted file mode 100644 index c99a92a6..00000000 --- a/src/Terminal.zig +++ /dev/null @@ -1,2670 +0,0 @@ -//! A terminal pane: its VT emulator and replay, prompt rows, the edit overlay -//! typed over shell rows, and the Filter that recolours output to the theme. -const panes = @import("panes.zig"); -const std = @import("std"); -const pardes = @import("pardes.zig"); -const config = @import("config.zig"); -const Pardes = pardes.Pardes; -const Surface = pardes.Surface; -const modal = @import("modal.zig"); -const tracy = @import("tracy.zig"); -const dump = @import("dump.zig"); -const Key = pardes.Key; -const Pane = panes.Pane; -const EditText = panes.EditText; -const File = panes.File; - -pub const enabled = pardes.terminal_panes; -const ghostty_vt = if (enabled) @import("ghostty-vt") else struct {}; - -pub const history_max = if (enabled) 64 else 8; - -pub const VtSlot = if (enabled) ghostty_vt.Terminal else void; -pub const StreamSlot = if (enabled) ghostty_vt.Stream(MarkedHandler) else void; - -/// The `aid` pardes's injected bash and fish marks carry (host_io.zig). -pub const prompt_aid = "pardes"; - -/// ghostty's handler, plus where the shell is in its command cycle as -/// its OSC 133 marks tell it: ghostty parses D's exit status and drops -/// it, and /pane//pty/run waits on exactly that. Only marks carrying -/// pardes's own `aid` move it, so fish's native marks, a nested shell's -/// and a stray `133;D` in some file being printed all pass it by. -pub const MarkedHandler = if (enabled) struct { - inner: ghostty_vt.TerminalStream.Handler, - phase: enum { none, prompt, input, running } = .none, - /// Counts commands started (C at the input phase). - started: u32 = 0, - /// Counts prompts drawn (B), so a line the shell refused without - /// running (a fish syntax error: no C, no D, a new prompt) shows. - prompts: u32 = 0, - /// D marks outside a running command: the shell handled a line - /// without starting it (bash on a syntax error prints no C). - declined: u32 = 0, - /// The newest prompt continues an unfinished line (bash's PS2, marked - /// `k=c`): the shell still holds the start of the command. - continuation: bool = false, - /// Where the newest command's output began (its C) and ended (its - /// D) on the primary screen, pinned so scrolling keeps them. - out_start: ?*ghostty_vt.Pin = null, - out_end: ?*ghostty_vt.Pin = null, - /// The running command's output was erased under it -- a clear, ED 3, - /// a reset -- so the pins no longer span what it printed: ED 3 moves - /// a pin to the next page without flagging it `garbage` - /// (PageList.erasePage). - lost: bool = false, - - /// The newest command to end: which one, and its status if given. - finished: ?struct { seq: u32, status: ?i32 } = null, - - const Action = ghostty_vt.TerminalStream.Action; - - /// Move one of the output pins to the cursor. Only the primary screen - /// is pinned: a command's own full-screen display is not its output. - fn pinCursor(self: *@This(), slot: *?*ghostty_vt.Pin, now: bool) void { - const screen = self.inner.terminal.screens.get(.primary) orelse return; - if (slot.*) |old| screen.pages.untrackPin(old); - slot.* = null; - if (!now or self.inner.terminal.screens.active_key != .primary) return; - slot.* = screen.pages.trackPin(screen.cursor.page_pin.*) catch null; - } - - pub fn vt(self: *@This(), comptime action: Action.Tag, value: Action.Value(action)) void { - if (comptime action == .semantic_prompt) mark: { - const aid = value.readOption(.aid) orelse break :mark; - if (!std.mem.eql(u8, aid, prompt_aid)) break :mark; - switch (value.action) { - .fresh_line_new_prompt => { - self.phase = .prompt; - self.continuation = value.readOption(.prompt_kind) == .continuation; - }, - .end_prompt_start_input => { - self.phase = .input; - self.prompts +%= 1; - }, - // bash's DEBUG trap also fires on its own PROMPT_COMMAND, - // outside the input phase; only a C that ends input counts - .end_input_start_output => if (self.phase == .input) { - self.phase = .running; - self.started +%= 1; - self.lost = false; - self.pinCursor(&self.out_start, true); - self.pinCursor(&self.out_end, false); - }, - .end_command => if (self.phase == .running) { - self.phase = .none; - self.finished = .{ .seq = self.started, .status = value.readOption(.exit_code) }; - self.pinCursor(&self.out_end, true); - } else { - self.declined +%= 1; - }, - else => {}, - } - } - if (comptime action == .erase_display_complete or action == .erase_display_scrollback or action == .full_reset) { - if (self.phase == .running) self.lost = true; - } - self.inner.vt(action, value); - } - - pub fn deinit(self: *@This()) void { - self.inner.deinit(); - } -} else void; - -pub const Replay = struct { - bytes: [1024 * 1024]u8 = undefined, - head: usize = 0, - len: usize = 0, -}; - -pub const State = struct { - vt: VtSlot, - stream: StreamSlot, - replay: Replay, - reply: [256]u8 = undefined, - reply_len: u16 = 0, -}; - -const GColor = ghostty_vt.color; - -const FilterPaletteKey = struct { - bg: GColor.RGB, - fg: GColor.RGB, - base: [16]GColor.RGB, -}; - -pub const FilterPalette = if (enabled) LivePalette else struct {}; - -const LivePalette = struct { - key: ?FilterPaletteKey = null, - colors: GColor.Palette = GColor.default, - - fn get(self: *LivePalette, theme: *const pardes.Theme) *const GColor.Palette { - const bg = asGhostRgb(theme.bg orelse theme.tag_bg); - const fg = asGhostRgb(theme.fg orelse theme.tag_fg); - var base: [16]GColor.RGB = undefined; - if (theme.palette) |palette| { - for (&base, palette) |*dst, src| dst.* = asGhostRgb(src); - } else { - const synthesized = [16][3]u8{ - theme.bg orelse theme.tag_bg, - theme.kw, - theme.str, - theme.num, - theme.box, - theme.sel_bg, - theme.comment, - theme.fg orelse theme.tag_fg, - theme.lineno, - theme.kw, - theme.str, - theme.num, - theme.scroll_thumb, - theme.sel_fg, - theme.tag_fg, - theme.fg orelse theme.tag_fg, - }; - for (&base, synthesized) |*dst, src| dst.* = asGhostRgb(src); - } - - const key: FilterPaletteKey = .{ .bg = bg, .fg = fg, .base = base }; - if (self.key) |old| if (std.meta.eql(old, key)) return &self.colors; - - var seed = GColor.default; - for (base, 0..) |rgb, i| seed[i] = rgb; - self.colors = GColor.generate256Color(seed, .initEmpty(), bg, fg, false); - self.key = key; - return &self.colors; - } -}; - -fn asGhostRgb(rgb: [3]u8) GColor.RGB { - return .{ .r = rgb[0], .g = rgb[1], .b = rgb[2] }; -} - -fn asPardesColor(rgb: GColor.RGB) pardes.Color { - return .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; -} - -/// The owned text standing in for `rows` live terminal rows, beginning at -/// absolute surface row `row`. The emulator grid remains untouched underneath. -pub const EditBuffer = struct { - row: i32 = 0, - rows: i32 = 1, - text: []u8 = &.{}, -}; - -/// One whole-state terminal edit boundary. Null means the pane has not yet -/// materialized an edit buffer; non-null snapshots own their text. -pub const Snapshot = struct { - ovl: ?EditBuffer, - cur_row: i32, - cur_col: i32, - vsel: panes.Text.CharSel, -}; - -pub const PendingCommand = struct { - bytes: []u8 = &.{}, - wait: enum { none, spawn, input } = .none, -}; - -pub fn armShellSpawn(pane: *Pane) void { - if (comptime !enabled) return; - std.debug.assert(pane.pending_command.bytes.len == 0); - pane.pending_command.wait = .spawn; -} - -/// Remembers a line pardes types into this terminal as the command it -/// started, for Kill: it runs from the shell's next C mark to its D. -/// ponytail: of several lines queued for a shell not up yet, only the last -/// is remembered, as the first of them. -pub fn noteCommand(pane: *Pane, line: []const u8) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - const word = std.mem.trim(u8, line, " \t")[0 .. std.mem.indexOfAny(u8, std.mem.trim(u8, line, " \t"), " \t") orelse std.mem.trim(u8, line, " \t").len]; - var sent: @typeInfo(@FieldType(Pane, "sent_command")).optional.child = .{ .seq = state.stream.handler.started +% 1 }; - sent.len = @intCast(@min(word.len, sent.word.len)); - @memcpy(sent.word[0..sent.len], word[0..sent.len]); - pane.sent_command = sent; -} - -/// Whether the command pardes last typed here is running now. -pub fn commandRunning(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - const sent = pane.sent_command orelse return false; - const marks = &state.stream.handler; - return marks.phase == .running and marks.started == sent.seq; -} - -pub fn queuePendingCommand(pane: *Pane, command: []const u8) !bool { - if (pane.pending_command.wait == .none) return false; - const old_len = pane.pending_command.bytes.len; - const new_len = try std.math.add(usize, old_len, try std.math.add(usize, command.len, 1)); - const bytes = if (old_len == 0) - try pane.gpa.alloc(u8, new_len) - else - try pane.gpa.realloc(pane.pending_command.bytes, new_len); - @memcpy(bytes[old_len..][0..command.len], command); - bytes[new_len - 1] = '\r'; - pane.pending_command.bytes = bytes; - pane.greet = false; - return true; -} - -pub fn shellSpawned(p: *Pardes, id: usize, prompt_marks: bool) void { - const pane = p.panes[id] orelse return; - if (!pane.isTerminal() or pane.pending_command.wait != .spawn) return; - if (prompt_marks) { - pane.pending_command.wait = .input; - releasePendingCommand(p, id, pane, false); - } else { - pane.greet = false; - releasePendingCommand(p, id, pane, true); - } -} - -pub fn releasePendingCommandIfReady(p: *Pardes, id: usize, pane: *Pane) void { - if (pane.pending_command.wait == .input) - releasePendingCommand(p, id, pane, promptInputReady(pane)); -} - -fn releasePendingCommand(p: *Pardes, id: usize, pane: *Pane, ready: bool) void { - if (!ready) return; - const bytes = pane.pending_command.bytes; - pane.pending_command = .{}; - if (bytes.len > 0) { - p.emitWrite(id, bytes); - pane.gpa.free(bytes); - } -} - -pub fn deinitPendingCommand(pane: *Pane) void { - if (pane.pending_command.bytes.len > 0) - pane.gpa.free(pane.pending_command.bytes); - pane.pending_command = .{}; -} - -pub fn terminalIo() std.Io { - return if (comptime !pardes.hosted) - std.Io.failing - else - std.Io.Threaded.global_single_threaded.io(); -} - -/// The three numbers ghostty's scrollbar reports; all zero without an emulator. -pub const Scrollbar = struct { total: usize = 0, offset: usize = 0, len: usize = 0 }; - -pub fn scrollbar(pane: *const Pane) Scrollbar { - if (comptime !enabled) return .{}; - const state = pane.terminal orelse return .{}; - const sb = state.vt.screens.active.pages.scrollbar(); - return .{ .total = sb.total, .offset = sb.offset, .len = sb.len }; -} - -/// The emulator's viewport offset, in SHELL rows: the top of what it shows. -pub fn gridOffset(pane: *const Pane) i32 { - return @intCast(scrollbar(pane).offset); -} - -/// Where the emulator itself puts the cursor, in active-area cells — the origin -/// without one, which is where an empty pane's cursor belongs anyway. -pub const GridCursor = struct { x: u16 = 0, y: u16 = 0 }; - -pub fn gridCursor(pane: *const Pane) GridCursor { - if (comptime !enabled) return .{}; - const state = pane.terminal orelse return .{}; - const cur = state.vt.screens.active.cursor; - return .{ .x = @intCast(cur.x), .y = @intCast(cur.y) }; -} - -pub fn visibleCursor(pane: *const Pane) ?GridCursor { - if (comptime !enabled) return null; - const state = pane.terminal orelse return null; - if (!state.vt.modes.get(.cursor_visible)) return null; - const cur = state.vt.screens.active.cursor; - const sb = scrollbar(pane); - const row = sb.total - sb.len + cur.y; - if (row < sb.offset or row - sb.offset >= sb.len) return null; - return .{ .x = @intCast(cur.x), .y = @intCast(row - sb.offset) }; -} - -/// Move the emulator's viewport by `delta` shell rows (negative scrolls back). -pub fn scrollGrid(pane: *Pane, delta: i32) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - state.vt.screens.active.scroll(.{ .delta_row = delta }); -} - -/// Is the viewport already showing the last row of output? -pub fn atBottom(pane: *const Pane) bool { - if (comptime !enabled) return true; - const sb = scrollbar(pane); - return sb.offset + sb.len >= sb.total; -} - -/// Snap the viewport back onto live output. -pub fn followOutput(pane: *Pane) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - state.vt.screens.active.scroll(.active); -} - -/// Reflow the grid. A failed reflow keeps the grid it had rather than dropping -/// a scrollback; the next resize retries with the same numbers. -pub fn resizeGrid(pane: *Pane, gpa: std.mem.Allocator, cols: u16, rows: u16) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - if (cols != pane.cols) for (0..pane.sel.len) |button| { - pane.clearPointerSelection(button); - pane.sel[button].state = .none; - }; - state.vt.resize(gpa, .{ .cols = cols, .rows = rows }) catch {}; -} - -/// DECSET 2004: the program wants its pastes bracketed. -pub fn bracketedPaste(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - return state.vt.modes.get(.bracketed_paste); -} - -/// The program tracks the mouse itself, so a click in its body is its event. -pub fn reportsMouse(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - const m = &state.vt.modes; - return m.get(.mouse_event_normal) or m.get(.mouse_event_button) or m.get(.mouse_event_any); -} - -/// ...and wants them in SGR (1006) rather than the legacy X10 bytes. -pub fn mouseFormatSgr(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - return state.vt.modes.get(.mouse_format_sgr); -} - -/// The whole scrollback as plain text, `gpa`-owned: what a terminal's body -/// reads and `Save` writes out. Logical lines: rows the terminal wrapped -/// are joined again (ghostty's wrap flags, as pty/run's output is), and -/// the last line ends with a newline. -pub fn screenTextAlloc(pane: *Pane, gpa: std.mem.Allocator) ![]const u8 { - if (comptime !enabled) return &.{}; - var out: std.Io.Writer.Allocating = .init(gpa); - errdefer out.deinit(); - try writeScreenText(pane, &out.writer); - return out.toOwnedSlice(); -} - -fn writeScreenText(pane: *Pane, w: *std.Io.Writer) !void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - const screen = state.vt.screens.active; - const br = screen.pages.getBottomRight(.screen) orelse return; - var both: TeeWriter = .{ .a = w }; - try screen.dumpString(&both.writer, .{ .tl = screen.pages.getTopLeft(.screen), .br = br, .unwrap = true }); - if (both.count > 0 and both.final != '\n') try w.writeByte('\n'); -} - -/// Passes bytes through, remembering how many and the last one. -const TeeWriter = struct { - a: *std.Io.Writer, - count: usize = 0, - final: u8 = 0, - writer: std.Io.Writer = .{ .vtable = &.{ .drain = drain }, .buffer = &.{} }, - - fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { - const t: *TeeWriter = @alignCast(@fieldParentPtr("writer", w)); - var n: usize = 0; - for (data[0 .. data.len - 1]) |bytes| { - try t.a.writeAll(bytes); - t.note(bytes); - n += bytes.len; - } - const pattern = data[data.len - 1]; - for (0..splat) |_| { - try t.a.writeAll(pattern); - t.note(pattern); - n += pattern.len; - } - return n; - } - - fn note(t: *TeeWriter, bytes: []const u8) void { - if (bytes.len == 0) return; - t.count += bytes.len; - t.final = bytes[bytes.len - 1]; - } -}; - -/// How long `screenTextAlloc` would be, counted without keeping it: the -/// length a terminal's body reads as, which its ctl line reports. -pub fn screenTextLen(pane: *Pane) usize { - if (comptime !enabled) return 0; - var buf: [256]u8 = undefined; - var counting: std.Io.Writer.Discarding = .init(&buf); - writeScreenText(pane, &counting.writer) catch return 0; - return @intCast(counting.fullCount()); -} - -/// Release the emulator's heap. The Pane allocation itself is the core's. -pub fn deinitEmulator(pane: *Pane, gpa: std.mem.Allocator) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - state.stream.deinit(); - state.vt.deinit(gpa); - gpa.destroy(state); - pane.terminal = null; -} - -/// Allocate the live emulator half of a terminal pane. Slot ownership, serial -/// assignment, and spawn effects remain core lifecycle invariants. -pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { - const pane = try createDoc(gpa, cols, rows); - errdefer gpa.destroy(pane); - if (comptime !enabled) return pane; - const state = try gpa.create(State); - errdefer gpa.destroy(state); - state.vt = try ghostty_vt.Terminal.init(terminalIo(), gpa, .{ - .cols = cols, - .rows = rows, - .max_scrollback = 16 * 1024 * 1024, - }); - state.stream = .initAlloc(gpa, .{ .inner = state.vt.vtHandler() }); - state.replay.head = 0; - state.replay.len = 0; - state.reply_len = 0; - state.stream.handler.inner.effects.write_pty = ptyReport; - state.stream.handler.inner.effects.device_attributes = ptyDeviceAttrs; - pane.terminal = state; - pane.tty_filter = true; - return pane; -} - -pub fn createDoc(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { - const pane = try gpa.create(Pane); - pane.* = .{ - .gpa = gpa, - .cols = cols, - .rows = rows, - }; - return pane; -} - -/// Where a restored terminal's history ends and its new shell begins. -pub const restored_banner = "\x1b[0m\r\n\x1b[2m\u{2500}\u{2500} restored history \u{2500}\u{2500}\x1b[0m\r\n"; - -/// Rebuild a dump's terminal emulator from its recorded output. `live`: a -/// shell will be spawned into it, so the history is marked off from what -/// that shell prints and the pane waits for it like any new terminal. -/// Registration and tag/cwd policy stay with the core; raw VT replay and -/// viewport restoration belong here. -pub fn restore(p: *Pardes, src: dump.Pane, live: bool) !*Pane { - const terminal = src.terminal.?; - if (comptime !enabled) { - const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); - errdefer p.gpa.destroy(pane); - if (terminal.stream.len > 0) - pane.ovl = .{ .row = 0, .rows = 1, .text = try p.gpa.dupe(u8, terminal.stream) }; - return pane; - } - // An older dump's raw output tail cannot come back live: cut off mid - // redraw, or written at sizes the pane no longer has, it replays as - // garbage. Its rendered text can. - const legacy_text = live and !terminal.stream_is_screen and terminal.stream.len > 0; - const bytes = if (legacy_text) - try std.mem.replaceOwned(u8, p.scratch.allocator(), terminal.stream, "\n", "\r\n") - else if (terminal.stream_b64.len > 0) - try dump.decodeBytes(p.scratch.allocator(), terminal.stream_b64) - else - &.{}; - const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); - if (live) { - if (bytes.len > 0) { - ingest(pane, bytes); - ingest(pane, restored_banner); - } - followOutput(pane); - // A view left scrolled back stays on what it was showing: the - // banner's line breaks scrolled a full screen by that many more. - if (src.scroll > 0) scrollGrid(pane, -@as(i32, @intCast(src.scroll + comptime std.mem.count(u8, restored_banner, "\n")))); - armShellSpawn(pane); - } else if (bytes.len > 0) { - ingest(pane, bytes); - followOutput(pane); - if (src.scroll > 0) - scrollGrid(pane, -@as(i32, @intCast(src.scroll))); - } - return pane; -} - -/// Feed the emulator and retain the bounded suffix a dump can replay. Live -/// output and restoration share this byte path, then apply different views. -fn ingest(pane: *Pane, bytes: []const u8) void { - const state = pane.terminal.?; - const replay = &state.replay; - if (bytes.len >= replay.bytes.len) { - const kept = bytes[bytes.len - replay.bytes.len ..]; - @memcpy(&replay.bytes, kept); - replay.head = 0; - replay.len = replay.bytes.len; - } else { - const overflow = bytes.len -| (replay.bytes.len - replay.len); - replay.head = (replay.head + overflow) % replay.bytes.len; - replay.len -= overflow; - const tail = (replay.head + replay.len) % replay.bytes.len; - const first = @min(bytes.len, replay.bytes.len - tail); - @memcpy(replay.bytes[tail..][0..first], bytes[0..first]); - @memcpy(replay.bytes[0 .. bytes.len - first], bytes[first..]); - replay.len += bytes.len; - } - state.stream.nextSlice(bytes); -} - -/// Return the replay ring in chronological order. Wrapped records are copied -/// into `allocator`; contiguous records remain a borrowed slice of the pane. -fn replayBytes(pane: *const Pane, allocator: std.mem.Allocator) ![]const u8 { - const state = pane.terminal orelse return &.{}; - const replay = &state.replay; - if (replay.len == 0) return &.{}; - if (replay.head + replay.len <= replay.bytes.len) - return replay.bytes[replay.head..][0..replay.len]; - const out = try allocator.alloc(u8, replay.len); - const first = replay.bytes.len - replay.head; - @memcpy(out[0..first], replay.bytes[replay.head..]); - @memcpy(out[first..], replay.bytes[0 .. replay.len - first]); - return out; -} - -test "replay ownership is terminal-only and construction rolls back on allocation failure" { - const Case = struct { - fn run(gpa: std.mem.Allocator, terminal: bool) !void { - const pane = if (terminal) try create(gpa, 40, 12) else try createDoc(gpa, 40, 12); - defer gpa.destroy(pane); - defer deinitEmulator(pane, gpa); - try std.testing.expectEqual(terminal and enabled, pane.terminal != null); - } - }; - try std.testing.expect(@sizeOf(Pane) < 128 * 1024); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{false}); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{true}); -} - -test "document construction allocates only the pane and has inert terminal defaults" { - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 }); - const allocator = failing.allocator(); - const pane = try createDoc(allocator, 40, 12); - defer allocator.destroy(pane); - defer deinitEmulator(pane, allocator); - try std.testing.expect(pane.terminal == null); - try std.testing.expectEqual(@as(usize, 1), failing.alloc_index); - try std.testing.expectEqual(@as(usize, 0), failing.resize_index); - try std.testing.expect(!failing.has_induced_failure); - try std.testing.expectEqual(@as(usize, @sizeOf(Pane)), failing.allocated_bytes); - try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); - try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); - try std.testing.expect(!bracketedPaste(pane)); - try std.testing.expect(!reportsMouse(pane)); - try std.testing.expect(!mouseFormatSgr(pane)); - try std.testing.expect(!promptInputReady(pane)); - scrollGrid(pane, 100); - followOutput(pane); - resizeGrid(pane, allocator, 80, 24); - try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); - try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); - try std.testing.expectEqualStrings("", try screenTextAlloc(pane, allocator)); - try std.testing.expectEqualStrings("", try replayBytes(pane, allocator)); - try std.testing.expect(!failing.has_induced_failure); -} - -test "terminal state keeps parser fragments and sends emulator replies through its owner" { - if (comptime !enabled) return error.SkipZigTest; - const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - const state = pane.terminal.?; - try std.testing.expect(state.stream.handler.inner.terminal == &state.vt); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[" } }); - while (p.nextEffect()) |effect| { - if (effect == .write) return error.PrematureTerminalReply; - } - p.update(.{ .output = .{ .pane = 0, .bytes = "6n" } }); - var replies: usize = 0; - while (p.nextEffect()) |effect| { - if (effect != .write) continue; - try std.testing.expectEqual(@as(u8, 0), effect.write.pane); - try std.testing.expectEqualStrings("\x1b[1;1R", effect.write.bytes.slice()); - replies += 1; - } - try std.testing.expectEqual(@as(usize, 1), replies); - try std.testing.expectEqual(@as(u16, 0), state.reply_len); - try std.testing.expectEqualStrings("\x1b[6n", try replayBytes(pane, std.testing.allocator)); -} - -test "replay keeps a bounded chronological suffix across large writes and wrapping" { - if (comptime !enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const pane = try create(gpa, 40, 12); - defer gpa.destroy(pane); - defer deinitEmulator(pane, gpa); - try std.testing.expectEqualStrings("", try replayBytes(pane, gpa)); - ingest(pane, "hello"); - const small = try replayBytes(pane, gpa); - try std.testing.expectEqualStrings("hello", small); - try std.testing.expectEqual(@intFromPtr(&pane.terminal.?.replay.bytes), @intFromPtr(small.ptr)); - - const capacity = pane.terminal.?.replay.bytes.len; - const input = try gpa.alloc(u8, capacity + 7); - defer gpa.free(input); - @memset(input, 0); - const ending = "\x1b[31mred\x1b[0m\r\n"; - @memcpy(input[input.len - ending.len ..], ending); - ingest(pane, input); - try std.testing.expectEqualSlices(u8, input[7..], try replayBytes(pane, gpa)); - ingest(pane, "next\r\n"); - const wrapped = try replayBytes(pane, gpa); - defer gpa.free(wrapped); - try std.testing.expectEqual(capacity, wrapped.len); - try std.testing.expectEqualSlices(u8, input[7 + "next\r\n".len ..], wrapped[0 .. capacity - "next\r\n".len]); - try std.testing.expectEqualStrings("next\r\n", wrapped[capacity - "next\r\n".len ..]); -} - -test "replay restores terminal cells from the retained stream" { - if (comptime !enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - feedOutput(p, pane, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); - const encoded = try dump.encodeBytes(gpa, try replayBytes(pane, gpa)); - defer gpa.free(encoded); - const restored = try restore(p, .{ - .kind = .terminal, - .tag = "", - .body = "", - .cols = pane.cols, - .rows = pane.rows, - .terminal = .{ .stream_b64 = encoded }, - }, false); - defer gpa.destroy(restored); - defer deinitEmulator(restored, gpa); - const before = try screenTextAlloc(pane, gpa); - defer gpa.free(before); - const after = try screenTextAlloc(restored, gpa); - defer gpa.free(after); - try std.testing.expectEqualStrings(before, after); - try std.testing.expectEqualSlices(u8, try replayBytes(pane, gpa), try replayBytes(restored, gpa)); -} - -test "a restored command pane comes back finished, its command not run again" { - if (comptime !enabled or pardes.isolated) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const cmd = p.freeSlot().?; - _ = try p.newCommand(cmd, "/tmp", "make test"); - feedOutput(p, p.panes[cmd].?, "ok\r\n"); - p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 2 } }); - try dump.dumpState(p); - const restored = try dump.initFromDump(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }, p.dump_out.?); - defer restored.deinit(); - var spawns: usize = 0; - while (restored.nextEffect()) |effect| switch (effect) { - .spawn => spawns += 1, - else => {}, - }; - try std.testing.expectEqual(@as(usize, 1), spawns); // the shell, not the command - const again = for (restored.panes) |slot| { - if (slot) |pane| if (pane.command != null) break pane; - } else return error.CommandPaneLost; - try std.testing.expectEqualStrings("make test", again.command.?); - try std.testing.expect(again.command_done); - try std.testing.expectEqual(@as(?u8, 2), again.command_status); - const text = try screenTextAlloc(again, gpa); - defer gpa.free(text); - try std.testing.expect(std.mem.indexOf(u8, text, "ok") != null); -} - -test "a restored terminal keeps its history above a marker and gets a shell where it was" { - if (comptime !enabled or pardes.isolated) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - feedOutput(p, pane, "old output\r\n$ ls\r\n"); - try pane.setOwnedCwd("/tmp"); - pane.shell = try gpa.dupe(u8, "bash"); // `Tty bash`: it comes back as bash - try dump.dumpState(p); - const restored = try dump.initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?); - defer restored.deinit(); - var spawned = false; - while (restored.nextEffect()) |effect| switch (effect) { - .spawn => |sp| spawned = sp.pane == 0 and std.mem.eql(u8, sp.cwd.slice(), "/tmp"), - else => {}, - }; - try std.testing.expect(spawned); - const again = restored.panes[0].?; - try std.testing.expectEqualStrings("bash", again.shell.?); - try std.testing.expect(again.command == null); - try std.testing.expectEqual(.spawn, again.pending_command.wait); - const text = try screenTextAlloc(again, gpa); - defer gpa.free(text); - const old_at = std.mem.indexOf(u8, text, "old output") orelse return error.HistoryLost; - const mark_at = std.mem.indexOf(u8, text, "restored history") orelse return error.NoMarker; - try std.testing.expect(old_at < mark_at); -} - -test "an older dump comes back live from its rendered text, not its raw output tail" { - if (comptime !enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); - defer p.deinit(); - // A tail cut mid-redraw: relative moves from a cursor it never set. - const tail = try dump.encodeBytes(gpa, "\x1b[7A\x1b[2Kgarbage\x1b[3B\x1b[9Gmore"); - defer gpa.free(tail); - const restored = try restore(p, .{ - .kind = .terminal, - .tag = "", - .body = "", - .cols = 40, - .rows = 12, - .terminal = .{ .stream = "$ ls\na.txt b.txt\n$ ", .stream_b64 = tail }, - }, true); - defer gpa.destroy(restored); - defer deinitEmulator(restored, gpa); - defer deinitPendingCommand(restored); - const text = try screenTextAlloc(restored, gpa); - defer gpa.free(text); - try std.testing.expect(std.mem.indexOf(u8, text, "$ ls\na.txt b.txt") != null); - try std.testing.expect(std.mem.indexOf(u8, text, "garbage") == null); -} - -/// Record and parse one live pty read, invalidate its motion surface, and -/// follow it only when the body (possibly parked under a tag edit) is raw. -pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void { - // There are no pty reads at all without an emulator to parse them into. - if (comptime !enabled) return; - if (pane.terminal == null) return; - const has_positions = pane.ovl != null or pane.body.cur_pinned or pane.body.vsel.active or - pane.body.msel.active or pane.body.nsel > 0 or pane.body.last_edit != null or pane.look_at != null or - pane.body.ed_undo_len > 0 or pane.body.ed_redo_len > 0 or pointerRowCount(pane) > 0; - // Sticky bottom, as every other terminal does it: output drags the - // viewport down only when the viewport was already on the last row, so - // a reader scrolled back into the scrollback stays where they scrolled. - const at_bottom = atBottom(pane); - if (has_positions) ingestWithPositions(pane, bytes) else ingest(pane, bytes); - p.shell_rows.markStale(pane); - if (pane.body.mode == .tty and at_bottom) followOutput(pane); -} - -const RowPin = struct { pin: ?*ghostty_vt.Pin = null, offset: i32 = 0 }; -const PositionPin = struct { - target: *i32, - row: RowPin, - overlay: ?*EditBuffer, - edit_row: ?i32 = null, -}; - -fn trackRow(pages: *ghostty_vt.PageList, row: i32, failed: *bool) RowPin { - if (row < 0) return .{ .offset = row }; - const bounded: usize = @min(@as(usize, @intCast(row)), pages.total_rows - 1); - var left = pages.total_rows - 1 - bounded; - var node = pages.pages.last.?; - while (left >= node.rows()) { - left -= node.rows(); - node = node.prev.?; - } - const pin = pages.trackPin(.{ .node = node, .y = @intCast(node.rows() - 1 - left) }) catch { - failed.* = true; - return .{}; - }; - return .{ .pin = pin, .offset = row - @as(i32, @intCast(bounded)) }; -} - -fn pinnedRow(pages: ?*ghostty_vt.PageList, row: RowPin) i32 { - const pin = row.pin orelse return row.offset; - const alive = pages orelse return 0; - if (pin.garbage) return 0; - var after: usize = 0; - var node = alive.pages.last; - while (node) |item| : (node = item.prev) { - if (item == pin.node) - return @as(i32, @intCast(alive.total_rows - after - item.rows() + pin.y)) +| row.offset; - after += item.rows(); - } - return 0; -} - -fn trackPosition(pages: *ghostty_vt.PageList, target: *i32, overlay: ?*EditBuffer, failed: *bool) PositionPin { - var grid = target.*; - if (overlay) |edit| { - const lines: i32 = @intCast(modal.lineCount(edit.text)); - if (grid >= edit.row and grid < edit.row +| lines) - return .{ .target = target, .row = .{}, .overlay = edit, .edit_row = grid - edit.row }; - if (grid > edit.row) grid = grid -| lines +| edit.rows; - } - return .{ .target = target, .row = trackRow(pages, grid, failed), .overlay = overlay }; -} - -fn pointerRowCount(pane: *const Pane) usize { - var count: usize = 0; - for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { - count += rows.len; - }; - return count; -} - -fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { - const screens = &pane.terminal.?.vt.screens; - const key = screens.active_key; - const generation = screens.generation(key); - const pages = &screens.active.pages; - const Group = struct { overlay: ?*EditBuffer, cursor: *i32, selection: *panes.Text.CharSel }; - var groups: [history_max * 2 + 1]Group = undefined; - groups[0] = .{ - .overlay = if (pane.ovl) |*overlay| overlay else null, - .cursor = &pane.body.cur_row, - .selection = &pane.body.vsel, - }; - var ngroups: usize = 1; - for ([_][]Snapshot{ pane.body.ed_undo[0..pane.body.ed_undo_len], pane.body.ed_redo[0..pane.body.ed_redo_len] }) |history| { - for (history) |*snapshot| { - groups[ngroups] = .{ - .overlay = if (snapshot.ovl) |*overlay| overlay else null, - .cursor = &snapshot.cur_row, - .selection = &snapshot.vsel, - }; - ngroups += 1; - } - } - const Span = struct { overlay: *EditBuffer, start: RowPin, end: RowPin }; - var spans: [groups.len]Span = undefined; - var nspans: usize = 0; - var positions: [groups.len * 2 + panes.Text.max_selections * 2 + 4]PositionPin = undefined; - var npositions: usize = 0; - var failed = false; - for (groups[0..ngroups]) |group| { - if (group.overlay) |overlay| { - spans[nspans] = .{ - .overlay = overlay, - .start = trackRow(pages, overlay.row, &failed), - .end = trackRow(pages, overlay.row +| (overlay.rows - 1), &failed), - }; - nspans += 1; - } - positions[npositions] = trackPosition(pages, group.cursor, group.overlay, &failed); - npositions += 1; - if (group.selection.active) { - positions[npositions] = trackPosition(pages, &group.selection.row, group.overlay, &failed); - npositions += 1; - } - } - const overlay = groups[0].overlay; - var extra: [panes.Text.max_selections * 2 + 4]*i32 = undefined; - var nextra: usize = 0; - if (pane.body.msel.active) { - extra[nextra] = &pane.body.msel.r0; - extra[nextra + 1] = &pane.body.msel.r1; - nextra += 2; - } - for (pane.body.sels[0..pane.body.nsel]) |*selection| { - extra[nextra] = &selection.row; - extra[nextra + 1] = &selection.arow; - nextra += 2; - } - if (pane.body.last_edit) |*at| { - extra[nextra] = &at.row; - nextra += 1; - } - if (pane.look_at) |*at| { - extra[nextra] = &at.row; - nextra += 1; - } - for (extra[0..nextra]) |target| { - positions[npositions] = trackPosition(pages, target, overlay, &failed); - npositions += 1; - } - const pointer_positions = pane.gpa.alloc(PositionPin, pointerRowCount(pane)) catch null; - defer if (pointer_positions) |pins| pane.gpa.free(pins); - if (pointer_positions) |pins| { - var index: usize = 0; - for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { - for (rows) |*row| { - pins[index] = trackPosition(pages, &row.row, if (row.raw_terminal) null else overlay, &failed); - index += 1; - } - }; - } else failed = true; - ingest(pane, bytes); - // RIS can destroy the alternate screen and every pin it owned. - const alive = if (screens.generation(key) == generation) pages else null; - var moved = false; - var pointer_rows_lost = alive == null or pointer_positions == null; - if (pointer_positions) |pins| for (pins) |position| { - if (alive != null) if (position.row.pin) |pin| { - if (pin.garbage) pointer_rows_lost = true; - }; - }; - for (spans[0..nspans]) |span| { - const start = pinnedRow(alive, span.start); - const rows = @max(1, pinnedRow(alive, span.end) -| start +| 1); - moved = moved or start != span.overlay.row or rows != span.overlay.rows; - span.overlay.row = start; - span.overlay.rows = rows; - if (alive) |owner| { - if (span.start.pin) |pin| owner.untrackPin(pin); - if (span.end.pin) |pin| owner.untrackPin(pin); - } - } - for ([_][]PositionPin{ positions[0..npositions], pointer_positions orelse &.{} }) |batch| for (batch) |position| { - var row = pinnedRow(alive, position.row); - if (position.overlay) |edit| { - if (position.edit_row) |relative| { - row = edit.row +| relative; - } else if (row > edit.row) { - row = if (row < edit.row +| edit.rows) - edit.row - else - row -| edit.rows +| @as(i32, @intCast(modal.lineCount(edit.text))); - } - } - moved = moved or row != position.target.*; - position.target.* = row; - if (alive) |owner| if (position.row.pin) |pin| owner.untrackPin(pin); - }; - if (pointer_rows_lost) for (0..pane.sel.len) |button| { - pane.clearPointerSelection(button); - pane.sel[button].state = .none; - }; - if (moved) pane.nsel_snap = 0; // Saved regex-preview offsets name the old flat text. - if (failed) { - const message = "terminal edit position reset: out of memory"; - @memcpy(pane.msg[0..message.len], message); - pane.msg_len = message.len; - } -} - -test "raw terminal output needs no position tracking allocations" { - if (comptime !enabled) return error.SkipZigTest; - var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); - const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); - defer p.deinit(); - const pane = p.panes[0].?; - pane.body.mode = .tty; - feedOutput(p, pane, "warm"); - const allocations = failing.alloc_index; - failing.fail_index = allocations; - const pins = pane.terminal.?.vt.screens.active.pages.countTrackedPins(); - feedOutput(p, pane, " output"); - try std.testing.expectEqual(allocations, failing.alloc_index); - try std.testing.expect(!failing.has_induced_failure); - try std.testing.expectEqual(pins, pane.terminal.?.vt.screens.active.pages.countTrackedPins()); -} - -/// A full-screen program has the emulator on its alternate screen. -pub fn onAlternateScreen(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - return state.vt.screens.active_key == .alternate; -} - -/// Whether a new terminal's greeting may be typed now: only at the shell's -/// first prompt (pardes's own marks: no command started; a prompt drawn -/// again for a resize is the same first prompt), with nothing -/// typed at it and no program on the alternate screen. Any later moment is `.never`, for good: something has run or -/// been typed first, and an `ls` then would go into it. A shell pardes -/// cannot mark has no first prompt to find, and is never greeted. -pub fn greeting(pane: *const Pane) enum { wait, now, never } { - if (comptime !enabled) return .never; - if (pane.fs.unmarked) return .never; - // Text typed into the edit buffer that stands in for the prompt row. - if (pane.ovl) |o| if (o.text.len > 0) return .never; - const state = pane.terminal orelse return .wait; - const marks = &state.stream.handler; - // (Not `declined`: bash's first prompt comes after a D of its own.) - if (marks.started > 0) return .never; - // At a prompt's input (ghostty's semantic marks, pardes's or the - // shell's own), before any command pardes's marks saw run. - if (!promptInputReady(pane)) return .wait; - return if (promptInputEmpty(pane)) .now else .never; -} - -pub fn promptInputReady(pane: *const Pane) bool { - if (comptime !enabled) return false; - const state = pane.terminal orelse return false; - return state.vt.screens.active_key != .alternate and - state.vt.screens.active.cursor.semantic_content == .input; -} - -pub const CommandOutput = struct { - /// Owned by the caller. - text: [:0]const u8, - /// Whether `text` starts where the command did. It does not when that - /// start is not there to read: cut off by `max_rows`, scrolled out of - /// the history (ghostty moved the pin to the oldest row it kept and - /// flagged it `garbage`), erased under it (`MarkedHandler.lost`), or - /// never pinned (a C or D that came on the alternate screen). - whole: bool, -}; - -/// What the newest finished command printed: the screen text between its -/// C and D marks, read from at most `max_rows` rows above its end, so a -/// command that printed the whole history costs no more than its tail. -/// The shell exited in the middle of a command (its `exit 3`): no end mark -/// will come, so the command's output ends where the cursor is. -pub fn endOutputHere(pane: *Pane) void { - if (comptime !enabled) return; - const state = pane.terminal orelse return; - const marks = &state.stream.handler; - if (marks.phase == .running and marks.out_end == null) marks.pinCursor(&marks.out_end, true); -} - -pub fn commandOutput(pane: *Pane, gpa: std.mem.Allocator, max_rows: usize) !CommandOutput { - // Unless there is text to read, whether the nothing it printed is the - // whole of it. - const whole = if (comptime enabled) printed: { - const state = pane.terminal orelse break :printed true; - const marks = &state.stream.handler; - const start = marks.out_start orelse break :printed false; - const end = marks.out_end orelse break :printed false; - const screen = state.vt.screens.get(.primary) orelse break :printed false; - if (end.garbage) break :printed false; - var whole = !marks.lost and !start.garbage; - // D is where the next prompt begins: the output ends a cell before. - const last = end.leftWrap(1) orelse break :printed whole; - if (start.eql(end.*) or last.before(start.*)) break :printed whole; - var from = start.*; - if (last.up(max_rows)) |floor| if (from.before(floor)) { - from = floor; - from.x = 0; - whole = false; - }; - return .{ - .text = try screen.selectionString(gpa, .{ .sel = ghostty_vt.Selection.init(from, last, false) }), - .whole = whole, - }; - } else true; - return .{ .text = try gpa.dupeZ(u8, ""), .whole = whole }; -} - -/// At a prompt with nothing typed on its line: no input left of the -/// cursor and none under it (text typed and then Ctrl-A'd starts at the -/// cursor). Nothing further right counts: that is where fish draws a -/// right prompt, and fish suggests nothing on an empty line. -pub fn promptInputEmpty(pane: *const Pane) bool { - if (comptime !enabled) return false; - if (!promptInputReady(pane)) return false; - const cursor = &pane.terminal.?.vt.screens.active.cursor; - const row = cursor.page_pin.cells(.all); - for (row[0..@min(cursor.x + 1, row.len)]) |cell| - if (cell.semantic_content == .input and !cell.isEmpty()) return false; - return true; -} - -/// Encode one key for the program that owns a raw terminal and queue its pty -/// write, respecting the application's keyboard protocol and terminal modes. -pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { - if (comptime enabled) { - const pane = p.panes[id] orelse return; - const state = pane.terminal orelse return; - const input = ghostty_vt.input; - const function_keys = comptime keys: { - var keys: [Key.f25 - Key.f1 + 1]input.Key = undefined; - for (&keys, 1..) |*k, n| k.* = @field(input.Key, std.fmt.comptimePrint("f{d}", .{n})); - break :keys keys; - }; - const physical: input.Key = switch (key.cp) { - Key.enter => .enter, - Key.backspace => .backspace, - Key.tab => .tab, - Key.escape => .escape, - Key.up => .arrow_up, - Key.down => .arrow_down, - Key.left => .arrow_left, - Key.right => .arrow_right, - Key.home => .home, - Key.end => .end, - Key.page_up => .page_up, - Key.page_down => .page_down, - Key.delete => .delete, - Key.insert => .insert, - Key.print_screen => .print_screen, - Key.scroll_lock => .scroll_lock, - Key.pause => .pause, - Key.menu => .context_menu, - Key.f1...Key.f25 => function_keys[key.cp - Key.f1], - else => if (key.cp < 128) input.Key.fromASCII(@intCast(key.cp)) orelse .unidentified else .unidentified, - }; - var utf8: [4]u8 = undefined; - const text_cp = if (key.shift and key.cp >= 'a' and key.cp <= 'z') key.cp - 'a' + 'A' else key.cp; - // A key with no text of its own types its code point only when that - // is a character: the kitty keyboard protocol numbers function and - // modifier keys in the private use area (F3 is U+E016), and a shell - // was typed those as junk. - const text = if (key.text.len > 0) key.text else if (key.cp >= 32 and key.cp < Key.up and key.cp != Key.backspace and !(key.cp >= 0xE000 and key.cp <= 0xF8FF)) - utf8[0 .. std.unicode.utf8Encode(text_cp, &utf8) catch return] - else - ""; - var buffer: [256]u8 = undefined; - var writer = std.Io.Writer.fixed(&buffer); - input.encodeKey(&writer, .{ - .key = physical, - .mods = .{ .ctrl = key.ctrl, .alt = key.alt, .shift = key.shift }, - .consumed_mods = .{ .shift = key.text.len > 0 and key.shift }, - .utf8 = text, - .unshifted_codepoint = if (key.cp >= 'A' and key.cp <= 'Z') key.cp - 'A' + 'a' else if (key.cp < Key.up) key.cp else 0, - }, options: { - var opts = input.KeyEncodeOptions.fromTerminal(&state.vt); - // fromTerminal cannot know this one and says so, defaulting to - // "option is not alt" — right for an app that lets macOS do the - // unicode translation and hands the encoder the composed text. - // Every pardes shell resolves the modifier itself and hands the - // core the BASE key with the alt bit and no text at all (see - // PardesView.keyDown, and app.mjs doing the same with the same - // two bits), so by the time this runs alt already means alt. - // Left at the default, a macOS build drops the ESC prefix on - // the floor and forwards Alt-n to the child as a bare `n`. - opts.macos_option_as_alt = .true; - break :options opts; - }) catch return; - if (writer.end > 0) p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(writer.buffered()) } }); - return; - } - var control: [1]u8 = undefined; - const bytes: ?[]const u8 = blk: { - if (key.ctrl) { - if (key.cp >= 'a' and key.cp <= 'z') { - control[0] = @intCast(key.cp - 0x60); - break :blk control[0..1]; - } - // ASCII @, A-Z, [, \, ], ^ and _ are one contiguous control range. - if (key.cp >= '@' and key.cp <= '_') { - control[0] = @intCast(key.cp - 0x40); - break :blk control[0..1]; - } - } - if (key.text.len > 0) break :blk key.text; - break :blk switch (key.cp) { - Key.enter => "\r", - Key.backspace => "\x7f", - Key.tab => "\t", - Key.escape => "\x1b", - Key.up => "\x1b[A", - Key.down => "\x1b[B", - Key.right => "\x1b[C", - Key.left => "\x1b[D", - Key.delete => "\x1b[3~", - else => null, - }; - }; - if (bytes) |encoded| - p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(encoded) } }); -} - -pub fn enterTty(p: *Pardes, id: usize) void { - const pane = p.panes[id] orelse return; - const selected = pane.rawPointerText(pane.sel[@intFromEnum(config.select_button)]) != null; - if (comptime enabled) if (!selected and pane.terminal != null and pane.body.cur_pinned and pane.terminal.?.vt.cursorIsAtPrompt()) handoff: { - const screen = pane.terminal.?.vt.screens.active; - const goff: i32 = @intCast(screen.pages.scrollbar().offset); - const vp_row = pane.gridRow(pane.body.cur_row) - goff; - if (vp_row < 0) break :handoff; - - var grid_col: i32 = @max(0, pane.body.cur_col); - if (screen.pages.pin(.{ .viewport = .{ .x = 0, .y = @intCast(vp_row) } })) |row_pin| { - if (row_pin.rowAndCell().row.semantic_prompt != .none) switch (promptCut(row_pin)) { - .cut => |cols| grid_col += @intCast(cols), - .keep, .blank => {}, - }; - } - const click_pin = screen.pages.pin(.{ - .viewport = .{ .x = @intCast(grid_col), .y = @intCast(vp_row) }, - }) orelse break :handoff; - const cursor_pin = screen.cursor.page_pin.*; - var prompts = cursor_pin.promptIterator(.left_up, null); - const prompt_pin = prompts.next() orelse break :handoff; - if (click_pin.before(prompt_pin)) break :handoff; - const moves = screen.promptClickMove(click_pin); - for (0..moves.left) |_| p.emitWrite(id, "\x1b[D"); - for (0..moves.right) |_| p.emitWrite(id, "\x1b[C"); - }; - - pane.body.mode = .tty; - followOutput(pane); // entering raw mode is a request for the live shell - pane.body.msel.active = false; - pane.body.vsel.active = false; - pane.body.nsel = 0; - // The raw renderer follows the live cursor. A captured mouse selection - // keeps its modal endpoint for the next return to editor mode. - pane.body.cur_pinned = selected; - pane.body.select = false; - pane.body.restore_cursor = false; - pane.body.sticky_col = -1; - pane.body.normal.clear(); -} - -// Returned slices remain valid until the next cache rebuild or reset. -pub const RowsCache = struct { - /// whose grid this describes; null = the slot is free - pane: ?*const Pane = null, - /// the rows joined by '\n' — `flatSurface` hands this back verbatim - /// instead of rebuilding the join on every keystroke - text: []const u8 = &.{}, - /// slices INTO `text`, absolute grid rows from 0 - rows: [][]const u8 = &.{}, - /// `text` is a prefix of this: blanking a prompt row shortens the join, - /// and the slack is not worth a second allocation to reclaim - text_alloc: []u8 = &.{}, - stale: bool = false, - - pub fn reset(c: *RowsCache, gpa: std.mem.Allocator) void { - if (c.text_alloc.len > 0) gpa.free(c.text_alloc); - if (c.rows.len > 0) gpa.free(c.rows); - c.* = .{}; - } - - /// Free a stale entry. Called at the top of `update`, and nowhere else. - pub fn sweep(c: *RowsCache, gpa: std.mem.Allocator) void { - if (c.stale) c.reset(gpa); - } - - /// `pane`'s grid moved: the entry no longer describes it. - pub fn markStale(c: *RowsCache, pane: *const Pane) void { - if (c.pane == pane) c.stale = true; - } - - pub fn dropPane(c: *RowsCache, pane: *const Pane) void { - if (c.pane != pane) return; - c.pane = null; - c.stale = true; - } -}; - -const Rows = struct { - text_alloc: []u8, - text: []const u8, - rows: [][]const u8, -}; - -const empty_grid = [1][]const u8{""}; - -/// What LEAVING raw tty mode does to one prompt row, decided from its cells -/// alone. See config.tty_blank for why any of this happens. -const PromptCut = union(enum) { - /// show the row exactly as ghostty dumped it - keep, - /// show nothing at all - blank, - /// drop this many leading COLUMNS — the prompt — and keep the rest, which - /// is what was typed at it - cut: usize, -}; - -fn promptCut(pin: ghostty_vt.Pin) PromptCut { - if (config.tty_blank == .prompt_and_input) return .blank; - const cells = pin.cells(.all); - var cols: usize = 0; - while (cols < cells.len and cells[cols].semantic_content == .prompt) cols += 1; - // Flagged, but with no prompt cells at the FRONT: a right-side prompt, or - // a repaint that has moved on. Nothing here is the prompt, so hide nothing. - if (cols == 0) return .keep; - // ...and all prompt, nothing typed yet: the row is chrome end to end. - if (cols >= cells.len) return .blank; - return .{ .cut = cols }; -} - -pub fn promptPrefixBytes(pane: *Pane, row: i32, raw: []const u8) usize { - if (comptime !enabled) return 0; - if (row < 0) return 0; - const state = pane.terminal orelse return 0; - const pin = state.vt.screens.active.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } }) orelse return 0; - if (pin.rowAndCell().row.semantic_prompt == .none) return 0; - return switch (promptCut(pin)) { - .keep => 0, - .blank => raw.len, - .cut => |cols| @min(raw.len, File.rawAtDisplay(raw, cols)), - }; -} - -fn promptRow(pin: ghostty_vt.Pin, raw: []const u8) []const u8 { - const cols = switch (promptCut(pin)) { - .keep => return raw, - .blank => return "", - .cut => |n| n, - }; - const cells = pin.cells(.all); - var at: usize = 0; - var col: usize = 0; - while (col < cols and at < raw.len) { - const cell = &cells[col]; - at = @min(raw.len, at + dumpedBytes(pin, cell)); - // the tail cell of a wide glyph spells nothing of its own - col += if (cell.wide == .wide) @as(usize, 2) else 1; - } - return std.mem.trimEnd(u8, raw[at..], " \t"); -} - -fn dumpedBytes(pin: ghostty_vt.Pin, cell: *const ghostty_vt.Cell) usize { - switch (cell.wide) { - .spacer_head, .spacer_tail => return 0, - .narrow, .wide => {}, - } - var n: usize = switch (cell.content_tag) { - .codepoint, .codepoint_grapheme => std.unicode.utf8CodepointSequenceLength( - cell.codepoint(), - ) catch 1, - // A cell carrying only a colour still spells one blank in the dump. - else => 1, - }; - if (cell.content_tag == .codepoint_grapheme) { - if (pin.grapheme(cell)) |extra| for (extra) |cp| { - n += std.unicode.utf8CodepointSequenceLength(cp) catch 1; - }; - } - return n; -} - -pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 { - if (comptime !enabled) return &empty_grid; - if (pane.terminal == null) return &empty_grid; - const c = &p.shell_rows; - if (!c.stale and c.pane == pane) return c.rows; - if (c.pane != null) { - c.stale = true; - return (try buildRows(p.scratch.allocator(), p, pane)).rows; - } - const built = try buildRows(p.gpa, p, pane); - c.* = .{ - .pane = pane, - .text = built.text, - .rows = built.rows, - .text_alloc = built.text_alloc, - }; - return c.rows; -} - -/// The full modal motion surface: shell history with the live edit overlay -/// spliced into the rows it covers. -pub fn cursorLines(p: *Pardes, pane: *Pane) ![]const []const u8 { - const rows = try shellRows(p, pane); - if (pane.ovl == null) return rows; - var last = rows.len; - if (pane.ovl) |overlay| - last = @max(last, @as(usize, @intCast(@max(0, overlay.row + overlay.rows)))); - var count = last; - if (pane.ovl) |overlay| { - if (overlay.row >= 0 and @as(usize, @intCast(overlay.row)) < last) - count = count - @min( - @as(usize, @intCast(overlay.rows)), - last - @as(usize, @intCast(overlay.row)), - ) + @max(1, modal.lineCount(overlay.text)); - } - const lines = try p.scratch.allocator().alloc([]const u8, count); - var n: usize = 0; - var grid_row: usize = 0; - while (grid_row < last) : (grid_row += 1) { - if (pane.ovl) |overlay| if (overlay.row >= 0 and grid_row == @as(usize, @intCast(overlay.row))) { - var overlay_lines = std.mem.splitScalar(u8, overlay.text, '\n'); - while (overlay_lines.next()) |line| : (n += 1) lines[n] = line; - grid_row += @intCast(overlay.rows - 1); - continue; - }; - lines[n] = if (grid_row < rows.len) rows[grid_row] else ""; - n += 1; - } - return lines[0..n]; -} - -/// Flatten `cursorLines` without rebuilding the common cached/no-overlay -/// case. Scratch-owned when a join is required. -pub fn flatSurface(p: *Pardes, pane: *Pane, lines: []const []const u8) ![]const u8 { - const cache = &p.shell_rows; - if (!cache.stale and cache.pane == pane and - lines.ptr == cache.rows.ptr and lines.len == cache.rows.len) return cache.text; - var total: usize = if (lines.len > 0) lines.len - 1 else 0; - for (lines) |line| total += line.len; - const text = try p.scratch.allocator().alloc(u8, total); - var at: usize = 0; - for (lines, 0..) |line, i| { - if (i > 0) { - text[at] = '\n'; - at += 1; - } - @memcpy(text[at..][0..line.len], line); - at += line.len; - } - return text; -} - -/// Materialize or extend the terminal edit overlay with one exact allocation. -/// Row slices are scratch-owned/borrowed; only the joined text is installed. -pub fn editText(p: *Pardes, pane: *Pane, lo: i32, hi: i32, col: i32) ?EditText { - const want_lo = @max(0, @min(lo, hi)); - const want_hi = @max(want_lo, @max(lo, hi)); - const fresh = pane.ovl == null; - const old: EditBuffer = pane.ovl orelse .{ .row = want_lo, .rows = 1, .text = &.{} }; - const lines: i32 = if (fresh) 1 else @intCast(modal.lineCount(old.text)); - const up = old.row - want_lo; - const down = want_hi - (old.row + lines - 1); - const extending = fresh or up > 0 or down > 0; - var row0 = old.row; - var covered = old.rows; - var text = old.text; - var owned = false; - if (extending) { - const rows = shellRows(p, pane) catch return null; - row0 = old.row - @max(0, up); - covered = old.rows + @max(0, up) + @max(0, down); - const up_len: usize = @intCast(@max(0, up)); - const down_len: usize = @intCast(@max(0, down)); - const parts = p.scratch.allocator().alloc([]const u8, up_len + 1 + down_len) catch return null; - for (parts[0..up_len], 0..) |*part, i| { - const src = @as(usize, @intCast(row0)) + i; - part.* = if (src < rows.len) rows[src] else ""; - } - const middle: usize = @intCast(old.row); - parts[up_len] = if (fresh) - (if (middle < rows.len) rows[middle] else "") - else - old.text; - for (parts[up_len + 1 ..], 0..) |*part, i| { - const src = @as(usize, @intCast(old.row + old.rows)) + i; - part.* = if (src < rows.len) rows[src] else ""; - } - text = std.mem.join(p.gpa, "\n", parts) catch return null; - owned = true; - } - - const row: usize = @intCast(@max(0, want_lo - row0)); - const line_len: i32 = @intCast(modal.lineSlice(text, row).len); - if (col > line_len) { - const spaces = p.scratch.allocator().alloc(u8, @intCast(col - line_len)) catch { - if (owned) p.gpa.free(text); - return null; - }; - @memset(spaces, ' '); - const padded = modal.insertAt(p.gpa, text, .{ .row = row, .col = @intCast(line_len) }, spaces) catch { - if (owned) p.gpa.free(text); - return null; - }; - if (owned) p.gpa.free(text); - text = padded; - owned = true; - } - if (owned) { - if (pane.ovl) |overlay| p.gpa.free(overlay.text); - pane.ovl = .{ .row = row0, .rows = covered, .text = text }; - } - return .{ .text = pane.ovl.?.text, .row0 = pane.ovl.?.row }; -} - -/// Consume a rewritten overlay, freeing the terminal edit text it replaces. -pub fn setEditText(p: *Pardes, pane: *Pane, new: []u8) void { - const overlay = if (pane.ovl) |*value| value else return pardes.edit.retireEditText(p, new); - for (0..pane.sel.len) |button| { - pane.clearPointerSelection(button); - pane.sel[button].state = .none; - } - p.gpa.free(overlay.text); - overlay.text = new; -} - -/// The shell's screen and scrollback (the primary screen, even under a -/// full-screen program) as VT that replays to what was shown: styled -/// text, soft-wrapped lines rejoined so they reflow at another width. -fn screenVt(pane: *const Pane, arena: std.mem.Allocator) ![]const u8 { - const screen = pane.terminal.?.vt.screens.get(.primary) orelse return &.{}; - var out: std.Io.Writer.Allocating = .init(arena); - try ghostty_vt.formatter.ScreenFormatter.init(screen, .{ .emit = .vt, .unwrap = true }).format(&out.writer); - return out.written(); -} - -/// Serialize terminal-only state; the core supplies shared pane metadata. -pub fn dumpPane( - pane: *Pane, - arena: std.mem.Allocator, - tag: []const u8, - body: []const u8, - scroll: usize, -) !dump.Pane { - if (!enabled or pane.terminal == null) { - const text = if (pane.ovl) |overlay| overlay.text else ""; - return .{ - .kind = .terminal, - .tag = tag, - .body = body, - .scroll = scroll, - .cols = pane.cols, - .rows = pane.rows, - .vweight = pane.vweight, - .collapsed = pane.collapsed, - .terminal = .{ - .cwd = try arena.dupe(u8, pane.cwdSlice()), - .shell = try arena.dupe(u8, pane.shell orelse ""), - .command = try arena.dupe(u8, pane.command orelse ""), - .status = pane.command_status, - .stream = try arena.dupe(u8, text), - .stream_b64 = &.{}, - .cursor = .{ .col = 0, .row = 0 }, - }, - }; - } - const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(arena, .{ .screen = .{} }); - const extra = if (pane.ovl) |overlay| overlay.text.len else 0; - const stream = try arena.alloc(u8, try std.math.add(usize, full.len, extra)); - var len: usize = 0; - var lines = std.mem.splitAny(u8, full, "\n"); - var prompts = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); - var row: i32 = 0; - var skip: i32 = 0; - while (lines.next()) |raw| : (row += 1) { - // Hidden overlay rows still consume prompt pins to keep them aligned. - const prompt = if (pane.body.mode != .tty) prompts.next() else null; - if (skip > 0) { - skip -= 1; - continue; - } - if (row > 0) { - stream[len] = '\n'; - len += 1; - } - if (pane.body.mode != .tty) if (pane.ovl) |overlay| if (row == overlay.row) { - @memcpy(stream[len..][0..overlay.text.len], overlay.text); - len += overlay.text.len; - skip = overlay.rows - 1; - continue; - }; - const shown = if (prompt) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw - else - raw; - @memcpy(stream[len..][0..shown.len], shown); - len += shown.len; - } - return .{ - .kind = .terminal, - .tag = tag, - .body = body, - .scroll = scroll, - .cols = pane.cols, - .rows = pane.rows, - .vweight = pane.vweight, - .collapsed = pane.collapsed, - .terminal = .{ - .cwd = try arena.dupe(u8, pane.cwdSlice()), - .shell = try arena.dupe(u8, pane.shell orelse ""), - .command = try arena.dupe(u8, pane.command orelse ""), - .status = pane.command_status, - .stream = stream[0..len], - .stream_b64 = try dump.encodeBytes(arena, try screenVt(pane, arena)), - .stream_is_screen = true, - .cursor = .{ - .col = pane.terminal.?.vt.screens.active.cursor.x, - .row = pane.terminal.?.vt.screens.active.cursor.y, - }, - }, - }; -} - -fn buildRows(alloc: std.mem.Allocator, p: *Pardes, pane: *Pane) !Rows { - const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(p.scratch.allocator(), .{ .screen = .{} }); - var pit = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); - // split yields one more item than delimiters; the extra final slot is the - // cursor row retained below. - const n_rows = std.mem.count(u8, full, "\n") + 2; - const rows = try alloc.alloc([]const u8, n_rows); - errdefer alloc.free(rows); - // Blanking a prompt row only ever SHORTENS it and the retained cursor row - // adds one separator, so the dump's length plus one bounds the join. - const text = try alloc.alloc(u8, full.len + 1); - errdefer alloc.free(text); - var at: usize = 0; - var n: usize = 0; - var it = std.mem.splitScalar(u8, full, '\n'); - while (it.next()) |raw| { - const shown = if (pit.next()) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw - else - raw; - if (n > 0) { - text[at] = '\n'; - at += 1; - } - @memcpy(text[at..][0..shown.len], shown); - rows[n] = text[at..][0..shown.len]; - at += shown.len; - n += 1; - } - text[at] = '\n'; - at += 1; - rows[n] = text[at..][0..0]; - n += 1; - std.debug.assert(n == n_rows); - return .{ .text_alloc = text, .text = text[0..at], .rows = rows }; -} - -pub fn bodyText(arena: std.mem.Allocator, pane: *Pane) ![]const u8 { - const vp: []const []const u8 = if (comptime !enabled) &.{} else vp: { - const state = pane.terminal orelse break :vp &.{}; - const screen = state.vt.screens.active; - var tl = screen.pages.getTopLeft(.viewport); - tl.x = 0; - const br = screen.pages.getBottomRight(.viewport) orelse return error.UnknownPoint; - var rows_out: std.Io.Writer.Allocating = .init(arena); - try screen.dumpString(&rows_out.writer, .{ .tl = tl, .br = br, .unwrap = false }); - const raw = try rows_out.toOwnedSlice(); - var prompts = screen.pages.rowIterator(.right_down, .{ .viewport = .{} }, null); - const vp = try arena.alloc([]const u8, std.mem.count(u8, raw, "\n") + 1); - var lines = std.mem.splitScalar(u8, raw, '\n'); - var n: usize = 0; - while (lines.next()) |ln| { - vp[n] = if (pane.body.mode != .tty) - if (prompts.next()) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, ln) else ln - else - ln - else - ln; - n += 1; - } - std.debug.assert(n == vp.len); - break :vp vp; - }; - - const len = fillBody(null, pane, vp); - const out = try arena.alloc(u8, len); - const filled = fillBody(out, pane, vp); - std.debug.assert(filled == out.len); - return out; -} - -pub const BodyRow = union(enum) { - grid: i32, - edit: struct { line: []const u8, idx: usize }, -}; - -const BodyWalk = struct { - pane: *Pane, - goff: i32, - g: i32, - /// the buffer can start above the viewport: drop the lines scrolled past - skip: usize, - n: usize = 0, - lines: ?std.mem.SplitIterator(u8, .scalar) = null, - covered: i32 = 0, - line_idx: usize = 0, - - fn init(pane: *Pane) BodyWalk { - const off = pane.scroll(); - const goff = gridOffset(pane); - return .{ - .pane = pane, - .goff = goff, - .g = if (pane.body.mode == .tty) goff else pane.gridRow(off), - .skip = if (pane.ovl) |o| @intCast(@max(0, off - pane.surfRow(o.row))) else 0, - }; - } - - fn next(w: *BodyWalk) ?BodyRow { - while (w.n < w.pane.rows) { - if (w.lines) |*it| { - if (it.next()) |line| { - const idx = w.line_idx; - w.line_idx += 1; - // Lines scrolled off the top still count: the index names a - // line of the BUFFER, not of the visible body. - if (w.skip > 0) { - w.skip -= 1; - continue; - } - w.n += 1; - return .{ .edit = .{ .line = line, .idx = idx } }; - } - // The buffer stands in for `rows` shell rows however many lines - // it actually spelled, which is the whole slide. - w.g += w.covered; - w.skip = 0; - w.lines = null; - continue; - } - if (w.pane.body.mode != .tty) if (w.pane.ovl) |o| if (w.g == o.row) { - w.lines = std.mem.splitScalar(u8, o.text, '\n'); - w.covered = o.rows; - w.line_idx = 0; - continue; - }; - const vi = w.g - w.goff; - w.g += 1; - w.n += 1; - return .{ .grid = vi }; - } - return null; - } -}; - -/// Run the terminal body row walk. A null destination counts bytes; a slice -/// fills the exact allocation made from that count. -fn fillBody(dst: ?[]u8, pane: *Pane, viewport: []const []const u8) usize { - var walk: BodyWalk = .init(pane); - var written: usize = 0; - var first = true; - while (walk.next()) |row| { - if (!first) { - if (dst) |out| out[written] = '\n'; - written += 1; - } - first = false; - const bytes = switch (row) { - .edit => |e| e.line, - .grid => |vi| if (vi >= 0 and @as(usize, @intCast(vi)) < viewport.len) - viewport[@intCast(vi)] - else - "", - }; - if (dst) |out| @memcpy(out[written..][0..bytes.len], bytes); - written += bytes.len; - } - return written; -} - -// Match surviving edit-buffer rows to their original terminal styles. -const EditAnchors = struct { - /// the buffer's own text, walked in order: a line the VIEWPORT skipped still - /// consumes the row it came from, so the lines below it stay aligned - text: []const u8 = &.{}, - at: usize = 0, - shell: []const []const u8 = &.{}, - /// the covered span, absolute grid rows, as `[first, end)` - first: usize = 0, - end: usize = 0, - lines: usize = 0, - /// the line `at` names, and the first row still unclaimed - idx: usize = 0, - cursor: usize = 0, - budget: usize = 0, - active: bool = false, - - fn init(p: *Pardes, pane: *Pane, o: EditBuffer) EditAnchors { - if (o.rows <= 0 or o.row < 0) return .{}; - const first: usize = @intCast(o.row); - const screen = pane.terminal.?.vt.screens.active; - const total = screen.pages.scrollbar().total; - if (first >= total) return .{}; - const covered: usize = @intCast(o.rows); - const count = @min(covered, total - first); - const tl = screen.pages.pin(.{ .screen = .{ .y = @intCast(first) } }) orelse return .{}; - const br = screen.pages.pin(.{ .screen = .{ - .x = screen.pages.cols - 1, - .y = @intCast(first + count - 1), - } }) orelse return .{}; - const arena = p.scratch.allocator(); - var output: std.Io.Writer.Allocating = .init(arena); - screen.dumpString(&output.writer, .{ .tl = tl, .br = br, .unwrap = false }) catch return .{}; - const shell = arena.alloc([]const u8, count) catch return .{}; - var raw = std.mem.splitScalar(u8, output.written(), '\n'); - var pins = tl.rowIterator(.right_down, br); - for (shell) |*row| { - const text = raw.next() orelse ""; - row.* = if (pins.next()) |pin| - if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, text) else text - else - text; - } - const lines = std.mem.count(u8, o.text, "\n") + 1; - return .{ - .text = o.text, - .shell = shell, - .first = first, - .end = first + count, - .lines = lines, - .cursor = first, - .budget = covered + 4 * lines, - .active = true, - }; - } - - fn shellRow(a: *EditAnchors, idx: usize) ?Anchor { - if (!a.active or idx >= a.lines) return null; - var found: ?Anchor = null; - while (a.idx <= idx) : (a.idx += 1) found = a.claim(a.nextLine() orelse return null); - return found; - } - - fn nextLine(a: *EditAnchors) ?[]const u8 { - if (a.at > a.text.len) return null; - const rest = a.text[a.at..]; - if (std.mem.indexOfScalar(u8, rest, '\n')) |n| { - a.at += n + 1; - return rest[0..n]; - } - // The last line has no terminator; one past the end ends the walk. - a.at = a.text.len + 1; - return rest; - } - - /// Where this line still stands over the grid, if anywhere. - fn claim(a: *EditAnchors, line: []const u8) ?Anchor { - const end = if (line.len == 0) @min(a.cursor + 1, a.end) else a.end; - var k = a.cursor; - while (k < end) : (k += 1) { - if (a.budget == 0) return null; - a.budget -= 1; - if (!std.mem.eql(u8, line, a.shell[k - a.first])) continue; - a.cursor = k + 1; - return .{ .row = @intCast(k) }; - } - if (a.cursor >= a.end) return null; - const shell = a.shell[a.cursor - a.first]; - var p: usize = 0; - while (p < line.len and p < shell.len and line[p] == shell[p]) p += 1; - var s: usize = 0; - const room = @min(line.len, shell.len) - p; - while (s < room and line[line.len - 1 - s] == shell[shell.len - 1 - s]) s += 1; - if (p + s == 0) return null; - if (line.len != p + s and shell.len - (p + s) > shell.len / 2) return null; - const row = a.cursor; - if (s > 0 or p >= shell.len) a.cursor += 1; - return .{ .row = @intCast(row), .prefix = p, .suffix = s, .shell_len = shell.len }; - } -}; - -const Anchor = struct { - /// the row, absolute while it comes from `EditAnchors`, viewport once - /// `recolorAnsi` has subtracted the walk's offset - row: i32, - prefix: usize = std.math.maxInt(usize), - suffix: usize = 0, - /// the row's own dumped length — what the suffix is measured from on the - /// GRID side, where the edit may have changed the byte count - shell_len: usize = 0, - - fn whole(an: Anchor) bool { - return an.prefix == std.math.maxInt(usize); - } -}; - -pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void { - // No emulator, no ANSI cells: the whole pass — and the 256-colour theme - // projection behind it — is compiled out. - if (comptime !enabled) return; - if (pane.terminal == null) return; - const body_y = p.bodyTop(pane, r); - var filtered_storage: FilteredColors = undefined; - const filtered: ?*FilteredColors = if (pane.tty_filter) blk: { - const tz_filter = tracy.zone(@src(), "filterInit"); - defer tz_filter.end(); - filtered_storage = FilteredColors.init(p, pane); - break :blk &filtered_storage; - } else null; - // DECSCNM, read once: the filtered palette folds it in itself, the raw - // path needs it per cell. - const scnm = pane.terminal.?.vt.modes.get(.reverse_colors); - const pages = &pane.terminal.?.vt.screens.active.pages; - const vp_rows: i32 = @intCast(scrollbar(pane).len); - // Which buffer lines the user has not actually changed, so a row swallowed - // by a growing buffer keeps the colour it still stands over. - var anchors: ?EditAnchors = null; - var walk: BodyWalk = .init(pane); - var lines = std.mem.splitScalar(u8, body, '\n'); - var vr: u16 = 0; - while (walk.next()) |row| : (vr += 1) { - if (vr >= body_h) break; - // Before any early exit below, or the lines fall out of step with rows. - const text = lines.next() orelse ""; - const anchor: Anchor = switch (row) { - .edit => |e| blk: { - if (anchors == null) anchors = .init(p, pane, pane.ovl.?); - var an = anchors.?.shellRow(e.idx) orelse continue; - an.row -= walk.goff; - break :blk an; - }, - .grid => |v| .{ .row = v }, - }; - const vi = anchor.row; - if (vi < 0 or vi >= vp_rows) continue; - const row_pin = pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; - const cut: u16 = if (pane.body.mode == .tty) 0 else cut: { - if (row_pin.rowAndCell().row.semantic_prompt == .none) break :cut 0; - break :cut switch (promptCut(row_pin)) { - .keep => 0, - // Blanked end to end: the row shows nothing of the grid, so - // projecting the prompt's own colours onto it would be a lie. - .blank => continue, - .cut => |n| std.math.cast(u16, n) orelse continue, - }; - }; - if (cut > 0 and text.len == 0) continue; - var at: usize = 0; - var sc: u16 = 0; - var gc: u16 = cut; - var sb: usize = 0; - const mine_from = @min(anchor.prefix, text.len); - const mine_to = text.len - @min(anchor.suffix, text.len); - var crossed = false; - while (at < text.len and sc < tw) { - const stop = modal.nextGrapheme(text, at); - if (stop <= at) break; - const span: u16 = if (sc + 1 < tw and s.at(tx + sc + 1, body_y + vr).len == 0) 2 else 1; - if (at >= mine_from and at < mine_to) { - sc += span; - at = stop; - continue; - } - if (at >= mine_to and !crossed) { - crossed = true; - const upto = anchor.shell_len - @min(anchor.suffix, anchor.shell_len); - while (sb < upto) { - const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; - sb += dumpedBytes(row_pin, ci.cell); - gc = std.math.add(u16, gc, 1) catch break; - } - } - const want = stop - at; - // Consume every cell that contributed to this grapheme. A cluster - // ghostty split across several cells is still ONE printed glyph. - var covered: usize = 0; - var style: ?pardes.CellStyle = null; - while (covered < want) { - const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; - if (style == null and ci.cell.wide != .spacer_tail and ci.cell.wide != .spacer_head) - style = cellStyle(p, ci, filtered, scnm); - covered += dumpedBytes(row_pin, ci.cell); - gc = std.math.add(u16, gc, 1) catch break; - // A spacer contributes no bytes; without this the loop would - // spin on a row that ends in one. - if (covered == 0 and gc >= pane.cols) break; - } - while (pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } })) |t| { - if (t.cell.wide != .spacer_tail) break; - gc = std.math.add(u16, gc, 1) catch break; - } - if (style) |st| for (0..span) |k| { - const cell = s.at(tx + sc + @as(u16, @intCast(k)), body_y + vr); - if (cell.default and filtered == null) continue; - cell.default = false; - cell.style = st; - }; - sb += covered; - sc += span; - at = stop; - } - var tail: ?pardes.CellStyle = null; - if (anchor.whole() or anchor.suffix > 0) { - while (sc < tw) { - const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; - gc = std.math.add(u16, gc, 1) catch break; - if (ci.cell.wide == .spacer_tail) continue; - const cell = s.at(tx + sc, body_y + vr); - sc += 1; - const style = cellStyle(p, ci, filtered, scnm); - tail = style; - if (cell.default and filtered == null) continue; - cell.default = false; - cell.style = style; - } - if (tail) |style| while (sc < tw) : (sc += 1) { - const cell = s.at(tx + sc, body_y + vr); - if (cell.default and filtered == null) continue; - cell.default = false; - cell.style = style; - }; - } - } -} - -fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColors, scnm: bool) pardes.CellStyle { - const style = ci.style(); - var cs: pardes.CellStyle = .{ - .fg = if (filtered) |colors| colors.fg(style) else ghostColor(p, style.fg_color, scnm), - .bg = if (filtered) |colors| colors.bg(style, ci.cell) else ghostColor(p, style.bg_color, !scnm), - .bold = style.flags.bold, - .dim = style.flags.faint, - .italic = style.flags.italic, - .blink = style.flags.blink, - .reverse = style.flags.inverse, - .invisible = style.flags.invisible, - .strikethrough = style.flags.strikethrough, - .ul = switch (style.flags.underline) { - .none => .off, - .single => .single, - .double => .double, - .curly => .curly, - .dotted => .dotted, - .dashed => .dashed, - }, - }; - if (filtered == null) switch (ci.cell.content_tag) { - .bg_color_palette => cs.bg = palColor(p, ci.cell.content.color_palette.data), - .bg_color_rgb => { - const rgb = ci.cell.content.color_rgb; - cs.bg = .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; - }, - else => {}, - }; - return cs; -} - -const FilteredColors = struct { - source: GColor.Palette, - target: *const GColor.Palette, - theme_bg: GColor.RGB, - theme_fg: GColor.RGB, - dynamic_bg: ?GColor.RGB, - dynamic_fg: ?GColor.RGB, - default_bg: GColor.RGB, - /// What a foreground too near `default_bg` becomes instead. - fallback_fg: GColor.RGB, - default_bg_luminance: f64, - fg_for_palette: [256]pardes.Color = undefined, - bg_for_palette: [256]pardes.Color = undefined, - /// The two answers for a cell that names no colour of its own. - fg_default: pardes.Color = undefined, - bg_default: pardes.Color = undefined, - cache_rgb: [256]GColor.RGB = undefined, - cache_key: [256]u8 = undefined, - cache_valid: [256]bool = @splat(false), - - fn init(p: *Pardes, pane: *const Pane) FilteredColors { - var source = GColor.default; - for (&source, 0..) |*rgb, i| - rgb.* = pane.terminal.?.vt.colorForXterm(.{ .palette = @intCast(i) }) orelse rgb.*; - const theme = p.theme(); - var theme_bg = asGhostRgb(theme.bg orelse theme.tag_bg); - var theme_fg = asGhostRgb(theme.fg orelse theme.tag_fg); - var dynamic_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }); - var dynamic_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }); - if (pane.terminal.?.vt.modes.get(.reverse_colors)) { - std.mem.swap(GColor.RGB, &theme_bg, &theme_fg); - std.mem.swap(?GColor.RGB, &dynamic_bg, &dynamic_fg); - } - var self: FilteredColors = .{ - .source = source, - .target = p.tty_filter_palette.get(theme), - .theme_bg = theme_bg, - .theme_fg = theme_fg, - .dynamic_bg = dynamic_bg, - .dynamic_fg = dynamic_fg, - .default_bg = theme_bg, - .fallback_fg = theme_fg, - .default_bg_luminance = luminanceOf(theme_bg), - }; - if (dynamic_bg) |rgb| self.default_bg = self.keyedRgb(rgb); - self.default_bg_luminance = luminanceOf(self.default_bg); - if (self.theme_bg.contrast(self.default_bg) > self.theme_fg.contrast(self.default_bg)) - self.fallback_fg = self.theme_bg; - - self.fg_default = asPardesColor(self.legible( - if (self.dynamic_fg) |rgb| self.keyedRgb(rgb) else self.theme_fg, - )); - self.bg_default = asPardesColor(self.default_bg); - for (&self.source, 0..) |current, i| { - const idx: u8 = @intCast(i); - const mapped = self.paletteRgb(idx, current); - self.fg_for_palette[idx] = asPardesColor(self.legible(mapped)); - self.bg_for_palette[idx] = asPardesColor(mapped); - } - return self; - } - - fn fg(self: *FilteredColors, style: ghostty_vt.Style) pardes.Color { - return switch (style.fg_color) { - .none => self.fg_default, - .palette => |idx| self.fg_for_palette[idx], - .rgb => asPardesColor(self.legible(self.keyedRgb(style.fg(.{ - .default = self.dynamic_fg orelse self.theme_fg, - .palette = &self.source, - .bold = null, - })))), - }; - } - - fn bg(self: *FilteredColors, style: ghostty_vt.Style, cell: *const ghostty_vt.Cell) pardes.Color { - switch (cell.content_tag) { - .bg_color_palette => return self.bg_for_palette[cell.content.color_palette.data], - .bg_color_rgb => {}, - else => switch (style.bg_color) { - .none => return self.bg_default, - .palette => |idx| return self.bg_for_palette[idx], - .rgb => {}, - }, - } - // Truecolour, from either the cell or its style. - return asPardesColor(self.keyedRgb(style.bg(cell, &self.source).?)); - } - - fn legible(self: *const FilteredColors, rgb: GColor.RGB) GColor.RGB { - if (contrastOf(luminanceOf(rgb), self.default_bg_luminance) >= - config.tty_filter_min_contrast) return rgb; - return self.fallback_fg; - } - - fn paletteRgb(self: *FilteredColors, idx: u8, current: GColor.RGB) GColor.RGB { - if (current.eql(GColor.default[idx])) return self.target[idx]; - return self.keyedRgb(current); - } - - fn keyedRgb(self: *FilteredColors, rgb: GColor.RGB) GColor.RGB { - return self.target[self.nearestKey(rgb)]; - } - - fn nearestKey(self: *FilteredColors, rgb: GColor.RGB) u8 { - const rgb24 = (@as(u32, rgb.r) << 16) | (@as(u32, rgb.g) << 8) | rgb.b; - const slot: u8 = @truncate((rgb24 *% 0x9e3779b1) >> 24); - if (self.cache_valid[slot] and self.cache_rgb[slot].eql(rgb)) - return self.cache_key[slot]; - - var best: u8 = 0; - var best_distance: u32 = std.math.maxInt(u32); - for (GColor.default, 0..) |candidate, i| { - const distance = colorDistance(rgb, candidate); - // Strict comparison makes duplicate-colour ties stable at the - // lowest canonical xterm key. - if (distance < best_distance) { - best_distance = distance; - best = @intCast(i); - } - } - self.cache_rgb[slot] = rgb; - self.cache_key[slot] = best; - self.cache_valid[slot] = true; - return best; - } -}; - -const channel_luminance: [256]f64 = blk: { - @setEvalBranchQuota(20000); - var table: [256]f64 = undefined; - for (&table, 0..) |*slot, c| { - const normalized: f64 = @as(f64, @floatFromInt(c)) / 255; - slot.* = if (normalized <= 0.03928) - normalized / 12.92 - else - std.math.pow(f64, (normalized + 0.055) / 1.055, 2.4); - } - break :blk table; -}; - -fn luminanceOf(rgb: GColor.RGB) f64 { - return 0.2126 * channel_luminance[rgb.r] + - 0.7152 * channel_luminance[rgb.g] + - 0.0722 * channel_luminance[rgb.b]; -} - -/// ghostty's `RGB.contrast` with both luminances already in hand. -fn contrastOf(a_luminance: f64, b_luminance: f64) f64 { - const lighter = @max(a_luminance, b_luminance); - const darker = @min(a_luminance, b_luminance); - return (lighter + 0.05) / (darker + 0.05); -} - -fn colorDistance(a: GColor.RGB, b: GColor.RGB) u32 { - const dr = @as(i32, a.r) - @as(i32, b.r); - const dg = @as(i32, a.g) - @as(i32, b.g); - const db = @as(i32, a.b) - @as(i32, b.b); - return @intCast(dr * dr + dg * dg + db * db); -} - -test "the luminance table answers exactly what ghostty computes" { - for (0..256) |i| { - const c: u8 = @intCast(i); - const grey: GColor.RGB = .{ .r = c, .g = c, .b = c }; - try std.testing.expectEqual(grey.luminance(), luminanceOf(grey)); - } - // Channel weights are asymmetric, so a grey ramp alone would not catch a - // transposed coefficient. The palette is what the tables enumerate. - for (GColor.default) |candidate| { - try std.testing.expectEqual(candidate.luminance(), luminanceOf(candidate)); - for (GColor.default) |page| { - try std.testing.expectEqual( - candidate.contrast(page), - contrastOf(luminanceOf(candidate), luminanceOf(page)), - ); - } - } -} - -test "terminal Filter keys indexed truecolor OSC and background-only cells through the theme" { - const testing = std.testing; - // Raw index assertions require a theme that inherits the ANSI palette. - const p = try Pardes.init(testing.allocator, .{ .startup_config = "Theme helix\n", .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.tag_expanded = false; // a one-row tag keeps this small screen's rows - p.sync(); - try testing.expect(pane.tty_filter); - pane.tty_filter = false; - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[31mA" ++ - "\x1b[38;5;196mB" ++ - "\x1b[38;2;255;0;0mC" ++ - "\x1b[0;48;5;25mD" ++ - "\x1b[0;48;2;0;95;175mE" ++ - "\x1b[0;1;2;3;4;5;7;8;9mF" ++ - "\x1b[0;48;5;25m\x1b[K" ++ - "\r\n\x1b[0;38;5;2m界" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - - const raw = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .index = 1 }, raw.at(tx, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .index = 196 }, raw.at(tx + 1, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .rgb = .{ 255, 0, 0 } }, raw.at(tx + 2, body_y).style.fg); - - pane.tty_filter = true; - _ = frame.reset(.retain_capacity); - const filtered = try p.render(frame.allocator()); - var expected_cache: FilterPalette = .{}; - const expected = expected_cache.get(p.theme()); - try testing.expectEqual(asPardesColor(expected[1]), filtered.at(tx, body_y).style.fg); - try testing.expectEqual(asPardesColor(expected[196]), filtered.at(tx + 1, body_y).style.fg); - try testing.expectEqual(filtered.at(tx + 1, body_y).style.fg, filtered.at(tx + 2, body_y).style.fg); - try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 3, body_y).style.bg); - try testing.expectEqual(filtered.at(tx + 3, body_y).style.bg, filtered.at(tx + 4, body_y).style.bg); - - const attrs = filtered.at(tx + 5, body_y).style; - try testing.expect(attrs.bold); - try testing.expect(attrs.dim); - try testing.expect(attrs.italic); - try testing.expect(attrs.blink); - try testing.expect(attrs.reverse); - try testing.expect(attrs.invisible); - try testing.expect(attrs.strikethrough); - try testing.expectEqual(.single, attrs.ul); - - const erased = pane.terminal.?.vt.screens.active.pages.getCell(.{ .viewport = .{ .x = 6, .y = 0 } }).?; - try testing.expectEqual(.bg_color_palette, erased.cell.content_tag); - try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 6, body_y).style.bg); - try testing.expectEqual(asPardesColor(expected[2]), filtered.at(tx, body_y + 1).style.fg); - try testing.expectEqual(filtered.at(tx, body_y + 1).style, filtered.at(tx + 1, body_y + 1).style); - // A filtered terminal never delegates either colour to a backend palette, - // including cells which were empty/default before the pass. - for (0..r.w - config.GUTTER) |col| { - const cell = filtered.at(tx + @as(u16, @intCast(col)), body_y); - try testing.expect(!cell.default); - switch (cell.style.fg) { - .rgb => {}, - else => return error.FilteredForegroundWasNotRgb, - } - switch (cell.style.bg) { - .rgb => {}, - else => return error.FilteredBackgroundWasNotRgb, - } - } - - // Colors remains the global master gate. The pane remembers Filter while - // ANSI projection is dormant, and resumes it without replaying VT bytes. - p.settings.colors = false; - _ = frame.reset(.retain_capacity); - const plain = try p.render(frame.allocator()); - try testing.expect(pane.tty_filter); - try testing.expectEqual(asPardesColor(asGhostRgb(p.theme().fg.?)), plain.at(tx, body_y).style.fg); - p.settings.colors = true; - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]4;1;#ff0000\x1b\\" } }); - const osc_red = pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?; - try testing.expect(osc_red.eql(.{ .r = 255, .g = 0, .b = 0 })); - pane.tty_filter = false; - pane.tty_filter = true; - try testing.expect(osc_red.eql(pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?)); - _ = frame.reset(.retain_capacity); - const osc_palette = try p.render(frame.allocator()); - try testing.expectEqual(asPardesColor(expected[196]), osc_palette.at(tx, body_y).style.fg); - - // Dynamic default foreground/background colours key every default cell, - // including the otherwise blank end of the row. - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]10;#ff0000\x1b\\" ++ - "\x1b]11;#5f5f5f\x1b\\" } }); - const dyn_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }).?; - const dyn_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }).?; - try testing.expect(dyn_fg.eql(.{ .r = 255, .g = 0, .b = 0 })); - try testing.expect(dyn_bg.eql(.{ .r = 95, .g = 95, .b = 95 })); - _ = frame.reset(.retain_capacity); - const dynamic = try p.render(frame.allocator()); - const blank = dynamic.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(expected[196]), blank.fg); - try testing.expectEqual(asPardesColor(expected[59]), blank.bg); - - const explicit_before_reverse = dynamic.at(tx, body_y).style.fg; - try testing.expectEqual(asPardesColor(expected[196]), explicit_before_reverse); - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); - _ = frame.reset(.retain_capacity); - const reversed = try p.render(frame.allocator()); - const reversed_blank = reversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(expected[59]), reversed_blank.fg); - try testing.expectEqual(asPardesColor(expected[196]), reversed_blank.bg); - const reversed_explicit = reversed.at(tx, body_y).style; - try testing.expectEqual(asPardesColor(expected[196]), reversed_explicit.bg); - try testing.expectEqual(pardes.Color{ .rgb = p.theme().bg.? }, reversed_explicit.fg); - try testing.expect(!std.meta.eql(reversed_explicit.fg, reversed_explicit.bg)); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5l" } }); - _ = frame.reset(.retain_capacity); - const unreversed = try p.render(frame.allocator()); - const unreversed_blank = unreversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; - try testing.expectEqual(asPardesColor(expected[196]), unreversed_blank.fg); - try testing.expectEqual(asPardesColor(expected[59]), unreversed_blank.bg); - - // The cache is keyed by values, not a theme name. Replacing a custom - // theme in place immediately recolours already-rendered indexed cells. - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]104;1\x1b\\" } }); - var custom = p.theme().*; - custom.name = try p.gpa.dupe(u8, "same-name"); - custom.palette = null; - custom.kw = .{ 1, 2, 3 }; - p.custom_theme = custom; - _ = frame.reset(.retain_capacity); - const custom_first = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = .{ 1, 2, 3 } }, custom_first.at(tx, body_y).style.fg); - if (p.custom_theme) |*theme| theme.kw = .{ 4, 5, 6 }; - _ = frame.reset(.retain_capacity); - const custom_second = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = .{ 4, 5, 6 } }, custom_second.at(tx, body_y).style.fg); -} - -test "terminal Filter keeps extended keys dark-to-light on a light theme" { - const p = try Pardes.init(std.testing.allocator, .{ .startup_config = "Theme acme\n", .tty_only = true }); - defer p.deinit(); - try std.testing.expectEqualStrings("acme", p.theme().name); - var cache: FilterPalette = .{}; - const palette = cache.get(p.theme()); - try std.testing.expect(palette[16].eql(asGhostRgb(p.theme().fg.?))); - try std.testing.expect(palette[231].eql(asGhostRgb(p.theme().bg.?))); -} - -test "terminal Filter preserves exact palette-null light theme default roles" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 5 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - - var light = p.theme().*; - light.name = try p.gpa.dupe(u8, "filter-light-defaults"); - light.bg = .{ 0xf8, 0xf8, 0xf8 }; - light.fg = .{ 0x38, 0x38, 0x38 }; - light.palette = null; - p.custom_theme = light; - - const pane = p.panes[0].?; - try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground })); - try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background })); - pane.tty_filter = true; - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - const ordinary = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, ordinary.at(tx, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, ordinary.at(tx, body_y).style.bg); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); - _ = frame.reset(.retain_capacity); - const reversed = try p.render(frame.allocator()); - try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, reversed.at(tx, body_y).style.fg); - try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, reversed.at(tx, body_y).style.bg); -} - -test "terminal Filter maps the default roles before it maps anything else" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - try testing.expect(pane.tty_filter); - - // Native dark/light palettes plus legacy helix/dark/acme, including - // the null-page fallback that only the legacy dark theme exercises. - for (0..9) |t| { - p.settings.theme = @intCast(t); - const stage_one = FilteredColors.init(p, pane); - // `dark` declares no background of its own, which is exactly why the - // resolver reads the tag colours as the fallback rather than `.?`. - const theme = p.theme(); - try testing.expect(stage_one.theme_bg.eql(asGhostRgb(theme.bg orelse theme.tag_bg))); - try testing.expect(stage_one.theme_fg.eql(asGhostRgb(theme.fg orelse theme.tag_fg))); - // With no OSC 11 in play the mapped page IS that anchor, and the - // fallback is the other one: a background never contrasts with itself. - try testing.expect(stage_one.default_bg.eql(stage_one.theme_bg)); - try testing.expect(stage_one.fallback_fg.eql(stage_one.theme_fg)); - } - - p.settings.theme = 0; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]11;#5f5f5f\x1b\\" } }); - var moved = FilteredColors.init(p, pane); - try testing.expect(!moved.default_bg.eql(moved.theme_bg)); - try testing.expect(moved.default_bg.eql(moved.keyedRgb(.{ .r = 0x5f, .g = 0x5f, .b = 0x5f }))); -} - -test "terminal Filter refuses a foreground that would collapse onto the page" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - try testing.expect(pane.tty_filter); - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[38;2;255;255;255mW" ++ - "\x1b[0;30mB" ++ - "\x1b[0;31mR" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - - for (0..9) |t| { - p.settings.theme = @intCast(t); - var fc = FilteredColors.init(p, pane); - const page = asPardesColor(fc.default_bg); - const rescued = asPardesColor(fc.fallback_fg); - _ = frame.reset(.retain_capacity); - const g = try p.render(frame.allocator()); - - // The colour each of the three would have been given with no floor. - const raw_white = fc.keyedRgb(.{ .r = 255, .g = 255, .b = 255 }); - const raw_black = fc.paletteRgb(0, GColor.default[0]); - const raw_red = fc.paletteRgb(1, GColor.default[1]); - - for ([_]struct { at: u16, raw: GColor.RGB }{ - .{ .at = 0, .raw = raw_white }, - .{ .at = 1, .raw = raw_black }, - .{ .at = 2, .raw = raw_red }, - }) |case| { - const cell = g.at(tx + case.at, body_y).style; - try testing.expectEqual(page, cell.bg); - if (case.raw.contrast(fc.default_bg) < config.tty_filter_min_contrast) { - // Refused: the projection's answer is not painted, the anchor is. - try testing.expectEqual(rescued, cell.fg); - try testing.expect(!std.meta.eql(cell.fg, cell.bg)); - } else { - // Cleared the floor, so stage two leaves it exactly alone. - try testing.expectEqual(asPardesColor(case.raw), cell.fg); - } - // Either way a filtered cell delegates neither colour to a backend. - switch (cell.fg) { - .rgb => |ink| try testing.expect(asGhostRgb(ink).contrast(fc.default_bg) >= - config.tty_filter_min_contrast), - else => return error.FilteredForegroundWasNotRgb, - } - } - - // At least one of the three has to have been a real collapse, or this - // theme proved nothing: white on the light theme, black on the dark. - try testing.expect(raw_white.contrast(fc.default_bg) < config.tty_filter_min_contrast or - raw_black.contrast(fc.default_bg) < config.tty_filter_min_contrast); - // A saturated red is never the page on any curated theme. - try testing.expect(raw_red.contrast(fc.default_bg) >= config.tty_filter_min_contrast); - } -} - -test "terminal Filter holds every projected foreground off the page" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - - for (0..9) |t| { - p.settings.theme = @intCast(t); - var fc = FilteredColors.init(p, pane); - var refused: usize = 0; - for (fc.target, 0..) |projected, key| { - const ink = fc.legible(projected); - try testing.expect(ink.contrast(fc.default_bg) >= config.tty_filter_min_contrast); - if (!ink.eql(projected)) { - refused += 1; - try testing.expect(ink.eql(fc.fallback_fg)); - // Only ever refused for being too near the page. - try testing.expect(projected.contrast(fc.default_bg) < config.tty_filter_min_contrast); - } - // The key a background asks for is handed back untouched, including - // the one whose value is the page itself. - try testing.expect(fc.keyedRgb(GColor.default[key]).eql(fc.target[fc.nearestKey(GColor.default[key])])); - } - // Every curated theme owns at least one collapsing key — that is why - // the floor exists — and the floor must not be flattening the palette. - try testing.expect(refused > 0); - try testing.expect(refused < fc.target.len / 8); - } -} - -test "tty ansi colors follow the prompt hug into normal mode" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.tty_filter = false; - - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32mPP\x1b]133;B\x1b\\\x1b[31mR\x1b[34mB\x1b[0m out" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - const red: pardes.Color = .{ .rgb = p.theme().palette.?[1] }; - const blue: pardes.Color = .{ .rgb = p.theme().palette.?[4] }; - - // tty mode projects the emulator's ansi colours cell for cell. - pane.body.mode = .tty; - p.shell_rows.stale = true; - const tty = try p.render(frame.allocator()); - try testing.expectEqual(red, tty.at(tx + 2, body_y).style.fg); - try testing.expectEqual(blue, tty.at(tx + 3, body_y).style.fg); - - pane.body.mode = .normal; - p.shell_rows.stale = true; - _ = frame.reset(.retain_capacity); - const norm = try p.render(frame.allocator()); - try testing.expectEqualStrings("R", norm.at(tx, body_y).grapheme()); - try testing.expectEqualStrings("B", norm.at(tx + 1, body_y).grapheme()); - try testing.expectEqual(red, norm.at(tx, body_y).style.fg); - try testing.expectEqual(blue, norm.at(tx + 1, body_y).style.fg); -} - -test "a prompt row hidden end to end paints nothing at all" { - const testing = std.testing; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 8 }); - defer p.deinit(); - while (p.nextEffect()) |_| {} - const pane = p.panes[0].?; - pane.tag_expanded = false; // a 12x8 screen: the body, not the tag - p.sync(); - pane.tty_filter = false; - pane.body.mode = .normal; - p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32maaaaaaaaa\x1b]133;B\x1b\\\x1b[41;36m\u{754C}\x1b[0m\r\n" } }); - - var frame = std.heap.ArenaAllocator.init(testing.allocator); - defer frame.deinit(); - const r = p.rects[0]; - const tx = r.x + config.GUTTER; - const body_y = p.bodyTop(pane, r); - p.shell_rows.stale = true; - const s = try p.render(frame.allocator()); - - try testing.expectEqualStrings(" ", s.at(tx, body_y).grapheme()); - try testing.expect(!std.meta.eql(pardes.Color{ .rgb = p.theme().palette.?[1] }, s.at(tx, body_y).style.bg)); -} - -pub fn palColor(p: *Pardes, idx: u8) pardes.Color { - if (p.theme().palette) |pal| if (idx < 16) return .{ .rgb = pal[idx] }; - return .{ .index = idx }; -} - -pub fn ghostColor(p: *Pardes, color: ghostty_vt.Style.Color, is_bg: bool) pardes.Color { - return switch (color) { - .none => blk: { - const t = if (is_bg) p.theme().bg else p.theme().fg; - break :blk if (t) |c| .{ .rgb = c } else .default; - }, - .palette => |idx| palColor(p, idx), - .rgb => |rgb| .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }, - }; -} - -/// executing at a prompt with typed text below it: pad the output area -/// with newlines so the command's output doesn't overwrite the buffer -pub fn padOutputBelowEdits(p: *Pardes, id: usize) void { - // Nothing to pad away from: with no emulator there is no prompt and no - // child whose output could land on top of the edit buffer. - if (comptime !enabled) return; - const pane = p.panes[id] orelse return; - const o = pane.ovl orelse return; - if (!pane.isTerminal()) return; - const state = pane.terminal orelse return; - if (!state.vt.cursorIsAtPrompt()) return; - // the buffer's LAST surface row: its lines may outnumber the shell - // rows it covers, and it is the bottom one output must clear - const max_row = o.row + @as(i32, @intCast(modal.lineCount(o.text))) - 1; - const goff: i32 = @intCast(state.vt.screens.active.pages.scrollbar().offset); - const cursor_abs = pane.surfRow(goff + @as(i32, @intCast(state.vt.screens.active.cursor.y))); - const pad = std.math.clamp(max_row - cursor_abs, 0, @as(i32, pane.rows)); - var i: i32 = 0; - while (i < pad) : (i += 1) p.emitWrite(id, "\r"); -} - -pub fn pushUndo(p: *Pardes, pane: *Pane) void { - pane.body.remember(p.gpa, pane.ovl); -} - -pub fn undo(p: *Pardes, pane: *Pane) void { - const back_to = pane.body.step(p.gpa, pane.ovl, true) orelse return; - if (pane.ovl) |o| p.gpa.free(o.text); - pane.ovl = back_to.ovl; - pane.ensureCursorVisible(); -} - -pub fn redo(p: *Pardes, pane: *Pane) void { - const forward_to = pane.body.step(p.gpa, pane.ovl, false) orelse return; - if (pane.ovl) |o| p.gpa.free(o.text); - pane.ovl = forward_to.ovl; - pane.ensureCursorVisible(); -} - -pub fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: [:0]const u8) void { - const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal)); - const room = state.reply.len - state.reply_len; - const n = @min(room, data.len); - @memcpy(state.reply[state.reply_len..][0..n], data[0..n]); - state.reply_len += @intCast(n); -} - -const DeviceAttrs = @typeInfo(@typeInfo(@typeInfo( - @FieldType(ghostty_vt.TerminalStream.Handler.Effects, "device_attributes"), -).optional.child).pointer.child).@"fn".return_type.?; -pub fn ptyDeviceAttrs(_: *ghostty_vt.TerminalStream.Handler) DeviceAttrs { - return .{}; -} diff --git a/src/Text.zig b/src/Text.zig index ab23bf8e..cef76b3b 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -14,7 +14,7 @@ const config = @import("config.zig"); const memory = @import("memory.zig"); const Pane = panes.Pane; const File = panes.File; -const Terminal = panes.Terminal; +const terminal = panes.terminal; const Text = @This(); pub const Mode = enum { normal, insert, tty }; @@ -84,9 +84,9 @@ normal: modal.Normal.State = .{}, /// last f/F/t/T motion, for Alt-. repeat find_op: u8 = 0, find_ch: u21 = 0, -ed_undo: [Terminal.history_max]Terminal.Snapshot = undefined, +ed_undo: [terminal.history_max]terminal.Snapshot = undefined, ed_undo_len: usize = 0, -ed_redo: [Terminal.history_max]Terminal.Snapshot = undefined, +ed_redo: [terminal.history_max]terminal.Snapshot = undefined, ed_redo_len: usize = 0, /// Set when an edit would have changed characters this text does not own /// (a tag's computed prefix) and was refused; the key that tried it puts @@ -706,10 +706,10 @@ pub fn clampCursor(t: *Text, text: []const u8, row0: i32) void { t.show(); } -fn pushHistory(gpa: std.mem.Allocator, slots: []Terminal.Snapshot, len: *usize, value: Terminal.Snapshot) void { +fn pushHistory(gpa: std.mem.Allocator, slots: []terminal.Snapshot, len: *usize, value: terminal.Snapshot) void { if (len.* == slots.len) { if (slots[0].ovl) |overlay| gpa.free(overlay.text); - std.mem.copyForwards(Terminal.Snapshot, slots[0 .. slots.len - 1], slots[1..]); + std.mem.copyForwards(terminal.Snapshot, slots[0 .. slots.len - 1], slots[1..]); len.* -= 1; } slots[len.*] = value; @@ -719,14 +719,14 @@ fn pushHistory(gpa: std.mem.Allocator, slots: []Terminal.Snapshot, len: *usize, /// Record an edit buffer (a terminal's overlay, a tag's own text) as it /// stands before an edit, once per change of it, and forget what could have /// been redone. Null is a buffer not made yet. -pub fn remember(t: *Text, gpa: std.mem.Allocator, current: ?Terminal.EditBuffer) void { +pub fn remember(t: *Text, gpa: std.mem.Allocator, current: ?terminal.EditBuffer) void { if (t.ed_undo_len > 0) { const top = t.ed_undo[t.ed_undo_len - 1]; const same = if (top.ovl) |overlay| if (current) |now| overlay.row == now.row and overlay.rows == now.rows and std.mem.eql(u8, overlay.text, now.text) else false else current == null; if (same) return; } - const copy: ?Terminal.EditBuffer = if (current) |now| .{ .row = now.row, .rows = now.rows, .text = gpa.dupe(u8, now.text) catch return } else null; + const copy: ?terminal.EditBuffer = if (current) |now| .{ .row = now.row, .rows = now.rows, .text = gpa.dupe(u8, now.text) catch return } else null; pushHistory(gpa, &t.ed_undo, &t.ed_undo_len, .{ .ovl = copy, .cur_row = t.cur_row, .cur_col = t.cur_col, .vsel = t.vsel }); for (t.ed_redo[0..t.ed_redo_len]) |item| if (item.ovl) |overlay| gpa.free(overlay.text); t.ed_redo_len = 0; @@ -736,13 +736,13 @@ pub fn remember(t: *Text, gpa: std.mem.Allocator, current: ?Terminal.EditBuffer) /// other history and the state to return to comes back, its cursor and /// selection already restored here. The caller installs its buffer, which /// it then owns. Null when there is nothing to step to. -pub fn step(t: *Text, gpa: std.mem.Allocator, current: ?Terminal.EditBuffer, back: bool) ?Terminal.Snapshot { +pub fn step(t: *Text, gpa: std.mem.Allocator, current: ?terminal.EditBuffer, back: bool) ?terminal.Snapshot { const from, const from_len, const to, const to_len = if (back) .{ &t.ed_undo, &t.ed_undo_len, &t.ed_redo, &t.ed_redo_len } else .{ &t.ed_redo, &t.ed_redo_len, &t.ed_undo, &t.ed_undo_len }; if (from_len.* == 0) return null; - const copy: ?Terminal.EditBuffer = if (current) |now| .{ .row = now.row, .rows = now.rows, .text = gpa.dupe(u8, now.text) catch return null } else null; + const copy: ?terminal.EditBuffer = if (current) |now| .{ .row = now.row, .rows = now.rows, .text = gpa.dupe(u8, now.text) catch return null } else null; pushHistory(gpa, to, to_len, .{ .ovl = copy, .cur_row = t.cur_row, .cur_col = t.cur_col, .vsel = t.vsel }); from_len.* -= 1; const back_to = from[from_len.*]; diff --git a/src/body_layer.zig b/src/body_layer.zig index 6e1fe8f1..cb26c1f2 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -51,7 +51,7 @@ fn paintTerminalSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: [ var visible: i32 = 0; while (lines.next()) |line| : (visible += 1) { if (visible >= r.h -| pane.tag_rows) break; - const source_row = if (raw) panes.Terminal.gridOffset(pane) + visible else pane.wrapAt(visible).line; + const source_row = if (raw) panes.terminal.gridOffset(pane) + visible else pane.wrapAt(visible).line; for (rows) |row| { const target = if (row.raw_terminal) (if (raw) row.row else pane.surfRow(row.row)) @@ -64,7 +64,7 @@ fn paintTerminalSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: [ lo -|= row.prompt_bytes; hi -|= row.prompt_bytes; } else if (!row.raw_terminal and raw) { - const prefix = panes.Terminal.promptPrefixBytes(pane, source_row, line); + const prefix = panes.terminal.promptPrefixBytes(pane, source_row, line); lo += prefix; hi += prefix; } @@ -85,7 +85,7 @@ fn paintTerminalSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: [ fn paintSourceSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: []const Pane.PointerRow, bg: [3]u8, fg: ?[3]u8) void { if (pane.isTerminal()) return paintTerminalSelection(p, s, pane, r, rows, bg, fg); - const terminal_lines = if (pane.file == null) panes.Terminal.cursorLines(p, pane) catch return else &.{}; + const terminal_lines = if (pane.file == null) panes.terminal.cursorLines(p, pane) catch return else &.{}; const tx = r.x + config.GUTTER; const width = r.w -| config.GUTTER; const body_y = p.bodyTop(pane, r); @@ -291,7 +291,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane panes.File.recolorSyntax(p, s, pane, f, r, tx, tw, body_h); panes.File.drawWrapMarkers(p, s, pane, r, tx, tw, body_h, pane_bg); } else if (pane.isTerminal() and p.settings.colors) { - panes.Terminal.recolorAnsi(p, s, pane, r, tx, tw, body_h, body); + panes.terminal.recolorAnsi(p, s, pane, r, tx, tw, body_h, body); } tz_color.end(); @@ -440,8 +440,8 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane // (the tag's or a prompt's cursor wins while that is being typed into) if (active and pane.focus == .body and (pane.prompt == .none or pane.prompt == .del_side or pane.prompt == .repl_choice)) { if (pane.body.mode != .tty) { - const cur = panes.Terminal.gridCursor(pane); - const goff = panes.Terminal.gridOffset(pane); + const cur = panes.terminal.gridCursor(pane); + const goff = panes.terminal.gridOffset(pane); const crow = if (pane.body.cur_pinned) pane.body.cur_row else pane.surfRow(@as(i32, @intCast(cur.y)) + goff); const ccol = if (pane.body.cur_pinned) pane.body.cur_col else @as(i32, @intCast(cur.x)); const cwp = pane.wrapRow(crow, ccol); @@ -460,7 +460,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane ccol; if (prow >= pane.tag_rows and cx >= 0 and prow < body_bottom and cx < tw) s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = body_y + @as(u16, @intCast(prow - pane.tag_rows)), .bar = pane.body.mode == .insert }; - } else if (panes.Terminal.visibleCursor(pane)) |cur| { + } else if (panes.terminal.visibleCursor(pane)) |cur| { if (cur.y + pane.tag_rows < body_bottom and cur.x < tw) s.cursor = .{ .x = tx + cur.x, .y = body_y + cur.y }; } @@ -492,5 +492,5 @@ pub fn bodyText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]const u8 { unreachable; } if (pane.file) |*f| return panes.File.bodyText(arena, pane, f, p.settings.wrap); - return panes.Terminal.bodyText(arena, pane); + return panes.terminal.bodyText(arena, pane); } diff --git a/src/builtins.zig b/src/builtins.zig index cc86067e..c549b17f 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -625,7 +625,7 @@ pub const Kill = struct { stopped = true; continue; }; - if (!panes.Terminal.commandRunning(pane)) continue; + if (!panes.terminal.commandRunning(pane)) continue; const sent = pane.sent_command.?; if (names.len > 0) { var words = std.mem.tokenizeAny(u8, names, " \t"); diff --git a/src/draw.zig b/src/draw.zig index 10303117..ad24153f 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -63,7 +63,7 @@ pub fn place(p: *Pardes, s: *Surface) void { // A folded pane is its tag rows and nothing else. if (pane.collapsed) continue; const body_h = r.h -| pane.tag_rows; - const line: i32 = if (pane.file) |f| @intCast(@min(f.scroll, std.math.maxInt(i32))) else if (pane.isTerminal()) panes.Terminal.gridOffset(pane) else 0; + const line: i32 = if (pane.file) |f| @intCast(@min(f.scroll, std.math.maxInt(i32))) else if (pane.isTerminal()) panes.terminal.gridOffset(pane) else 0; s.addRegion(.{ .kind = .body, .owner = owner, .serial = pane.serial, .active = active, .line = line, .rect = .{ .x = r.x + config.GUTTER, .y = body_y, .w = r.w - config.GUTTER, .h = body_h } }); var rail: Region = .{ .kind = .rail, .owner = owner, .serial = pane.serial, .active = active, .rect = .{ .x = r.x, .y = body_y, .w = config.GUTTER, .h = body_h } }; // An image's rail has no thumb; a native PDF's is measured as its @@ -78,7 +78,7 @@ pub fn place(p: *Pardes, s: *Surface) void { .offset = page, .len = 1, } else blk: { - const gsb = panes.Terminal.scrollbar(pane); + const gsb = panes.terminal.scrollbar(pane); break :blk .{ .total = gsb.total, .offset = gsb.offset, .len = gsb.len }; }; const track_h: usize = body_h; @@ -241,7 +241,7 @@ fn glideCursor(p: *Pardes, s: *Surface) void { if (inside) frame = paneFrame(s, pane.serial, rect); const origin: [2]f32 = .{ @floatFromInt(rect.x), @floatFromInt(rect.y) }; const view = p.cursor_view; - const line: i64 = if (pane.file) |f| @intCast(f.scroll) else if (pane.isTerminal()) panes.Terminal.gridOffset(pane) else 0; + const line: i64 = if (pane.file) |f| @intCast(f.scroll) else if (pane.isTerminal()) panes.terminal.gridOffset(pane) else 0; if (view.serial == pane.serial and view.inside == inside) { // The pane moved in the layout: the springs move with it (its // own cursor's; one in a column's tag stays). @@ -719,7 +719,7 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { sb_off = page; sb_total = if (comptime pdf_enabled) at.pdf.?.page_count else 0; } else { - const sb = panes.Terminal.scrollbar(at); + const sb = panes.terminal.scrollbar(at); sb_off = sb.offset; sb_total = sb.total; } diff --git a/src/dump.zig b/src/dump.zig index 1eabdae8..73d4e4ed 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -731,7 +731,7 @@ pub fn dumpState(p: *Pardes) !void { } else if (pane.image) |iv| try pardes.panes.Image.dumpPane(p, arena, pane, tag, body, scroll, iv.path, iv.raw) else - try pardes.panes.Terminal.dumpPane(pane, arena, tag, body, scroll); + try pardes.panes.terminal.dumpPane(pane, arena, tag, body, scroll); dp.tag_tail = pane.tag.own; if (dp.file) |*df| { const dot = ctlfs.pane.dotOf(pane); @@ -914,7 +914,7 @@ fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previo // and how it ended: its command is not run again. const live = comptime (terminal_panes and platform != .web and !isolated); const revive = live and t.cwd.len <= effect_path_cap and t.command.len == 0; - const restored = try pardes.panes.Terminal.restore(p, src, revive); + const restored = try pardes.panes.terminal.restore(p, src, revive); p.installPane(i, restored); try restored.setOwnedCwd(t.cwd); if (t.shell.len > 0) restored.shell = try gpa.dupe(u8, t.shell); diff --git a/src/edit.zig b/src/edit.zig index 26062029..98c60efb 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -113,7 +113,7 @@ pub fn clipRequest(p: *Pardes, id: usize, mode: @FieldType(ClipRequest, "mode")) pub fn typeToTty(p: *Pardes, id: usize, pane: *const Pane, text: []const u8) void { if (text.len == 0) return; - if (panes.Terminal.bracketedPaste(pane)) { + if (panes.terminal.bracketedPaste(pane)) { p.emitWrite(id, "\x1b[200~"); p.emitWrite(id, text); p.emitWrite(id, "\x1b[201~"); @@ -225,7 +225,7 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { // Refresh the source map before translating the rendered rectangle. const raw = pane.isTerminal() and pane.body.mode == .tty; const body = try body_layer.bodyText(p, p.scratch.allocator(), pane); - const terminal_lines = if (pane.file == null and !raw) try panes.Terminal.cursorLines(p, pane) else &.{}; + const terminal_lines = if (pane.file == null and !raw) try panes.terminal.cursorLines(p, pane) else &.{}; const first = @max(0, @min(gesture.r0, gesture.r1) - pane.tag_rows); const logical_rows = if (pane.body_rows > 0) pane.body_rows else pane.rows; const last = @min(@as(i32, logical_rows) - 1, @max(gesture.r0, gesture.r1) - pane.tag_rows); @@ -242,7 +242,7 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { const left: i32 = if (cols.first) cols.lo else prefix; const right: i32 = cols.hi orelse std.math.maxInt(i32) / 2; var source = pane.wrapAt(visible); - if (raw) source = .{ .line = panes.Terminal.gridOffset(pane) + visible, .at = 0 }; + if (raw) source = .{ .line = panes.terminal.gridOffset(pane) + visible, .at = 0 }; const line = if (raw) modal.lineSlice(body, @intCast(visible)) else pointerSourceLine(pane, terminal_lines, source.line); var next = pane.wrapAt(visible + 1); if (raw) next = .{ .line = source.line + 1, .at = 0 }; @@ -256,7 +256,7 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { .hi = if (right < prefix) lo else if (cols.hi == null) end else @min(end, modal.nextGrapheme(line, at)), .to_edge = cols.hi == null, .raw_terminal = raw, - .prompt_bytes = if (raw) panes.Terminal.promptPrefixBytes(pane, source.line, line) else 0, + .prompt_bytes = if (raw) panes.terminal.promptPrefixBytes(pane, source.line, line) else 0, }; const rendered = modal.lineSlice(body, @intCast(visible)); const prefix_end = @min(rendered.len, @as(usize, @intCast(@min(prefix, right + 1)))); @@ -276,7 +276,7 @@ pub fn selectionText(p: *Pardes, pane: *Pane, sl: Pane.Sel) ![]const u8 { const arena = p.scratch.allocator(); if (pane.rawPointerText(sl)) |text| return arena.dupe(u8, text); if (pane.pointerSelection(sl)) |rows| { - const terminal_lines = if (pane.file == null) try panes.Terminal.cursorLines(p, pane) else &.{}; + const terminal_lines = if (pane.file == null) try panes.terminal.cursorLines(p, pane) else &.{}; var total: usize = rows.len -| 1; for (rows) |row| { const line = pointerSourceLine(pane, terminal_lines, row.row); @@ -402,7 +402,7 @@ pub fn paneCursorLines(p: *Pardes, t: *Text) ![]const []const u8 { if (comptime pdf_enabled) return panes.Pdf.textLines(&pane.pdf.?, p.pdf_gpa, arena); unreachable; } - return panes.Terminal.cursorLines(p, pane); + return panes.terminal.cursorLines(p, pane); } pub fn paneByteAtDisplay(p: *Pardes, t: *Text, row: i32, from_raw: i32, display_col: i32) i32 { @@ -448,8 +448,8 @@ pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { if (comptime pdf_enabled) return pane.pdf.?.ensureText(p.pdf_gpa); unreachable; } - const lines = try panes.Terminal.cursorLines(p, pane); - return panes.Terminal.flatSurface(p, pane, lines); + const lines = try panes.terminal.cursorLines(p, pane); + return panes.terminal.flatSurface(p, pane, lines); } pub fn paneWrapWidth(p: *const Pardes, t: *Text) usize { @@ -474,7 +474,7 @@ fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText { const pane = t.pane() orelse return null; if (pane.file) |f| return .{ .text = f.content, .row0 = 0 }; if (pane.image != null or pane.hasPdf()) return null; - return panes.Terminal.editText(p, pane, lo, hi, col); + return panes.terminal.editText(p, pane, lo, hi, col); } fn editTextEol(p: *Pardes, t: *Text, b: Bounds) ?panes.EditText { @@ -535,7 +535,7 @@ pub fn setEditTextEnd(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor) }; t.last_edit = .{ .row = @as(i32, @intCast(end.row)) + row0, .col = @intCast(end.col) }; if (pane.file) |*f| return panes.File.setContent(p, f, new); - panes.Terminal.setEditText(p, pane, new); + panes.terminal.setEditText(p, pane, new); } /// Take a text an edit made that nothing keeps, holding it until the next @@ -2057,7 +2057,7 @@ pub fn pushUndo(p: *Pardes, t: *Text) void { } const pane = t.pane() orelse return; if (pane.file != null) return panes.File.pushUndo(p, pane); - panes.Terminal.pushUndo(p, pane); + panes.terminal.pushUndo(p, pane); } pub fn doUndo(p: *Pardes, t: *Text) void { @@ -2065,7 +2065,7 @@ pub fn doUndo(p: *Pardes, t: *Text) void { if (t.what != .body) return; const pane = t.pane() orelse return; if (pane.file != null) return panes.File.undo(p, pane); - panes.Terminal.undo(p, pane); + panes.terminal.undo(p, pane); } pub fn doRedo(p: *Pardes, t: *Text) void { @@ -2073,7 +2073,7 @@ pub fn doRedo(p: *Pardes, t: *Text) void { if (t.what != .body) return; const pane = t.pane() orelse return; if (pane.file != null) return panes.File.redo(p, pane); - panes.Terminal.redo(p, pane); + panes.terminal.redo(p, pane); } /// Undo or redo an edit of a text's own characters; stepping back past its diff --git a/src/exec.zig b/src/exec.zig index 2c42389c..221de105 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -42,11 +42,11 @@ pub fn takesCommandLine(p: *const Pardes, id: usize) bool { // idle, EMPTY prompt is typed at; otherwise a new pane runs the line. // (Text in pardes's own edit buffer is not the shell's yet: an exec of // it, or of anything, types only what it runs.) - if (panes.Terminal.promptInputReady(pane) and !panes.Terminal.promptInputEmpty(pane)) return false; + if (panes.terminal.promptInputReady(pane) and !panes.terminal.promptInputEmpty(pane)) return false; // A mounted shell sits behind sudo's process supervisor. Its OSC 133 // prompt marks identify input readiness; the launcher's executable is // not the shell executable used by the ordinary process heuristic. - if (pane.v9fs_on_spawn) return panes.Terminal.promptInputReady(pane); + if (pane.v9fs_on_spawn) return panes.terminal.promptInputReady(pane); return !p.hostTtyTaken(id); } @@ -111,7 +111,7 @@ pub fn pointerOperand(p: *Pardes, pane: *Pane, clicked: Pane.Sel) PointerOperand const visible = clicked.r0 - @as(i32, pane.tag_rows); const wrapped = pane.wrapAt(visible); const raw = pane.isTerminal() and pane.body.mode == .tty and clicked.r0 >= pane.tag_rows; - const row = if (raw) panes.Terminal.gridOffset(pane) + visible else wrapped.line; + const row = if (raw) panes.terminal.gridOffset(pane) + visible else wrapped.line; const raw_line = if (raw) modal.lineSlice(body_layer.bodyText(p, p.scratch.allocator(), pane) catch "", @intCast(@max(0, visible))) else ""; const col = if (raw) @as(i32, @intCast(panes.File.rawAtDisplay(raw_line, @intCast(@max(0, clicked.c0))))) @@ -143,7 +143,7 @@ pub fn pointerOperand(p: *Pardes, pane: *Pane, clicked: Pane.Sel) PointerOperand lo -|= span.prompt_bytes; hi -|= span.prompt_bytes; } else if (!span.raw_terminal and raw) { - const prefix = panes.Terminal.promptPrefixBytes(pane, row, raw_line); + const prefix = panes.terminal.promptPrefixBytes(pane, row, raw_line); lo += prefix; hi += prefix; } @@ -429,8 +429,8 @@ pub fn evictLonePristineTty(p: *Pardes, col: usize, keep_id: usize) void { const tt = p.panes[tty_id] orelse return; // No typing, cursor on the first prompt line, no scrollback: this is // the throwaway boot placeholder a document may replace. - if (tt.ovl != null or panes.Terminal.gridCursor(tt).y != 0 or - panes.Terminal.scrollbar(tt).total > tt.rows) return; + if (tt.ovl != null or panes.terminal.gridCursor(tt).y != 0 or + panes.terminal.scrollbar(tt).total > tt.rows) return; p.deinitPane(tt) catch |err| return p.reportError(tty_id, "close", err); layout.compute(p); // a just-stacked doc has no rect yet; absorb snaps to rows _ = layout.absorbVWeight(p, tty_id, null); @@ -588,7 +588,7 @@ pub fn sendToRepl(p: *Pardes, from: usize, to: usize, text: []const u8) void { var said: [128]u8 = undefined; return p.setMessage(from, std.fmt.bufPrint(&said, "Repl: {d} bytes is more than can be sent at once; send less", .{n}) catch "Repl: too long to send"); } - const pasted = panes.Terminal.bracketedPaste(dst); + const pasted = panes.terminal.bracketedPaste(dst); edit.typeToTty(p, to, dst, clean[0..n]); // A Python block whose last line is indented, or a bare header, is not // over at one Enter, pasted into 3.13's REPL or typed into the old one: @@ -611,7 +611,7 @@ pub fn sendToRepl(p: *Pardes, from: usize, to: usize, text: []const u8) void { dst.repl_enter_due_ns = clockNow(p) + repl_enter_wait_ns; } else for (0..enters) |_| p.emitWrite(to, "\r"); // Line by line, a blank line inside a Python block ends the block. - if (!panes.Terminal.bracketedPaste(dst) and !dst.repl_warned and (if (dst.repl) |r| r.lang == python_lang else false) and + if (!panes.terminal.bracketedPaste(dst) and !dst.repl_warned and (if (dst.repl) |r| r.lang == python_lang else false) and std.mem.indexOfScalar(u8, text, '\n') != null) { dst.repl_warned = true; @@ -671,9 +671,9 @@ pub fn executeFrom(p: *Pardes, id: usize, txt: []const u8, from_body: bool) ?usi return null; } if (!takesCommandLine(p, id)) return runCommand(p, id, cmd); - panes.Terminal.padOutputBelowEdits(p, id); - panes.Terminal.noteCommand(pane, cmd); - if (panes.Terminal.queuePendingCommand(pane, cmd) catch |err| { + panes.terminal.padOutputBelowEdits(p, id); + panes.terminal.noteCommand(pane, cmd); + if (panes.terminal.queuePendingCommand(pane, cmd) catch |err| { p.reportError(id, "queue command", err); return id; }) return id; @@ -733,8 +733,8 @@ fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { // saved cursor), mouse reports and bracketed paste off, the cursor // shown, colours reset. (Not DECSTR: ghostty's stream does not // implement it.) - if (panes.Terminal.onAlternateScreen(pane)) panes.Terminal.feedOutput(p, pane, "\x1b[?1049l"); - panes.Terminal.feedOutput(p, pane, "\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[?25h\x1b[0m"); + if (panes.terminal.onAlternateScreen(pane)) panes.terminal.feedOutput(p, pane, "\x1b[?1049l"); + panes.terminal.feedOutput(p, pane, "\x1b[?1000l\x1b[?1002l\x1b[?1003l\x1b[?1006l\x1b[?2004l\x1b[?25h\x1b[0m"); echoCommand(p, pane, line); p.emitSpawn(id, pane.serial, pane.cwdSlice()); noteRun(p, pane, "run", line); @@ -760,10 +760,10 @@ fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { fn echoCommand(p: *Pardes, pane: *Pane, line: []const u8) void { var buf: [2 * command_max + 8]u8 = undefined; var w = std.Io.Writer.fixed(&buf); - w.writeAll(if (panes.Terminal.gridCursor(pane).x != 0) "\r\n% " else "% ") catch {}; + w.writeAll(if (panes.terminal.gridCursor(pane).x != 0) "\r\n% " else "% ") catch {}; for (line) |c| (if (c == '\n') w.writeAll("\r\n") else w.writeByte(c)) catch {}; w.writeAll("\r\n") catch {}; - panes.Terminal.feedOutput(p, pane, w.buffered()); + panes.terminal.feedOutput(p, pane, w.buffered()); } /// `run ` or `exit ` in the log. @@ -788,8 +788,8 @@ pub fn commandDone(p: *Pardes, id: usize, status: ?u8) void { var buf: [16]u8 = undefined; const code = if (status) |n| std.fmt.bufPrint(&buf, "{d}", .{n}) catch "?" else "?"; var said: [32]u8 = undefined; - const lead = if (panes.Terminal.gridCursor(pane).x != 0) "\r\n" else ""; - panes.Terminal.feedOutput(p, pane, std.fmt.bufPrint(&said, "{s}exit {s}\r\n", .{ lead, code }) catch "exit ?\r\n"); + const lead = if (panes.terminal.gridCursor(pane).x != 0) "\r\n" else ""; + panes.terminal.feedOutput(p, pane, std.fmt.bufPrint(&said, "{s}exit {s}\r\n", .{ lead, code }) catch "exit ?\r\n"); noteRun(p, pane, "exit", code); p.needs_frame = true; } diff --git a/src/fs.zig b/src/fs.zig index a2e8daf8..fc3eb98f 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -57,7 +57,7 @@ const source_files = [_]Source{ .{ .path = "src/Output.zig", .contents = @embedFile("Output.zig") }, .{ .path = "src/mini.zig", .contents = @embedFile("mini.zig") }, .{ .path = "src/image.zig", .contents = @embedFile("image.zig") }, - .{ .path = "src/Terminal.zig", .contents = @embedFile("Terminal.zig") }, + .{ .path = "src/terminal.zig", .contents = @embedFile("terminal.zig") }, .{ .path = "src/pdf_view.zig", .contents = @embedFile("pdf_view.zig") }, .{ .path = "src/layout.zig", .contents = @embedFile("layout.zig") }, .{ .path = "src/fs.zig", .contents = @embedFile("fs.zig") }, diff --git a/src/host_io.zig b/src/host_io.zig index 9e3fbf79..e7be28cd 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -1293,7 +1293,7 @@ pub fn forkShell( var command: std.Io.Writer.Allocating = .init(c.gpa); defer command.deinit(); try @import("linux/v9fs.zig").writeLaunchCommand(&command.writer, path, std.mem.span(socket), &spawn.argv); - if (!try pardes.panes.Terminal.queuePendingCommand(pn, command.written())) return error.ShellAlreadyStarted; + if (!try pardes.panes.terminal.queuePendingCommand(pn, command.written())) return error.ShellAlreadyStarted; } // Built here and not after the fork: between fork and exec the child may // not call setenv, whose malloc can deadlock against a pty reader thread diff --git a/src/layout.zig b/src/layout.zig index 28f567bc..28f3d270 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -607,7 +607,7 @@ fn blankRows(p: *const Pardes, id: usize) u16 { // The empty line after a final newline shows nothing. (panes.File.nlines(p.gpa, f) -| @intFromBool(std.mem.endsWith(u8, f.content, "\n"))) -| f.scroll else if (pane.isTerminal()) - @as(usize, panes.Terminal.gridCursor(pane).y) + 1 + @as(usize, panes.terminal.gridCursor(pane).y) + 1 else rows; return rows -| @as(u16, @intCast(@min(used, rows))); @@ -742,7 +742,7 @@ pub fn splitBelow(p: *Pardes, src_id: usize, nw: *Pane) void { // Its tag may wrap to more than one row: the rows under it are its body. const tag_h = @max(BOX_H, src.tag_rows); const body: u16 = if (src_h > tag_h) src_h - tag_h else 1; - const cur: u16 = if (!src.isTerminal()) body / 2 else panes.Terminal.gridCursor(src).y + 1; + const cur: u16 = if (!src.isTerminal()) body / 2 else panes.terminal.gridCursor(src).y + 1; // cap keep so a content-full source still leaves the new pane a tag + // a few body rows (an Alt-n from a full shell was born 0 rows tall) // ...and the source min_body_rows of its own (exec.placeNew), when it diff --git a/src/mouse.zig b/src/mouse.zig index 1f2648b0..cb0378de 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -821,7 +821,7 @@ fn mirrorTtySelection(p: *Pardes, pane: *Pane) void { const forward = gesture.r1 > gesture.r0 or (gesture.r1 == gesture.r0 and gesture.c1 >= gesture.c0); const endpoint = rows[if (forward) rows.len - 1 else 0]; const body = body_layer.bodyText(p, p.scratch.allocator(), pane) catch return; - const line = modal.lineSlice(body, @intCast(@max(0, endpoint.row - panes.Terminal.gridOffset(pane)))); + const line = modal.lineSlice(body, @intCast(@max(0, endpoint.row - panes.terminal.gridOffset(pane)))); const byte = if (forward) modal.prevGrapheme(line, @min(endpoint.hi, line.len)) else endpoint.lo; pane.body.cur_row = pane.surfRow(endpoint.row); var shown = std.mem.trimEnd(u8, line[@min(endpoint.prompt_bytes, line.len)..], " \t"); @@ -1137,11 +1137,11 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { if (cut) return; const y = p.registers.text(p.gpa, pardes.Registers.default) orelse return; if (y.len == 0) return; - if (panes.Terminal.reportsMouse(pane)) { + if (panes.terminal.reportsMouse(pane)) { const col: u16 = @intCast(std.math.clamp(pane.sel[sel_slot].c1 + 1, 1, 9999)); const row: u16 = @intCast(std.math.clamp(pane.sel[sel_slot].r1 - @as(i32, pane.tag_rows) + 1, 1, 9999)); var mb: [32]u8 = undefined; - if (panes.Terminal.mouseFormatSgr(pane)) { + if (panes.terminal.mouseFormatSgr(pane)) { p.emitWrite(s.id, std.fmt.bufPrint(&mb, "\x1b[<0;{d};{d}M\x1b[<0;{d};{d}m", .{ col, row, col, row }) catch return); } else { // ponytail: legacy X10 bytes; add utf8/urxvt formats if an app ever wants them diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 5bf354eb..060e0d6c 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -344,7 +344,7 @@ pub fn paneText(p: *Pardes, pane: *Pane, buf: []u8) []const u8 { pane.serial, pane_files.tagOf(p, pane).len, // A terminal's body is its history, read whole on an open's first read. - if (pane.isTerminal()) panes.Terminal.screenTextLen(pane) else pane_files.bodyOf(pane).len, + if (pane.isTerminal()) panes.terminal.screenTextLen(pane) else pane_files.bodyOf(pane).len, @as(u32, 0), @intFromBool(pane_files.dirtyOf(pane)), pane.cols, diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 3c1e181e..3fad1fae 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -258,7 +258,7 @@ pub fn fileSize(p: *Pardes, id: usize, f: PaneFile) u64 { const pf = &pane.fs; return switch (f) { // A terminal's body reads its screen and history, as text. - .body => if (pane.file == null and pane.isTerminal()) panes.Terminal.screenTextLen(pane) else if (pdfText(p, pane)) |t| t.len else bodyOf(pane).len, + .body => if (pane.file == null and pane.isTerminal()) panes.terminal.screenTextLen(pane) else if (pdfText(p, pane)) |t| t.len else bodyOf(pane).len, .data, .xdata => bodyOf(pane).len, .tag => tagOf(p, pane).len, .name => nameOf(pane).len + 1, @@ -399,7 +399,7 @@ fn readBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { return tree.stagedReply(p, req); } if (req.handle != 0 and pane.isTerminal()) return screen.readSnapshot(p, req, pane); - const text = panes.Terminal.screenTextAlloc(pane, p.gpa) catch + const text = panes.terminal.screenTextAlloc(pane, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); defer p.gpa.free(text); const out = p.fs.stage(p.gpa); diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index 8ba9f4df..0f5202cc 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -139,9 +139,9 @@ pub fn readStatus(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { // or a line is typed at the prompt. Before the shell's first prompt a // run waits for it rather than answer busy, so that is not busy. // A build with no terminal panes (the board) has no marks to read. - const marks = if (comptime !pardes.panes.Terminal.enabled) null else if (pane.terminal) |state| &state.stream.handler else null; + const marks = if (comptime !pardes.panes.terminal.enabled) null else if (pane.terminal) |state| &state.stream.handler else null; const busy = p.hostTtyTaken(id) or (!pane.fs.unmarked and (waitingRun(p, pane) != null or - (if (marks) |m| m.prompts > 0 and (m.phase != .input or !pardes.panes.Terminal.promptInputEmpty(pane)) else false))); + (if (marks) |m| m.prompts > 0 and (m.phase != .input or !pardes.panes.terminal.promptInputEmpty(pane)) else false))); const out = p.fs.stage(p.gpa); const size = winsize(pane); out.print(p.gpa, "{d:>11} {d:>11} {d:>11}\n", .{ size[0], size[1], @intFromBool(busy) }) catch {}; @@ -222,7 +222,7 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { if (std.mem.trim(u8, line, " \t").len == 0) return tree.failText(req.tag, E.INVAL, e_bad_line); if (line.len == 0) return tree.failText(req.tag, E.INVAL, e_bad_line); for (line) |c| if (c < ' ' and c != '\t') return tree.failText(req.tag, E.INVAL, e_bad_line); - if (comptime !pardes.panes.Terminal.enabled) return tree.failText(req.tag, E.INVAL, e_bad_line); + if (comptime !pardes.panes.terminal.enabled) return tree.failText(req.tag, E.INVAL, e_bad_line); const pf = &pane.fs; const state = pane.terminal orelse return tree.failText(req.tag, E.INVAL, e_bad_line); const marks = &state.stream.handler; @@ -235,7 +235,7 @@ pub fn writeRun(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { } else if (pf.unmarked) { answer(p, slot, "error no prompt marks", .{}); } else if (waitingRun(p, pane) != null or (marks.prompts > 0 and (marks.phase != .input or - !pardes.panes.Terminal.promptInputEmpty(pane) or p.hostTtyTaken(id)))) + !pardes.panes.terminal.promptInputEmpty(pane) or p.hostTtyTaken(id)))) { // Something is running or someone has typed at the prompt: sending // now would type into the middle of it. The phase is pardes's own @@ -288,7 +288,7 @@ pub fn readRun(p: *Pardes, req: Req) Reply { /// for the prompt means whoever reads the answer can send the next command /// at once instead of finding the shell still drawing it. pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { - if (comptime !pardes.panes.Terminal.enabled) return; + if (comptime !pardes.panes.terminal.enabled) return; const state = pane.terminal orelse return; const pf = &pane.fs; const slot = waitingRun(p, pane) orelse return; @@ -299,13 +299,13 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { pf.run = null; return; } - if (marks.phase != .input or !pardes.panes.Terminal.promptInputEmpty(pane) or p.hostTtyTaken(id)) return; + if (marks.phase != .input or !pardes.panes.terminal.promptInputEmpty(pane) or p.hostTtyTaken(id)) return; slot.want = marks.started +% 1; slot.prompts = marks.prompts; slot.declined = marks.declined; p.emitWrite(id, slot.line); p.emitWrite(id, "\r"); - pardes.panes.Terminal.noteCommand(pane, slot.line); + pardes.panes.terminal.noteCommand(pane, slot.line); slot.phase = .sent; return; } @@ -319,7 +319,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { // typed into an empty prompt, so throw it away with Ctrl-C, which // drops the whole pending command, and answer at the prompt after // that, so the next line finds the shell clear. - const empty = pardes.panes.Terminal.promptInputEmpty(pane); + const empty = pardes.panes.terminal.promptInputEmpty(pane); switch (slot.cleared) { .no => { if (marks.continuation) { @@ -360,7 +360,7 @@ pub fn noteMarks(p: *Pardes, id: usize, pane: *Pane) void { /// Answers a run whose command ended with `status`: the header and the /// output it printed. fn finish(p: *Pardes, slot: *Run, pane: *Pane, status_code: ?i32) void { - const printed = pardes.panes.Terminal.commandOutput(pane, p.gpa, output_rows) catch + const printed = pardes.panes.terminal.commandOutput(pane, p.gpa, output_rows) catch return answer(p, slot, "error out of memory", .{}); defer p.gpa.free(printed.text); // Keep the tail, cut at a line start so the first line kept is whole. @@ -400,7 +400,7 @@ pub fn shellExited(p: *Pardes, pane: *Pane, status: ?u8) void { const code = status orelse return; if (waitingRun(p, pane)) |slot| if (slot.phase == .sent) { pane.fs.run = null; - pardes.panes.Terminal.endOutputHere(pane); + pardes.panes.terminal.endOutputHere(pane); finish(p, slot, pane, code); }; var buf: [4]u8 = undefined; @@ -963,10 +963,10 @@ test "a run's answer says cut when its output's start is gone, and reads a bound // A resize between its start and end reflows the pins with the text. h = sh.send(p, node); sh.put(p, c ++ "one\r\ntwo\r\n"); - pardes.panes.Terminal.resizeGrid(pane, gpa, 50, 20); + pardes.panes.terminal.resizeGrid(pane, gpa, 50, 20); sh.put(p, d ++ prompt); try testing.expectEqualStrings("exit 0\none\ntwo\n", sh.answered(p, node, h, into)); - pardes.panes.Terminal.resizeGrid(pane, gpa, pane.cols, pane.rows); + pardes.panes.terminal.resizeGrid(pane, gpa, pane.cols, pane.rows); // A full-screen program leaves nothing on the primary screen, and a D // with no status is not a success. diff --git a/src/ninep/screen.zig b/src/ninep/screen.zig index f496da03..b991c3e4 100644 --- a/src/ninep/screen.zig +++ b/src/ninep/screen.zig @@ -47,7 +47,7 @@ pub fn readSnapshot(p: *Pardes, req: Req, pane: ?*Pane) Reply { const snapshot = &(tree.openOf(p, req) orelse return Reply.fail(req.tag, E.INVAL)).what.snapshot; if (snapshot.* == null) { const terminal = pane orelse return Reply.fail(req.tag, E.INVAL); - snapshot.* = panes.Terminal.screenTextAlloc(terminal, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); + snapshot.* = panes.terminal.screenTextAlloc(terminal, p.gpa) catch return Reply.fail(req.tag, E.NOMEM); } const bytes = snapshot.*.?; const off = @min(req.off, bytes.len); @@ -129,7 +129,7 @@ test "terminal body handles keep one history snapshot across fragmented reads" { const node = Node.of(serialOf(p), .body); p.update(.{ .output = .{ .pane = 0, .bytes = "old caf\xc3\xa9\r\nold tail" } }); while (p.nextEffect()) |_| {} - const original = try panes.Terminal.screenTextAlloc(p.panes[0].?, gpa); + const original = try panes.terminal.screenTextAlloc(p.panes[0].?, gpa); defer gpa.free(original); const opened = call(p, .{ .tag = 1, .op = .open, .node = node }); try testing.expectEqual(Status.ok, opened.reply.status); diff --git a/src/panes.zig b/src/panes.zig index b6fdc31a..0380f89f 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -89,7 +89,7 @@ pub const Pane = struct { pub const Cwd = union(enum) { none, inherited: *Pane, owned: []u8 }; pub const Focus = enum { body, tag }; - terminal: ?*Terminal.State = null, + terminal: ?*terminal.State = null, gpa: std.mem.Allocator, serial: u32 = 0, /// What the control filesystem keeps of this pane -- addr and limit, the @@ -116,7 +116,7 @@ pub const Pane = struct { /// A shell has run in it (Pardes.acknowledgeShell): a Tty whose first /// shell fails to start closes, one started again keeps its pane. had_shell: bool = false, - pending_command: Terminal.PendingCommand = .{}, + pending_command: terminal.PendingCommand = .{}, /// The last command line pardes typed into this terminal (an exec, a /// middle click, a pty/run): its first word, which Kill matches, and /// the shell's command count its start (C mark) reaches. @@ -227,7 +227,7 @@ pub const Pane = struct { next_pointer_selection: u64 = 0, /// terminals only: the typed-text buffer standing in for shell rows - ovl: ?Terminal.EditBuffer = null, + ovl: ?terminal.EditBuffer = null, tty_filter: bool = false, msg: [256]u8 = undefined, msg_len: u16 = 0, @@ -486,7 +486,7 @@ pub const Pane = struct { pub fn scroll(pane: *Pane) i32 { if (pane.file) |f| return @intCast(f.scroll); if (comptime Pdf.enabled) if (pane.pdf) |pv| return @intCast(pv.text_scroll); - return pane.surfRow(Terminal.gridOffset(pane)); + return pane.surfRow(terminal.gridOffset(pane)); } pub fn wrapAt(pane: *Pane, vr: i32) struct { line: i32, at: i32 } { @@ -531,8 +531,8 @@ pub const Pane = struct { } } else { // the vt scrolls in SHELL rows; convert through the edit buffer - const off = Terminal.gridOffset(pane); - Terminal.scrollGrid(pane, pane.gridRow(pane.surfRow(off) + delta) - off); + const off = terminal.gridOffset(pane); + terminal.scrollGrid(pane, pane.gridRow(pane.surfRow(off) + delta) - off); } } @@ -611,8 +611,8 @@ pub const Pane = struct { pane.body.cur_row = pane.scroll(); pane.body.cur_col = 0; } else { - const cur = Terminal.gridCursor(pane); - pane.body.cur_row = pane.surfRow(@as(i32, cur.y) + Terminal.gridOffset(pane)); + const cur = terminal.gridCursor(pane); + pane.body.cur_row = pane.surfRow(@as(i32, cur.y) + terminal.gridOffset(pane)); pane.body.cur_col = @intCast(cur.x); } pane.body.cur_pinned = true; @@ -642,7 +642,7 @@ pub const Image = @import("image.zig"); pub const Pdf = @import("pdf_view.zig"); -pub const Terminal = @import("Terminal.zig"); +pub const terminal = @import("terminal.zig"); test { _ = Pane; @@ -652,5 +652,5 @@ test { _ = mini; _ = Image; _ = Pdf; - _ = Terminal; + _ = terminal; } diff --git a/src/pardes.zig b/src/pardes.zig index 141b214e..623af3c9 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -1195,9 +1195,9 @@ test "Tty9p marks only the new Linux terminal for a mounted shell" { try std.testing.expect(pane.v9fs_on_spawn); try std.testing.expect(!pane.greet); try std.testing.expect(!exec.takesCommandLine(p, p.active)); - panes.Terminal.feedOutput(p, pane, "\x1b]133;A\x07$ \x1b]133;B\x07"); + panes.terminal.feedOutput(p, pane, "\x1b]133;A\x07$ \x1b]133;B\x07"); try std.testing.expect(exec.takesCommandLine(p, p.active)); - panes.Terminal.feedOutput(p, pane, "\x1b]133;C\x07"); + panes.terminal.feedOutput(p, pane, "\x1b]133;C\x07"); try std.testing.expect(!exec.takesCommandLine(p, p.active)); } @@ -1558,7 +1558,7 @@ test "a command of several lines keeps its tag one row, and its echo does not st _ = exec.execute(p, 1, two); while (p.nextEffect()) |_| {} _ = try p.render(frame.allocator()); - const body = try panes.Terminal.screenTextAlloc(pane, gpa); + const body = try panes.terminal.screenTextAlloc(pane, gpa); defer gpa.free(body); try std.testing.expect(std.mem.indexOf(u8, body, "% def greet(name):\n return name") != null); } @@ -1878,7 +1878,7 @@ test "a command pane shows how its command ended, and the next command there run const pane = p.panes[dst].?; // Its first command is echoed as every later one is. { - const first = try panes.Terminal.screenTextAlloc(pane, gpa); + const first = try panes.terminal.screenTextAlloc(pane, gpa); defer gpa.free(first); try std.testing.expect(std.mem.startsWith(u8, first, "% make -j8")); } @@ -1909,16 +1909,16 @@ test "a command pane shows how its command ended, and the next command there run // A program that crashed out of its full screen leaves the emulator // in its modes; the next command starts clear of them. p.update(.{ .output = .{ .pane = @intCast(dst), .bytes = "\x1b[?1049h\x1b[?2004h\x1b[?1000h" } }); - try std.testing.expect(panes.Terminal.bracketedPaste(pane)); + try std.testing.expect(panes.terminal.bracketedPaste(pane)); // Done, the directory's next command runs there, below what it showed. try std.testing.expectEqual(@as(?usize, dst), exec.execute(p, 1, "make test")); - try std.testing.expect(!panes.Terminal.bracketedPaste(pane)); + try std.testing.expect(!panes.terminal.bracketedPaste(pane)); var respawned = false; while (p.nextEffect()) |effect| if (effect == .spawn and effect.spawn.pane == dst) { respawned = true; }; try std.testing.expect(respawned); - const body = try panes.Terminal.screenTextAlloc(pane, gpa); + const body = try panes.terminal.screenTextAlloc(pane, gpa); defer gpa.free(body); const said = std.mem.indexOf(u8, body, "compiled") orelse return error.OutputLost; const ended = std.mem.indexOf(u8, body, "exit 2") orelse return error.ExitLost; @@ -4394,7 +4394,7 @@ pub const Pardes = struct { settings: config.Runtime = .{ .font = .{ .tagline_percent = config.gui_tagline_font_percent } }, locations_config: locations.Config = .{}, locations_cache: locations.Cache = .{}, - tty_filter_palette: panes.Terminal.FilterPalette = .{}, + tty_filter_palette: panes.terminal.FilterPalette = .{}, font_request_taken: bool = false, custom_theme: ?Theme = null, /// bodyChrome's: the theme it was worked out for, and it. @@ -4580,8 +4580,8 @@ pub const Pardes = struct { /// that still own their loop pass their own arena to `render` instead. frame_arena: std.heap.ArenaAllocator, /// the terminal motion surface, memoized against the pane it was built - /// for — see panes.Terminal.RowsCache for the lifetime rule - shell_rows: panes.Terminal.RowsCache = .{}, + /// for — see panes.terminal.RowsCache for the lifetime rule + shell_rows: panes.terminal.RowsCache = .{}, /// The message row's entry points, called from everywhere as /// `p.setMessage(...)`; they live with the rest of it in Messages.zig. @@ -4944,7 +4944,7 @@ pub const Pardes = struct { } p.shell_rows.dropPane(pane); for (0..pane.pointer_selections.len) |slot| pane.clearPointerSelection(slot); - panes.Terminal.deinitPendingCommand(pane); + panes.terminal.deinitPendingCommand(pane); if (pane.command) |line| p.gpa.free(line); if (pane.shell) |bin| p.gpa.free(bin); if (pane.image) |*iv| { @@ -4957,7 +4957,7 @@ pub const Pardes = struct { pane.tag.deinit(p.gpa); pane.input.deinit(p.gpa); pane.jump.deinit(p.gpa); - panes.Terminal.deinitEmulator(pane, p.gpa); + panes.terminal.deinitEmulator(pane, p.gpa); pane.clearCwd(); pane.fs.deinit(p.gpa); p.gpa.destroy(pane); @@ -4986,12 +4986,12 @@ pub const Pardes = struct { pub fn newShell(p: *Pardes, id: usize, cwd: []const u8) !*Pane { std.debug.assert(p.panes[id] == null); if (cwd.len > limits.host_path_cap) return error.PathTooLong; - const pane = try panes.Terminal.create(p.gpa, p.screen_w, p.screen_h); + const pane = try panes.terminal.create(p.gpa, p.screen_w, p.screen_h); // Named by the directory it is started in from the first, so the // shell saying it is there is no rename (`new N /` then `rename`); // out of memory for it, the shell names it when it says. if (cwd.len > 0) pane.setOwnedCwd(cwd) catch {}; - panes.Terminal.armShellSpawn(pane); + panes.terminal.armShellSpawn(pane); p.installPane(id, pane); p.emitSpawn(id, pane.serial, cwd); return pane; @@ -5017,7 +5017,7 @@ pub const Pardes = struct { if (cwd.len > limits.host_path_cap) return error.PathTooLong; const owned = try p.gpa.dupe(u8, line); errdefer p.gpa.free(owned); - const pane = try panes.Terminal.create(p.gpa, p.screen_w, p.screen_h); + const pane = try panes.terminal.create(p.gpa, p.screen_w, p.screen_h); pane.command = owned; pane.command_pty = true; pane.body.mode = .tty; @@ -5031,7 +5031,7 @@ pub const Pardes = struct { pub fn newDocPane(p: *Pardes, id: usize) !*Pane { std.debug.assert(p.panes[id] == null); - const pane = try panes.Terminal.createDoc(p.gpa, p.screen_w, p.screen_h); + const pane = try panes.terminal.createDoc(p.gpa, p.screen_w, p.screen_h); p.installPane(id, pane); return pane; } @@ -5223,7 +5223,7 @@ pub const Pardes = struct { } else |_| {} } }; - if (id < MAX_PANES) panes.Terminal.shellSpawned(p, id, prompt_marks); + if (id < MAX_PANES) panes.terminal.shellSpawned(p, id, prompt_marks); if (p.settings.shell.effective.set(executable)) p.settings.shell.pending = false; } @@ -5358,7 +5358,7 @@ pub const Pardes = struct { /// The pane a session word runs with in an empty window. pub fn standIn(p: *Pardes) ?*Pane { - if (p.stand_in == null) p.stand_in = panes.Terminal.createDoc(p.gpa, p.screen_w, p.screen_h) catch null; + if (p.stand_in == null) p.stand_in = panes.terminal.createDoc(p.gpa, p.screen_w, p.screen_h) catch null; return p.stand_in; } @@ -5627,7 +5627,7 @@ pub const Pardes = struct { return; } if (!pane.isTerminal()) return; - const text = panes.Terminal.screenTextAlloc(pane, p.gpa) catch return; + const text = panes.terminal.screenTextAlloc(pane, p.gpa) catch return; defer p.gpa.free(text); p.hostWriteFile(st.pane, st.path.slice(), text); }, @@ -5839,7 +5839,7 @@ pub const Pardes = struct { const pane = p.panes[o.pane] orelse return; pane.shell_spoke = true; ctlfs.events.notePtyOutput(p, o.pane, o.bytes); - panes.Terminal.feedOutput(p, pane, o.bytes); + panes.terminal.feedOutput(p, pane, o.bytes); ctlfs.pty.noteMarks(p, o.pane, pane); exec.flushReplEnter(p, o.pane, true); }, @@ -5944,7 +5944,7 @@ pub const Pardes = struct { .normal => edit.enterInsert(p, &pane.body, .at, 1), .insert => { edit.exitInsert(p, &pane.body); - if (pane.isTerminal()) panes.Terminal.enterTty(p, id); + if (pane.isTerminal()) panes.terminal.enterTty(p, id); }, } } @@ -5960,7 +5960,7 @@ pub const Pardes = struct { if (pane.body.mode == .tty) { pane.body.mode = .normal; pane.body.normal.clear(); - } else panes.Terminal.enterTty(p, id); + } else panes.terminal.enterTty(p, id); } /// Type `keys` again (a macro, `.`): through the modal handling as @@ -6079,7 +6079,7 @@ pub const Pardes = struct { return exec.runBuiltin(p, .Last, p.active, "", null); if (key.cp == Key.escape and !key.ctrl and !key.alt and !key.shift and exec.takesCommandLine(p, p.active)) return exec.runBuiltin(p, .Last, p.active, "", null); - panes.Terminal.followOutput(pane); // typing snaps back to live output + panes.terminal.followOutput(pane); // typing snaps back to live output // Paste stays the window's, the one exception to forwarding a raw // tty's keys: Ctrl-V types the register at the program and // Ctrl-Shift-V asks the desktop for its clipboard first. Forwarded, @@ -6094,7 +6094,7 @@ pub const Pardes = struct { // Ctrl-V a black hole in every full-screen application. if (p.registers.text(p.gpa, Registers.default)) |text| return edit.typeToTty(p, p.active, pane, text); } - return panes.Terminal.forwardKey(p, p.active, key); + return panes.terminal.forwardKey(p, p.active, key); } if (p.leader_on) return p.leaderKey(key); if (p.ctrl_w_pending) { @@ -6247,7 +6247,7 @@ pub const Pardes = struct { edit.exitInsert(p, t) else edit.handleInsert(p, t, key), - .tty => panes.Terminal.forwardKey(p, p.active, key), + .tty => panes.terminal.forwardKey(p, p.active, key), } // `.`'s log: the keys of the normal command that entered insert // mode, then everything typed until it is left @@ -6738,7 +6738,7 @@ pub const Pardes = struct { errdefer p.gpa.free(path); const history = try panes.File.History.create(p.gpa); errdefer p.gpa.destroy(history); - const pane = try panes.Terminal.createDoc(p.gpa, p.screen_w, p.screen_h); + const pane = try panes.terminal.createDoc(p.gpa, p.screen_w, p.screen_h); errdefer p.gpa.destroy(pane); try p.deinitPane(p.panes[0].?); p.panes[0] = null; @@ -7086,7 +7086,7 @@ pub const Pardes = struct { // doc panes have no pty/emulator grid to reflow; just record // the size so bodyText renders the right number of rows if (pane.isTerminal()) { - panes.Terminal.resizeGrid(pane, p.gpa, cols, rows); + panes.terminal.resizeGrid(pane, p.gpa, cols, rows); p.shell_rows.markStale(pane); // reflow moved every row p.emit(.{ .resize_pty = .{ .pane = @intCast(id), .cols = cols, .rows = rows } }); pane.fs.winsize = null; @@ -7095,12 +7095,12 @@ pub const Pardes = struct { pane.rows = rows; if (pane.file) |*file| file.syntax_dirty = true; } - panes.Terminal.releasePendingCommandIfReady(p, id, pane); + panes.terminal.releasePendingCommandIfReady(p, id, pane); // The greeting `ls` of a new terminal in a directory is typed at // its shell's FIRST prompt, or never: typed later it would land // in whatever runs then, or in the middle of a line someone - // typed (panes.Terminal.greeting). - if (pane.greet and pane.isTerminal() and p.resize_count > 0) switch (panes.Terminal.greeting(pane)) { + // typed (panes.terminal.greeting). + if (pane.greet and pane.isTerminal() and p.resize_count > 0) switch (panes.terminal.greeting(pane)) { .wait => {}, .never => pane.greet = false, .now => { @@ -7381,7 +7381,7 @@ test "argv naming nothing boots an errors pane rather than failing the launch" { } test "raw terminal cursor obeys visibility without hiding modal and tag cursors" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); @@ -7426,7 +7426,7 @@ test "raw terminal cursor obeys visibility without hiding modal and tag cursors" } test "raw terminal cursor follows its active row only while that row is visible" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; for ([_]bool{ false, true }) |tag_bottom| { const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); @@ -7445,13 +7445,13 @@ test "raw terminal cursor follows its active row only while that row is visible" try std.testing.expectEqual(rect.x + config.GUTTER + 3, live.x); try std.testing.expectEqual(body_y + 2, live.y); - panes.Terminal.scrollGrid(pane, -1); + panes.terminal.scrollGrid(pane, -1); const scrolled = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; try std.testing.expectEqual(live.x, scrolled.x); try std.testing.expectEqual(live.y + 1, scrolled.y); - panes.Terminal.scrollGrid(pane, -@as(i32, pane.rows)); + panes.terminal.scrollGrid(pane, -@as(i32, pane.rows)); try std.testing.expect((try p.render(frame.allocator())).cursor == null); - panes.Terminal.followOutput(pane); + panes.terminal.followOutput(pane); const returned = (try p.render(frame.allocator())).cursor orelse return error.MissingCursor; try std.testing.expectEqual(live.x, returned.x); try std.testing.expectEqual(live.y, returned.y); @@ -7895,31 +7895,31 @@ test "tty output follows only from the bottom" { p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); } p.sync(); - const bottom = panes.Terminal.scrollbar(sp).offset; + const bottom = panes.terminal.scrollbar(sp).offset; try std.testing.expect(bottom > 0); // Scrolled back, the reader stays put however much the shell prints. sp.scrollBy(-10); p.sync(); - const parked = panes.Terminal.scrollbar(sp).offset; + const parked = panes.terminal.scrollbar(sp).offset; try std.testing.expect(parked < bottom); for (60..70) |i| { var buf: [32]u8 = undefined; p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = std.fmt.bufPrint(&buf, "line {d}\r\n", .{i}) catch unreachable } }); } p.sync(); - try std.testing.expectEqual(parked, panes.Terminal.scrollbar(sp).offset); + try std.testing.expectEqual(parked, panes.terminal.scrollbar(sp).offset); // Typing snaps back to live output, so nobody types blind. p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); p.sync(); - try std.testing.expect(panes.Terminal.scrollbar(sp).offset > parked); + try std.testing.expect(panes.terminal.scrollbar(sp).offset > parked); // ...and from there output follows again. - const live = panes.Terminal.scrollbar(sp).offset; + const live = panes.terminal.scrollbar(sp).offset; p.update(.{ .output = .{ .pane = @intCast(shell), .bytes = "tail\r\n" } }); p.sync(); - try std.testing.expect(panes.Terminal.scrollbar(sp).offset > live); + try std.testing.expect(panes.terminal.scrollbar(sp).offset > live); } test "Esc back into a file leaves its view where it was" { @@ -8135,7 +8135,7 @@ test "an unasked desktop paste reaches a tty pane's program, not its buffer" { _ = drainWrites(p, &buf); const pane = p.panes[0].?; - panes.Terminal.enterTty(p, 0); + panes.terminal.enterTty(p, 0); // No request behind it: the window manager's own paste, or SDL answering a // Ctrl-Shift-V the desktop handled. It still has to reach the shell. p.update(.{ .paste = "ls -la" }); @@ -8153,7 +8153,7 @@ test "a paste larger than the effect ring reaches the program whole and in order const buf = try gpa.alloc(u8, 1 << 20); defer gpa.free(buf); _ = drainWrites(p, buf); - panes.Terminal.enterTty(p, 0); + panes.terminal.enterTty(p, 0); const text = try gpa.alloc(u8, 300 * 1024); defer gpa.free(text); @@ -8166,7 +8166,7 @@ test "a paste larger than the effect ring reaches the program whole and in order test "a bracketed paste larger than the ring still closes its bracket" { if (platform == .web) return; - if (comptime !panes.Terminal.enabled) return; + if (comptime !panes.terminal.enabled) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -8174,10 +8174,10 @@ test "a bracketed paste larger than the ring still closes its bracket" { const buf = try gpa.alloc(u8, 1 << 20); defer gpa.free(buf); _ = drainWrites(p, buf); - panes.Terminal.enterTty(p, 0); + panes.terminal.enterTty(p, 0); p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h" } }); - try std.testing.expect(panes.Terminal.bracketedPaste(p.panes[0].?)); + try std.testing.expect(panes.terminal.bracketedPaste(p.panes[0].?)); const text = try gpa.alloc(u8, 300 * 1024); defer gpa.free(text); @memset(text, 'z'); @@ -8197,7 +8197,7 @@ test "pasted bytes still queued at shutdown are freed, not leaked" { const buf = try gpa.alloc(u8, 1 << 20); defer gpa.free(buf); _ = drainWrites(p, buf); - panes.Terminal.enterTty(p, 0); + panes.terminal.enterTty(p, 0); const text = try gpa.alloc(u8, 300 * 1024); defer gpa.free(text); @@ -8227,14 +8227,14 @@ test "leaving tty hides the prompt and keeps the command typed at it" { const rowOf = struct { fn at(pp: *Pardes, pane: *Pane, needle: []const u8) ?[]const u8 { - const rows = panes.Terminal.shellRows(pp, pane) catch return null; + const rows = panes.terminal.shellRows(pp, pane) catch return null; for (rows) |r| if (std.mem.indexOf(u8, r, needle) != null) return r; return null; } }.at; const bodyRowOf = struct { fn at(pp: *Pardes, pane: *Pane, needle: []const u8) ?[]const u8 { - const body = panes.Terminal.bodyText(pp.scratch.allocator(), pane) catch return null; + const body = panes.terminal.bodyText(pp.scratch.allocator(), pane) catch return null; var it = std.mem.splitScalar(u8, body, '\n'); while (it.next()) |r| if (std.mem.indexOf(u8, r, needle) != null) return r; return null; @@ -8290,7 +8290,7 @@ test "entering tty walks the shell cursor to the column clicked past the prompt" p.shell_rows.stale = true; // The command shows LEFT-HUGGED, so its column 3 is the '3'... - const rows = try panes.Terminal.shellRows(p, sp); + const rows = try panes.terminal.shellRows(p, sp); var row: i32 = 0; const at = for (rows, 0..) |r, i| { if (std.mem.indexOf(u8, r, "0123456789") != null) break i; @@ -8304,7 +8304,7 @@ test "entering tty walks the shell cursor to the column clicked past the prompt" sp.body.cur_col = 3; sp.body.cur_pinned = true; while (p.nextEffect()) |_| {} - panes.Terminal.enterTty(p, shell); + panes.terminal.enterTty(p, shell); // The walk is arrow keys the shell understands. Seven lefts: readline's // cursor sits past the '9' and the click was on the '3'. @@ -8347,7 +8347,7 @@ test "board heap: every inline ring the board pays for still fits its budget" { const effect_ring = 128 * @sizeOf(Effect); // ...and the undo history, the largest in `Pane` once the terminal is out: // 16 snapshots on the board against 256 on a desktop. - const undo_history = 2 * 16 * @sizeOf(panes.Terminal.Snapshot); + const undo_history = 2 * 16 * @sizeOf(panes.terminal.Snapshot); const grid = @as(usize, board_cols) * board_rows * (2 * @sizeOf(Cell) + @sizeOf(PanelCellDiff)); // Each of the three separately, so a failure names the one that grew @@ -8475,7 +8475,7 @@ test "jump history terminal rectangle follows output and clears on reflow" { try std.testing.expectEqualStrings("alpha", try edit.selectionText(p, pane, pane.sel[0])); for (0..40) |_| p.update(.{ .output = .{ .pane = 0, .bytes = "more output\r\n" } }); try std.testing.expectEqualStrings("alpha", try edit.selectionText(p, pane, pane.sel[0])); - panes.Terminal.resizeGrid(pane, p.gpa, pane.cols - 1, pane.rows); + panes.terminal.resizeGrid(pane, p.gpa, pane.cols - 1, pane.rows); try std.testing.expect(pane.pointerSelection(pane.sel[0]) == null); try std.testing.expectEqual(.none, pane.sel[0].state); } diff --git a/src/terminal.zig b/src/terminal.zig new file mode 100644 index 00000000..c99a92a6 --- /dev/null +++ b/src/terminal.zig @@ -0,0 +1,2670 @@ +//! A terminal pane: its VT emulator and replay, prompt rows, the edit overlay +//! typed over shell rows, and the Filter that recolours output to the theme. +const panes = @import("panes.zig"); +const std = @import("std"); +const pardes = @import("pardes.zig"); +const config = @import("config.zig"); +const Pardes = pardes.Pardes; +const Surface = pardes.Surface; +const modal = @import("modal.zig"); +const tracy = @import("tracy.zig"); +const dump = @import("dump.zig"); +const Key = pardes.Key; +const Pane = panes.Pane; +const EditText = panes.EditText; +const File = panes.File; + +pub const enabled = pardes.terminal_panes; +const ghostty_vt = if (enabled) @import("ghostty-vt") else struct {}; + +pub const history_max = if (enabled) 64 else 8; + +pub const VtSlot = if (enabled) ghostty_vt.Terminal else void; +pub const StreamSlot = if (enabled) ghostty_vt.Stream(MarkedHandler) else void; + +/// The `aid` pardes's injected bash and fish marks carry (host_io.zig). +pub const prompt_aid = "pardes"; + +/// ghostty's handler, plus where the shell is in its command cycle as +/// its OSC 133 marks tell it: ghostty parses D's exit status and drops +/// it, and /pane//pty/run waits on exactly that. Only marks carrying +/// pardes's own `aid` move it, so fish's native marks, a nested shell's +/// and a stray `133;D` in some file being printed all pass it by. +pub const MarkedHandler = if (enabled) struct { + inner: ghostty_vt.TerminalStream.Handler, + phase: enum { none, prompt, input, running } = .none, + /// Counts commands started (C at the input phase). + started: u32 = 0, + /// Counts prompts drawn (B), so a line the shell refused without + /// running (a fish syntax error: no C, no D, a new prompt) shows. + prompts: u32 = 0, + /// D marks outside a running command: the shell handled a line + /// without starting it (bash on a syntax error prints no C). + declined: u32 = 0, + /// The newest prompt continues an unfinished line (bash's PS2, marked + /// `k=c`): the shell still holds the start of the command. + continuation: bool = false, + /// Where the newest command's output began (its C) and ended (its + /// D) on the primary screen, pinned so scrolling keeps them. + out_start: ?*ghostty_vt.Pin = null, + out_end: ?*ghostty_vt.Pin = null, + /// The running command's output was erased under it -- a clear, ED 3, + /// a reset -- so the pins no longer span what it printed: ED 3 moves + /// a pin to the next page without flagging it `garbage` + /// (PageList.erasePage). + lost: bool = false, + + /// The newest command to end: which one, and its status if given. + finished: ?struct { seq: u32, status: ?i32 } = null, + + const Action = ghostty_vt.TerminalStream.Action; + + /// Move one of the output pins to the cursor. Only the primary screen + /// is pinned: a command's own full-screen display is not its output. + fn pinCursor(self: *@This(), slot: *?*ghostty_vt.Pin, now: bool) void { + const screen = self.inner.terminal.screens.get(.primary) orelse return; + if (slot.*) |old| screen.pages.untrackPin(old); + slot.* = null; + if (!now or self.inner.terminal.screens.active_key != .primary) return; + slot.* = screen.pages.trackPin(screen.cursor.page_pin.*) catch null; + } + + pub fn vt(self: *@This(), comptime action: Action.Tag, value: Action.Value(action)) void { + if (comptime action == .semantic_prompt) mark: { + const aid = value.readOption(.aid) orelse break :mark; + if (!std.mem.eql(u8, aid, prompt_aid)) break :mark; + switch (value.action) { + .fresh_line_new_prompt => { + self.phase = .prompt; + self.continuation = value.readOption(.prompt_kind) == .continuation; + }, + .end_prompt_start_input => { + self.phase = .input; + self.prompts +%= 1; + }, + // bash's DEBUG trap also fires on its own PROMPT_COMMAND, + // outside the input phase; only a C that ends input counts + .end_input_start_output => if (self.phase == .input) { + self.phase = .running; + self.started +%= 1; + self.lost = false; + self.pinCursor(&self.out_start, true); + self.pinCursor(&self.out_end, false); + }, + .end_command => if (self.phase == .running) { + self.phase = .none; + self.finished = .{ .seq = self.started, .status = value.readOption(.exit_code) }; + self.pinCursor(&self.out_end, true); + } else { + self.declined +%= 1; + }, + else => {}, + } + } + if (comptime action == .erase_display_complete or action == .erase_display_scrollback or action == .full_reset) { + if (self.phase == .running) self.lost = true; + } + self.inner.vt(action, value); + } + + pub fn deinit(self: *@This()) void { + self.inner.deinit(); + } +} else void; + +pub const Replay = struct { + bytes: [1024 * 1024]u8 = undefined, + head: usize = 0, + len: usize = 0, +}; + +pub const State = struct { + vt: VtSlot, + stream: StreamSlot, + replay: Replay, + reply: [256]u8 = undefined, + reply_len: u16 = 0, +}; + +const GColor = ghostty_vt.color; + +const FilterPaletteKey = struct { + bg: GColor.RGB, + fg: GColor.RGB, + base: [16]GColor.RGB, +}; + +pub const FilterPalette = if (enabled) LivePalette else struct {}; + +const LivePalette = struct { + key: ?FilterPaletteKey = null, + colors: GColor.Palette = GColor.default, + + fn get(self: *LivePalette, theme: *const pardes.Theme) *const GColor.Palette { + const bg = asGhostRgb(theme.bg orelse theme.tag_bg); + const fg = asGhostRgb(theme.fg orelse theme.tag_fg); + var base: [16]GColor.RGB = undefined; + if (theme.palette) |palette| { + for (&base, palette) |*dst, src| dst.* = asGhostRgb(src); + } else { + const synthesized = [16][3]u8{ + theme.bg orelse theme.tag_bg, + theme.kw, + theme.str, + theme.num, + theme.box, + theme.sel_bg, + theme.comment, + theme.fg orelse theme.tag_fg, + theme.lineno, + theme.kw, + theme.str, + theme.num, + theme.scroll_thumb, + theme.sel_fg, + theme.tag_fg, + theme.fg orelse theme.tag_fg, + }; + for (&base, synthesized) |*dst, src| dst.* = asGhostRgb(src); + } + + const key: FilterPaletteKey = .{ .bg = bg, .fg = fg, .base = base }; + if (self.key) |old| if (std.meta.eql(old, key)) return &self.colors; + + var seed = GColor.default; + for (base, 0..) |rgb, i| seed[i] = rgb; + self.colors = GColor.generate256Color(seed, .initEmpty(), bg, fg, false); + self.key = key; + return &self.colors; + } +}; + +fn asGhostRgb(rgb: [3]u8) GColor.RGB { + return .{ .r = rgb[0], .g = rgb[1], .b = rgb[2] }; +} + +fn asPardesColor(rgb: GColor.RGB) pardes.Color { + return .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; +} + +/// The owned text standing in for `rows` live terminal rows, beginning at +/// absolute surface row `row`. The emulator grid remains untouched underneath. +pub const EditBuffer = struct { + row: i32 = 0, + rows: i32 = 1, + text: []u8 = &.{}, +}; + +/// One whole-state terminal edit boundary. Null means the pane has not yet +/// materialized an edit buffer; non-null snapshots own their text. +pub const Snapshot = struct { + ovl: ?EditBuffer, + cur_row: i32, + cur_col: i32, + vsel: panes.Text.CharSel, +}; + +pub const PendingCommand = struct { + bytes: []u8 = &.{}, + wait: enum { none, spawn, input } = .none, +}; + +pub fn armShellSpawn(pane: *Pane) void { + if (comptime !enabled) return; + std.debug.assert(pane.pending_command.bytes.len == 0); + pane.pending_command.wait = .spawn; +} + +/// Remembers a line pardes types into this terminal as the command it +/// started, for Kill: it runs from the shell's next C mark to its D. +/// ponytail: of several lines queued for a shell not up yet, only the last +/// is remembered, as the first of them. +pub fn noteCommand(pane: *Pane, line: []const u8) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + const word = std.mem.trim(u8, line, " \t")[0 .. std.mem.indexOfAny(u8, std.mem.trim(u8, line, " \t"), " \t") orelse std.mem.trim(u8, line, " \t").len]; + var sent: @typeInfo(@FieldType(Pane, "sent_command")).optional.child = .{ .seq = state.stream.handler.started +% 1 }; + sent.len = @intCast(@min(word.len, sent.word.len)); + @memcpy(sent.word[0..sent.len], word[0..sent.len]); + pane.sent_command = sent; +} + +/// Whether the command pardes last typed here is running now. +pub fn commandRunning(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + const sent = pane.sent_command orelse return false; + const marks = &state.stream.handler; + return marks.phase == .running and marks.started == sent.seq; +} + +pub fn queuePendingCommand(pane: *Pane, command: []const u8) !bool { + if (pane.pending_command.wait == .none) return false; + const old_len = pane.pending_command.bytes.len; + const new_len = try std.math.add(usize, old_len, try std.math.add(usize, command.len, 1)); + const bytes = if (old_len == 0) + try pane.gpa.alloc(u8, new_len) + else + try pane.gpa.realloc(pane.pending_command.bytes, new_len); + @memcpy(bytes[old_len..][0..command.len], command); + bytes[new_len - 1] = '\r'; + pane.pending_command.bytes = bytes; + pane.greet = false; + return true; +} + +pub fn shellSpawned(p: *Pardes, id: usize, prompt_marks: bool) void { + const pane = p.panes[id] orelse return; + if (!pane.isTerminal() or pane.pending_command.wait != .spawn) return; + if (prompt_marks) { + pane.pending_command.wait = .input; + releasePendingCommand(p, id, pane, false); + } else { + pane.greet = false; + releasePendingCommand(p, id, pane, true); + } +} + +pub fn releasePendingCommandIfReady(p: *Pardes, id: usize, pane: *Pane) void { + if (pane.pending_command.wait == .input) + releasePendingCommand(p, id, pane, promptInputReady(pane)); +} + +fn releasePendingCommand(p: *Pardes, id: usize, pane: *Pane, ready: bool) void { + if (!ready) return; + const bytes = pane.pending_command.bytes; + pane.pending_command = .{}; + if (bytes.len > 0) { + p.emitWrite(id, bytes); + pane.gpa.free(bytes); + } +} + +pub fn deinitPendingCommand(pane: *Pane) void { + if (pane.pending_command.bytes.len > 0) + pane.gpa.free(pane.pending_command.bytes); + pane.pending_command = .{}; +} + +pub fn terminalIo() std.Io { + return if (comptime !pardes.hosted) + std.Io.failing + else + std.Io.Threaded.global_single_threaded.io(); +} + +/// The three numbers ghostty's scrollbar reports; all zero without an emulator. +pub const Scrollbar = struct { total: usize = 0, offset: usize = 0, len: usize = 0 }; + +pub fn scrollbar(pane: *const Pane) Scrollbar { + if (comptime !enabled) return .{}; + const state = pane.terminal orelse return .{}; + const sb = state.vt.screens.active.pages.scrollbar(); + return .{ .total = sb.total, .offset = sb.offset, .len = sb.len }; +} + +/// The emulator's viewport offset, in SHELL rows: the top of what it shows. +pub fn gridOffset(pane: *const Pane) i32 { + return @intCast(scrollbar(pane).offset); +} + +/// Where the emulator itself puts the cursor, in active-area cells — the origin +/// without one, which is where an empty pane's cursor belongs anyway. +pub const GridCursor = struct { x: u16 = 0, y: u16 = 0 }; + +pub fn gridCursor(pane: *const Pane) GridCursor { + if (comptime !enabled) return .{}; + const state = pane.terminal orelse return .{}; + const cur = state.vt.screens.active.cursor; + return .{ .x = @intCast(cur.x), .y = @intCast(cur.y) }; +} + +pub fn visibleCursor(pane: *const Pane) ?GridCursor { + if (comptime !enabled) return null; + const state = pane.terminal orelse return null; + if (!state.vt.modes.get(.cursor_visible)) return null; + const cur = state.vt.screens.active.cursor; + const sb = scrollbar(pane); + const row = sb.total - sb.len + cur.y; + if (row < sb.offset or row - sb.offset >= sb.len) return null; + return .{ .x = @intCast(cur.x), .y = @intCast(row - sb.offset) }; +} + +/// Move the emulator's viewport by `delta` shell rows (negative scrolls back). +pub fn scrollGrid(pane: *Pane, delta: i32) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + state.vt.screens.active.scroll(.{ .delta_row = delta }); +} + +/// Is the viewport already showing the last row of output? +pub fn atBottom(pane: *const Pane) bool { + if (comptime !enabled) return true; + const sb = scrollbar(pane); + return sb.offset + sb.len >= sb.total; +} + +/// Snap the viewport back onto live output. +pub fn followOutput(pane: *Pane) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + state.vt.screens.active.scroll(.active); +} + +/// Reflow the grid. A failed reflow keeps the grid it had rather than dropping +/// a scrollback; the next resize retries with the same numbers. +pub fn resizeGrid(pane: *Pane, gpa: std.mem.Allocator, cols: u16, rows: u16) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + if (cols != pane.cols) for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + }; + state.vt.resize(gpa, .{ .cols = cols, .rows = rows }) catch {}; +} + +/// DECSET 2004: the program wants its pastes bracketed. +pub fn bracketedPaste(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + return state.vt.modes.get(.bracketed_paste); +} + +/// The program tracks the mouse itself, so a click in its body is its event. +pub fn reportsMouse(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + const m = &state.vt.modes; + return m.get(.mouse_event_normal) or m.get(.mouse_event_button) or m.get(.mouse_event_any); +} + +/// ...and wants them in SGR (1006) rather than the legacy X10 bytes. +pub fn mouseFormatSgr(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + return state.vt.modes.get(.mouse_format_sgr); +} + +/// The whole scrollback as plain text, `gpa`-owned: what a terminal's body +/// reads and `Save` writes out. Logical lines: rows the terminal wrapped +/// are joined again (ghostty's wrap flags, as pty/run's output is), and +/// the last line ends with a newline. +pub fn screenTextAlloc(pane: *Pane, gpa: std.mem.Allocator) ![]const u8 { + if (comptime !enabled) return &.{}; + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + try writeScreenText(pane, &out.writer); + return out.toOwnedSlice(); +} + +fn writeScreenText(pane: *Pane, w: *std.Io.Writer) !void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + const screen = state.vt.screens.active; + const br = screen.pages.getBottomRight(.screen) orelse return; + var both: TeeWriter = .{ .a = w }; + try screen.dumpString(&both.writer, .{ .tl = screen.pages.getTopLeft(.screen), .br = br, .unwrap = true }); + if (both.count > 0 and both.final != '\n') try w.writeByte('\n'); +} + +/// Passes bytes through, remembering how many and the last one. +const TeeWriter = struct { + a: *std.Io.Writer, + count: usize = 0, + final: u8 = 0, + writer: std.Io.Writer = .{ .vtable = &.{ .drain = drain }, .buffer = &.{} }, + + fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize { + const t: *TeeWriter = @alignCast(@fieldParentPtr("writer", w)); + var n: usize = 0; + for (data[0 .. data.len - 1]) |bytes| { + try t.a.writeAll(bytes); + t.note(bytes); + n += bytes.len; + } + const pattern = data[data.len - 1]; + for (0..splat) |_| { + try t.a.writeAll(pattern); + t.note(pattern); + n += pattern.len; + } + return n; + } + + fn note(t: *TeeWriter, bytes: []const u8) void { + if (bytes.len == 0) return; + t.count += bytes.len; + t.final = bytes[bytes.len - 1]; + } +}; + +/// How long `screenTextAlloc` would be, counted without keeping it: the +/// length a terminal's body reads as, which its ctl line reports. +pub fn screenTextLen(pane: *Pane) usize { + if (comptime !enabled) return 0; + var buf: [256]u8 = undefined; + var counting: std.Io.Writer.Discarding = .init(&buf); + writeScreenText(pane, &counting.writer) catch return 0; + return @intCast(counting.fullCount()); +} + +/// Release the emulator's heap. The Pane allocation itself is the core's. +pub fn deinitEmulator(pane: *Pane, gpa: std.mem.Allocator) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + state.stream.deinit(); + state.vt.deinit(gpa); + gpa.destroy(state); + pane.terminal = null; +} + +/// Allocate the live emulator half of a terminal pane. Slot ownership, serial +/// assignment, and spawn effects remain core lifecycle invariants. +pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { + const pane = try createDoc(gpa, cols, rows); + errdefer gpa.destroy(pane); + if (comptime !enabled) return pane; + const state = try gpa.create(State); + errdefer gpa.destroy(state); + state.vt = try ghostty_vt.Terminal.init(terminalIo(), gpa, .{ + .cols = cols, + .rows = rows, + .max_scrollback = 16 * 1024 * 1024, + }); + state.stream = .initAlloc(gpa, .{ .inner = state.vt.vtHandler() }); + state.replay.head = 0; + state.replay.len = 0; + state.reply_len = 0; + state.stream.handler.inner.effects.write_pty = ptyReport; + state.stream.handler.inner.effects.device_attributes = ptyDeviceAttrs; + pane.terminal = state; + pane.tty_filter = true; + return pane; +} + +pub fn createDoc(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { + const pane = try gpa.create(Pane); + pane.* = .{ + .gpa = gpa, + .cols = cols, + .rows = rows, + }; + return pane; +} + +/// Where a restored terminal's history ends and its new shell begins. +pub const restored_banner = "\x1b[0m\r\n\x1b[2m\u{2500}\u{2500} restored history \u{2500}\u{2500}\x1b[0m\r\n"; + +/// Rebuild a dump's terminal emulator from its recorded output. `live`: a +/// shell will be spawned into it, so the history is marked off from what +/// that shell prints and the pane waits for it like any new terminal. +/// Registration and tag/cwd policy stay with the core; raw VT replay and +/// viewport restoration belong here. +pub fn restore(p: *Pardes, src: dump.Pane, live: bool) !*Pane { + const terminal = src.terminal.?; + if (comptime !enabled) { + const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); + errdefer p.gpa.destroy(pane); + if (terminal.stream.len > 0) + pane.ovl = .{ .row = 0, .rows = 1, .text = try p.gpa.dupe(u8, terminal.stream) }; + return pane; + } + // An older dump's raw output tail cannot come back live: cut off mid + // redraw, or written at sizes the pane no longer has, it replays as + // garbage. Its rendered text can. + const legacy_text = live and !terminal.stream_is_screen and terminal.stream.len > 0; + const bytes = if (legacy_text) + try std.mem.replaceOwned(u8, p.scratch.allocator(), terminal.stream, "\n", "\r\n") + else if (terminal.stream_b64.len > 0) + try dump.decodeBytes(p.scratch.allocator(), terminal.stream_b64) + else + &.{}; + const pane = try create(p.gpa, @max(1, src.cols), @max(1, src.rows)); + if (live) { + if (bytes.len > 0) { + ingest(pane, bytes); + ingest(pane, restored_banner); + } + followOutput(pane); + // A view left scrolled back stays on what it was showing: the + // banner's line breaks scrolled a full screen by that many more. + if (src.scroll > 0) scrollGrid(pane, -@as(i32, @intCast(src.scroll + comptime std.mem.count(u8, restored_banner, "\n")))); + armShellSpawn(pane); + } else if (bytes.len > 0) { + ingest(pane, bytes); + followOutput(pane); + if (src.scroll > 0) + scrollGrid(pane, -@as(i32, @intCast(src.scroll))); + } + return pane; +} + +/// Feed the emulator and retain the bounded suffix a dump can replay. Live +/// output and restoration share this byte path, then apply different views. +fn ingest(pane: *Pane, bytes: []const u8) void { + const state = pane.terminal.?; + const replay = &state.replay; + if (bytes.len >= replay.bytes.len) { + const kept = bytes[bytes.len - replay.bytes.len ..]; + @memcpy(&replay.bytes, kept); + replay.head = 0; + replay.len = replay.bytes.len; + } else { + const overflow = bytes.len -| (replay.bytes.len - replay.len); + replay.head = (replay.head + overflow) % replay.bytes.len; + replay.len -= overflow; + const tail = (replay.head + replay.len) % replay.bytes.len; + const first = @min(bytes.len, replay.bytes.len - tail); + @memcpy(replay.bytes[tail..][0..first], bytes[0..first]); + @memcpy(replay.bytes[0 .. bytes.len - first], bytes[first..]); + replay.len += bytes.len; + } + state.stream.nextSlice(bytes); +} + +/// Return the replay ring in chronological order. Wrapped records are copied +/// into `allocator`; contiguous records remain a borrowed slice of the pane. +fn replayBytes(pane: *const Pane, allocator: std.mem.Allocator) ![]const u8 { + const state = pane.terminal orelse return &.{}; + const replay = &state.replay; + if (replay.len == 0) return &.{}; + if (replay.head + replay.len <= replay.bytes.len) + return replay.bytes[replay.head..][0..replay.len]; + const out = try allocator.alloc(u8, replay.len); + const first = replay.bytes.len - replay.head; + @memcpy(out[0..first], replay.bytes[replay.head..]); + @memcpy(out[first..], replay.bytes[0 .. replay.len - first]); + return out; +} + +test "replay ownership is terminal-only and construction rolls back on allocation failure" { + const Case = struct { + fn run(gpa: std.mem.Allocator, terminal: bool) !void { + const pane = if (terminal) try create(gpa, 40, 12) else try createDoc(gpa, 40, 12); + defer gpa.destroy(pane); + defer deinitEmulator(pane, gpa); + try std.testing.expectEqual(terminal and enabled, pane.terminal != null); + } + }; + try std.testing.expect(@sizeOf(Pane) < 128 * 1024); + try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{false}); + try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{true}); +} + +test "document construction allocates only the pane and has inert terminal defaults" { + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1 }); + const allocator = failing.allocator(); + const pane = try createDoc(allocator, 40, 12); + defer allocator.destroy(pane); + defer deinitEmulator(pane, allocator); + try std.testing.expect(pane.terminal == null); + try std.testing.expectEqual(@as(usize, 1), failing.alloc_index); + try std.testing.expectEqual(@as(usize, 0), failing.resize_index); + try std.testing.expect(!failing.has_induced_failure); + try std.testing.expectEqual(@as(usize, @sizeOf(Pane)), failing.allocated_bytes); + try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); + try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); + try std.testing.expect(!bracketedPaste(pane)); + try std.testing.expect(!reportsMouse(pane)); + try std.testing.expect(!mouseFormatSgr(pane)); + try std.testing.expect(!promptInputReady(pane)); + scrollGrid(pane, 100); + followOutput(pane); + resizeGrid(pane, allocator, 80, 24); + try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); + try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); + try std.testing.expectEqualStrings("", try screenTextAlloc(pane, allocator)); + try std.testing.expectEqualStrings("", try replayBytes(pane, allocator)); + try std.testing.expect(!failing.has_induced_failure); +} + +test "terminal state keeps parser fragments and sends emulator replies through its owner" { + if (comptime !enabled) return error.SkipZigTest; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + const state = pane.terminal.?; + try std.testing.expect(state.stream.handler.inner.terminal == &state.vt); + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[" } }); + while (p.nextEffect()) |effect| { + if (effect == .write) return error.PrematureTerminalReply; + } + p.update(.{ .output = .{ .pane = 0, .bytes = "6n" } }); + var replies: usize = 0; + while (p.nextEffect()) |effect| { + if (effect != .write) continue; + try std.testing.expectEqual(@as(u8, 0), effect.write.pane); + try std.testing.expectEqualStrings("\x1b[1;1R", effect.write.bytes.slice()); + replies += 1; + } + try std.testing.expectEqual(@as(usize, 1), replies); + try std.testing.expectEqual(@as(u16, 0), state.reply_len); + try std.testing.expectEqualStrings("\x1b[6n", try replayBytes(pane, std.testing.allocator)); +} + +test "replay keeps a bounded chronological suffix across large writes and wrapping" { + if (comptime !enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const pane = try create(gpa, 40, 12); + defer gpa.destroy(pane); + defer deinitEmulator(pane, gpa); + try std.testing.expectEqualStrings("", try replayBytes(pane, gpa)); + ingest(pane, "hello"); + const small = try replayBytes(pane, gpa); + try std.testing.expectEqualStrings("hello", small); + try std.testing.expectEqual(@intFromPtr(&pane.terminal.?.replay.bytes), @intFromPtr(small.ptr)); + + const capacity = pane.terminal.?.replay.bytes.len; + const input = try gpa.alloc(u8, capacity + 7); + defer gpa.free(input); + @memset(input, 0); + const ending = "\x1b[31mred\x1b[0m\r\n"; + @memcpy(input[input.len - ending.len ..], ending); + ingest(pane, input); + try std.testing.expectEqualSlices(u8, input[7..], try replayBytes(pane, gpa)); + ingest(pane, "next\r\n"); + const wrapped = try replayBytes(pane, gpa); + defer gpa.free(wrapped); + try std.testing.expectEqual(capacity, wrapped.len); + try std.testing.expectEqualSlices(u8, input[7 + "next\r\n".len ..], wrapped[0 .. capacity - "next\r\n".len]); + try std.testing.expectEqualStrings("next\r\n", wrapped[capacity - "next\r\n".len ..]); +} + +test "replay restores terminal cells from the retained stream" { + if (comptime !enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + feedOutput(p, pane, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); + const encoded = try dump.encodeBytes(gpa, try replayBytes(pane, gpa)); + defer gpa.free(encoded); + const restored = try restore(p, .{ + .kind = .terminal, + .tag = "", + .body = "", + .cols = pane.cols, + .rows = pane.rows, + .terminal = .{ .stream_b64 = encoded }, + }, false); + defer gpa.destroy(restored); + defer deinitEmulator(restored, gpa); + const before = try screenTextAlloc(pane, gpa); + defer gpa.free(before); + const after = try screenTextAlloc(restored, gpa); + defer gpa.free(after); + try std.testing.expectEqualStrings(before, after); + try std.testing.expectEqualSlices(u8, try replayBytes(pane, gpa), try replayBytes(restored, gpa)); +} + +test "a restored command pane comes back finished, its command not run again" { + if (comptime !enabled or pardes.isolated) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const cmd = p.freeSlot().?; + _ = try p.newCommand(cmd, "/tmp", "make test"); + feedOutput(p, p.panes[cmd].?, "ok\r\n"); + p.update(.{ .exited = .{ .pane = @intCast(cmd), .status = 2 } }); + try dump.dumpState(p); + const restored = try dump.initFromDump(gpa, .{ .tty_only = true, .cols = 60, .rows = 16 }, p.dump_out.?); + defer restored.deinit(); + var spawns: usize = 0; + while (restored.nextEffect()) |effect| switch (effect) { + .spawn => spawns += 1, + else => {}, + }; + try std.testing.expectEqual(@as(usize, 1), spawns); // the shell, not the command + const again = for (restored.panes) |slot| { + if (slot) |pane| if (pane.command != null) break pane; + } else return error.CommandPaneLost; + try std.testing.expectEqualStrings("make test", again.command.?); + try std.testing.expect(again.command_done); + try std.testing.expectEqual(@as(?u8, 2), again.command_status); + const text = try screenTextAlloc(again, gpa); + defer gpa.free(text); + try std.testing.expect(std.mem.indexOf(u8, text, "ok") != null); +} + +test "a restored terminal keeps its history above a marker and gets a shell where it was" { + if (comptime !enabled or pardes.isolated) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + feedOutput(p, pane, "old output\r\n$ ls\r\n"); + try pane.setOwnedCwd("/tmp"); + pane.shell = try gpa.dupe(u8, "bash"); // `Tty bash`: it comes back as bash + try dump.dumpState(p); + const restored = try dump.initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?); + defer restored.deinit(); + var spawned = false; + while (restored.nextEffect()) |effect| switch (effect) { + .spawn => |sp| spawned = sp.pane == 0 and std.mem.eql(u8, sp.cwd.slice(), "/tmp"), + else => {}, + }; + try std.testing.expect(spawned); + const again = restored.panes[0].?; + try std.testing.expectEqualStrings("bash", again.shell.?); + try std.testing.expect(again.command == null); + try std.testing.expectEqual(.spawn, again.pending_command.wait); + const text = try screenTextAlloc(again, gpa); + defer gpa.free(text); + const old_at = std.mem.indexOf(u8, text, "old output") orelse return error.HistoryLost; + const mark_at = std.mem.indexOf(u8, text, "restored history") orelse return error.NoMarker; + try std.testing.expect(old_at < mark_at); +} + +test "an older dump comes back live from its rendered text, not its raw output tail" { + if (comptime !enabled) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); + defer p.deinit(); + // A tail cut mid-redraw: relative moves from a cursor it never set. + const tail = try dump.encodeBytes(gpa, "\x1b[7A\x1b[2Kgarbage\x1b[3B\x1b[9Gmore"); + defer gpa.free(tail); + const restored = try restore(p, .{ + .kind = .terminal, + .tag = "", + .body = "", + .cols = 40, + .rows = 12, + .terminal = .{ .stream = "$ ls\na.txt b.txt\n$ ", .stream_b64 = tail }, + }, true); + defer gpa.destroy(restored); + defer deinitEmulator(restored, gpa); + defer deinitPendingCommand(restored); + const text = try screenTextAlloc(restored, gpa); + defer gpa.free(text); + try std.testing.expect(std.mem.indexOf(u8, text, "$ ls\na.txt b.txt") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "garbage") == null); +} + +/// Record and parse one live pty read, invalidate its motion surface, and +/// follow it only when the body (possibly parked under a tag edit) is raw. +pub fn feedOutput(p: *Pardes, pane: *Pane, bytes: []const u8) void { + // There are no pty reads at all without an emulator to parse them into. + if (comptime !enabled) return; + if (pane.terminal == null) return; + const has_positions = pane.ovl != null or pane.body.cur_pinned or pane.body.vsel.active or + pane.body.msel.active or pane.body.nsel > 0 or pane.body.last_edit != null or pane.look_at != null or + pane.body.ed_undo_len > 0 or pane.body.ed_redo_len > 0 or pointerRowCount(pane) > 0; + // Sticky bottom, as every other terminal does it: output drags the + // viewport down only when the viewport was already on the last row, so + // a reader scrolled back into the scrollback stays where they scrolled. + const at_bottom = atBottom(pane); + if (has_positions) ingestWithPositions(pane, bytes) else ingest(pane, bytes); + p.shell_rows.markStale(pane); + if (pane.body.mode == .tty and at_bottom) followOutput(pane); +} + +const RowPin = struct { pin: ?*ghostty_vt.Pin = null, offset: i32 = 0 }; +const PositionPin = struct { + target: *i32, + row: RowPin, + overlay: ?*EditBuffer, + edit_row: ?i32 = null, +}; + +fn trackRow(pages: *ghostty_vt.PageList, row: i32, failed: *bool) RowPin { + if (row < 0) return .{ .offset = row }; + const bounded: usize = @min(@as(usize, @intCast(row)), pages.total_rows - 1); + var left = pages.total_rows - 1 - bounded; + var node = pages.pages.last.?; + while (left >= node.rows()) { + left -= node.rows(); + node = node.prev.?; + } + const pin = pages.trackPin(.{ .node = node, .y = @intCast(node.rows() - 1 - left) }) catch { + failed.* = true; + return .{}; + }; + return .{ .pin = pin, .offset = row - @as(i32, @intCast(bounded)) }; +} + +fn pinnedRow(pages: ?*ghostty_vt.PageList, row: RowPin) i32 { + const pin = row.pin orelse return row.offset; + const alive = pages orelse return 0; + if (pin.garbage) return 0; + var after: usize = 0; + var node = alive.pages.last; + while (node) |item| : (node = item.prev) { + if (item == pin.node) + return @as(i32, @intCast(alive.total_rows - after - item.rows() + pin.y)) +| row.offset; + after += item.rows(); + } + return 0; +} + +fn trackPosition(pages: *ghostty_vt.PageList, target: *i32, overlay: ?*EditBuffer, failed: *bool) PositionPin { + var grid = target.*; + if (overlay) |edit| { + const lines: i32 = @intCast(modal.lineCount(edit.text)); + if (grid >= edit.row and grid < edit.row +| lines) + return .{ .target = target, .row = .{}, .overlay = edit, .edit_row = grid - edit.row }; + if (grid > edit.row) grid = grid -| lines +| edit.rows; + } + return .{ .target = target, .row = trackRow(pages, grid, failed), .overlay = overlay }; +} + +fn pointerRowCount(pane: *const Pane) usize { + var count: usize = 0; + for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { + count += rows.len; + }; + return count; +} + +fn ingestWithPositions(pane: *Pane, bytes: []const u8) void { + const screens = &pane.terminal.?.vt.screens; + const key = screens.active_key; + const generation = screens.generation(key); + const pages = &screens.active.pages; + const Group = struct { overlay: ?*EditBuffer, cursor: *i32, selection: *panes.Text.CharSel }; + var groups: [history_max * 2 + 1]Group = undefined; + groups[0] = .{ + .overlay = if (pane.ovl) |*overlay| overlay else null, + .cursor = &pane.body.cur_row, + .selection = &pane.body.vsel, + }; + var ngroups: usize = 1; + for ([_][]Snapshot{ pane.body.ed_undo[0..pane.body.ed_undo_len], pane.body.ed_redo[0..pane.body.ed_redo_len] }) |history| { + for (history) |*snapshot| { + groups[ngroups] = .{ + .overlay = if (snapshot.ovl) |*overlay| overlay else null, + .cursor = &snapshot.cur_row, + .selection = &snapshot.vsel, + }; + ngroups += 1; + } + } + const Span = struct { overlay: *EditBuffer, start: RowPin, end: RowPin }; + var spans: [groups.len]Span = undefined; + var nspans: usize = 0; + var positions: [groups.len * 2 + panes.Text.max_selections * 2 + 4]PositionPin = undefined; + var npositions: usize = 0; + var failed = false; + for (groups[0..ngroups]) |group| { + if (group.overlay) |overlay| { + spans[nspans] = .{ + .overlay = overlay, + .start = trackRow(pages, overlay.row, &failed), + .end = trackRow(pages, overlay.row +| (overlay.rows - 1), &failed), + }; + nspans += 1; + } + positions[npositions] = trackPosition(pages, group.cursor, group.overlay, &failed); + npositions += 1; + if (group.selection.active) { + positions[npositions] = trackPosition(pages, &group.selection.row, group.overlay, &failed); + npositions += 1; + } + } + const overlay = groups[0].overlay; + var extra: [panes.Text.max_selections * 2 + 4]*i32 = undefined; + var nextra: usize = 0; + if (pane.body.msel.active) { + extra[nextra] = &pane.body.msel.r0; + extra[nextra + 1] = &pane.body.msel.r1; + nextra += 2; + } + for (pane.body.sels[0..pane.body.nsel]) |*selection| { + extra[nextra] = &selection.row; + extra[nextra + 1] = &selection.arow; + nextra += 2; + } + if (pane.body.last_edit) |*at| { + extra[nextra] = &at.row; + nextra += 1; + } + if (pane.look_at) |*at| { + extra[nextra] = &at.row; + nextra += 1; + } + for (extra[0..nextra]) |target| { + positions[npositions] = trackPosition(pages, target, overlay, &failed); + npositions += 1; + } + const pointer_positions = pane.gpa.alloc(PositionPin, pointerRowCount(pane)) catch null; + defer if (pointer_positions) |pins| pane.gpa.free(pins); + if (pointer_positions) |pins| { + var index: usize = 0; + for (pane.sel) |gesture| if (pane.pointerSelection(gesture)) |rows| { + for (rows) |*row| { + pins[index] = trackPosition(pages, &row.row, if (row.raw_terminal) null else overlay, &failed); + index += 1; + } + }; + } else failed = true; + ingest(pane, bytes); + // RIS can destroy the alternate screen and every pin it owned. + const alive = if (screens.generation(key) == generation) pages else null; + var moved = false; + var pointer_rows_lost = alive == null or pointer_positions == null; + if (pointer_positions) |pins| for (pins) |position| { + if (alive != null) if (position.row.pin) |pin| { + if (pin.garbage) pointer_rows_lost = true; + }; + }; + for (spans[0..nspans]) |span| { + const start = pinnedRow(alive, span.start); + const rows = @max(1, pinnedRow(alive, span.end) -| start +| 1); + moved = moved or start != span.overlay.row or rows != span.overlay.rows; + span.overlay.row = start; + span.overlay.rows = rows; + if (alive) |owner| { + if (span.start.pin) |pin| owner.untrackPin(pin); + if (span.end.pin) |pin| owner.untrackPin(pin); + } + } + for ([_][]PositionPin{ positions[0..npositions], pointer_positions orelse &.{} }) |batch| for (batch) |position| { + var row = pinnedRow(alive, position.row); + if (position.overlay) |edit| { + if (position.edit_row) |relative| { + row = edit.row +| relative; + } else if (row > edit.row) { + row = if (row < edit.row +| edit.rows) + edit.row + else + row -| edit.rows +| @as(i32, @intCast(modal.lineCount(edit.text))); + } + } + moved = moved or row != position.target.*; + position.target.* = row; + if (alive) |owner| if (position.row.pin) |pin| owner.untrackPin(pin); + }; + if (pointer_rows_lost) for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + }; + if (moved) pane.nsel_snap = 0; // Saved regex-preview offsets name the old flat text. + if (failed) { + const message = "terminal edit position reset: out of memory"; + @memcpy(pane.msg[0..message.len], message); + pane.msg_len = message.len; + } +} + +test "raw terminal output needs no position tracking allocations" { + if (comptime !enabled) return error.SkipZigTest; + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{}); + const p = try Pardes.init(failing.allocator(), .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = p.panes[0].?; + pane.body.mode = .tty; + feedOutput(p, pane, "warm"); + const allocations = failing.alloc_index; + failing.fail_index = allocations; + const pins = pane.terminal.?.vt.screens.active.pages.countTrackedPins(); + feedOutput(p, pane, " output"); + try std.testing.expectEqual(allocations, failing.alloc_index); + try std.testing.expect(!failing.has_induced_failure); + try std.testing.expectEqual(pins, pane.terminal.?.vt.screens.active.pages.countTrackedPins()); +} + +/// A full-screen program has the emulator on its alternate screen. +pub fn onAlternateScreen(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + return state.vt.screens.active_key == .alternate; +} + +/// Whether a new terminal's greeting may be typed now: only at the shell's +/// first prompt (pardes's own marks: no command started; a prompt drawn +/// again for a resize is the same first prompt), with nothing +/// typed at it and no program on the alternate screen. Any later moment is `.never`, for good: something has run or +/// been typed first, and an `ls` then would go into it. A shell pardes +/// cannot mark has no first prompt to find, and is never greeted. +pub fn greeting(pane: *const Pane) enum { wait, now, never } { + if (comptime !enabled) return .never; + if (pane.fs.unmarked) return .never; + // Text typed into the edit buffer that stands in for the prompt row. + if (pane.ovl) |o| if (o.text.len > 0) return .never; + const state = pane.terminal orelse return .wait; + const marks = &state.stream.handler; + // (Not `declined`: bash's first prompt comes after a D of its own.) + if (marks.started > 0) return .never; + // At a prompt's input (ghostty's semantic marks, pardes's or the + // shell's own), before any command pardes's marks saw run. + if (!promptInputReady(pane)) return .wait; + return if (promptInputEmpty(pane)) .now else .never; +} + +pub fn promptInputReady(pane: *const Pane) bool { + if (comptime !enabled) return false; + const state = pane.terminal orelse return false; + return state.vt.screens.active_key != .alternate and + state.vt.screens.active.cursor.semantic_content == .input; +} + +pub const CommandOutput = struct { + /// Owned by the caller. + text: [:0]const u8, + /// Whether `text` starts where the command did. It does not when that + /// start is not there to read: cut off by `max_rows`, scrolled out of + /// the history (ghostty moved the pin to the oldest row it kept and + /// flagged it `garbage`), erased under it (`MarkedHandler.lost`), or + /// never pinned (a C or D that came on the alternate screen). + whole: bool, +}; + +/// What the newest finished command printed: the screen text between its +/// C and D marks, read from at most `max_rows` rows above its end, so a +/// command that printed the whole history costs no more than its tail. +/// The shell exited in the middle of a command (its `exit 3`): no end mark +/// will come, so the command's output ends where the cursor is. +pub fn endOutputHere(pane: *Pane) void { + if (comptime !enabled) return; + const state = pane.terminal orelse return; + const marks = &state.stream.handler; + if (marks.phase == .running and marks.out_end == null) marks.pinCursor(&marks.out_end, true); +} + +pub fn commandOutput(pane: *Pane, gpa: std.mem.Allocator, max_rows: usize) !CommandOutput { + // Unless there is text to read, whether the nothing it printed is the + // whole of it. + const whole = if (comptime enabled) printed: { + const state = pane.terminal orelse break :printed true; + const marks = &state.stream.handler; + const start = marks.out_start orelse break :printed false; + const end = marks.out_end orelse break :printed false; + const screen = state.vt.screens.get(.primary) orelse break :printed false; + if (end.garbage) break :printed false; + var whole = !marks.lost and !start.garbage; + // D is where the next prompt begins: the output ends a cell before. + const last = end.leftWrap(1) orelse break :printed whole; + if (start.eql(end.*) or last.before(start.*)) break :printed whole; + var from = start.*; + if (last.up(max_rows)) |floor| if (from.before(floor)) { + from = floor; + from.x = 0; + whole = false; + }; + return .{ + .text = try screen.selectionString(gpa, .{ .sel = ghostty_vt.Selection.init(from, last, false) }), + .whole = whole, + }; + } else true; + return .{ .text = try gpa.dupeZ(u8, ""), .whole = whole }; +} + +/// At a prompt with nothing typed on its line: no input left of the +/// cursor and none under it (text typed and then Ctrl-A'd starts at the +/// cursor). Nothing further right counts: that is where fish draws a +/// right prompt, and fish suggests nothing on an empty line. +pub fn promptInputEmpty(pane: *const Pane) bool { + if (comptime !enabled) return false; + if (!promptInputReady(pane)) return false; + const cursor = &pane.terminal.?.vt.screens.active.cursor; + const row = cursor.page_pin.cells(.all); + for (row[0..@min(cursor.x + 1, row.len)]) |cell| + if (cell.semantic_content == .input and !cell.isEmpty()) return false; + return true; +} + +/// Encode one key for the program that owns a raw terminal and queue its pty +/// write, respecting the application's keyboard protocol and terminal modes. +pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { + if (comptime enabled) { + const pane = p.panes[id] orelse return; + const state = pane.terminal orelse return; + const input = ghostty_vt.input; + const function_keys = comptime keys: { + var keys: [Key.f25 - Key.f1 + 1]input.Key = undefined; + for (&keys, 1..) |*k, n| k.* = @field(input.Key, std.fmt.comptimePrint("f{d}", .{n})); + break :keys keys; + }; + const physical: input.Key = switch (key.cp) { + Key.enter => .enter, + Key.backspace => .backspace, + Key.tab => .tab, + Key.escape => .escape, + Key.up => .arrow_up, + Key.down => .arrow_down, + Key.left => .arrow_left, + Key.right => .arrow_right, + Key.home => .home, + Key.end => .end, + Key.page_up => .page_up, + Key.page_down => .page_down, + Key.delete => .delete, + Key.insert => .insert, + Key.print_screen => .print_screen, + Key.scroll_lock => .scroll_lock, + Key.pause => .pause, + Key.menu => .context_menu, + Key.f1...Key.f25 => function_keys[key.cp - Key.f1], + else => if (key.cp < 128) input.Key.fromASCII(@intCast(key.cp)) orelse .unidentified else .unidentified, + }; + var utf8: [4]u8 = undefined; + const text_cp = if (key.shift and key.cp >= 'a' and key.cp <= 'z') key.cp - 'a' + 'A' else key.cp; + // A key with no text of its own types its code point only when that + // is a character: the kitty keyboard protocol numbers function and + // modifier keys in the private use area (F3 is U+E016), and a shell + // was typed those as junk. + const text = if (key.text.len > 0) key.text else if (key.cp >= 32 and key.cp < Key.up and key.cp != Key.backspace and !(key.cp >= 0xE000 and key.cp <= 0xF8FF)) + utf8[0 .. std.unicode.utf8Encode(text_cp, &utf8) catch return] + else + ""; + var buffer: [256]u8 = undefined; + var writer = std.Io.Writer.fixed(&buffer); + input.encodeKey(&writer, .{ + .key = physical, + .mods = .{ .ctrl = key.ctrl, .alt = key.alt, .shift = key.shift }, + .consumed_mods = .{ .shift = key.text.len > 0 and key.shift }, + .utf8 = text, + .unshifted_codepoint = if (key.cp >= 'A' and key.cp <= 'Z') key.cp - 'A' + 'a' else if (key.cp < Key.up) key.cp else 0, + }, options: { + var opts = input.KeyEncodeOptions.fromTerminal(&state.vt); + // fromTerminal cannot know this one and says so, defaulting to + // "option is not alt" — right for an app that lets macOS do the + // unicode translation and hands the encoder the composed text. + // Every pardes shell resolves the modifier itself and hands the + // core the BASE key with the alt bit and no text at all (see + // PardesView.keyDown, and app.mjs doing the same with the same + // two bits), so by the time this runs alt already means alt. + // Left at the default, a macOS build drops the ESC prefix on + // the floor and forwards Alt-n to the child as a bare `n`. + opts.macos_option_as_alt = .true; + break :options opts; + }) catch return; + if (writer.end > 0) p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(writer.buffered()) } }); + return; + } + var control: [1]u8 = undefined; + const bytes: ?[]const u8 = blk: { + if (key.ctrl) { + if (key.cp >= 'a' and key.cp <= 'z') { + control[0] = @intCast(key.cp - 0x60); + break :blk control[0..1]; + } + // ASCII @, A-Z, [, \, ], ^ and _ are one contiguous control range. + if (key.cp >= '@' and key.cp <= '_') { + control[0] = @intCast(key.cp - 0x40); + break :blk control[0..1]; + } + } + if (key.text.len > 0) break :blk key.text; + break :blk switch (key.cp) { + Key.enter => "\r", + Key.backspace => "\x7f", + Key.tab => "\t", + Key.escape => "\x1b", + Key.up => "\x1b[A", + Key.down => "\x1b[B", + Key.right => "\x1b[C", + Key.left => "\x1b[D", + Key.delete => "\x1b[3~", + else => null, + }; + }; + if (bytes) |encoded| + p.emit(.{ .write = .{ .pane = @intCast(id), .bytes = .from(encoded) } }); +} + +pub fn enterTty(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + const selected = pane.rawPointerText(pane.sel[@intFromEnum(config.select_button)]) != null; + if (comptime enabled) if (!selected and pane.terminal != null and pane.body.cur_pinned and pane.terminal.?.vt.cursorIsAtPrompt()) handoff: { + const screen = pane.terminal.?.vt.screens.active; + const goff: i32 = @intCast(screen.pages.scrollbar().offset); + const vp_row = pane.gridRow(pane.body.cur_row) - goff; + if (vp_row < 0) break :handoff; + + var grid_col: i32 = @max(0, pane.body.cur_col); + if (screen.pages.pin(.{ .viewport = .{ .x = 0, .y = @intCast(vp_row) } })) |row_pin| { + if (row_pin.rowAndCell().row.semantic_prompt != .none) switch (promptCut(row_pin)) { + .cut => |cols| grid_col += @intCast(cols), + .keep, .blank => {}, + }; + } + const click_pin = screen.pages.pin(.{ + .viewport = .{ .x = @intCast(grid_col), .y = @intCast(vp_row) }, + }) orelse break :handoff; + const cursor_pin = screen.cursor.page_pin.*; + var prompts = cursor_pin.promptIterator(.left_up, null); + const prompt_pin = prompts.next() orelse break :handoff; + if (click_pin.before(prompt_pin)) break :handoff; + const moves = screen.promptClickMove(click_pin); + for (0..moves.left) |_| p.emitWrite(id, "\x1b[D"); + for (0..moves.right) |_| p.emitWrite(id, "\x1b[C"); + }; + + pane.body.mode = .tty; + followOutput(pane); // entering raw mode is a request for the live shell + pane.body.msel.active = false; + pane.body.vsel.active = false; + pane.body.nsel = 0; + // The raw renderer follows the live cursor. A captured mouse selection + // keeps its modal endpoint for the next return to editor mode. + pane.body.cur_pinned = selected; + pane.body.select = false; + pane.body.restore_cursor = false; + pane.body.sticky_col = -1; + pane.body.normal.clear(); +} + +// Returned slices remain valid until the next cache rebuild or reset. +pub const RowsCache = struct { + /// whose grid this describes; null = the slot is free + pane: ?*const Pane = null, + /// the rows joined by '\n' — `flatSurface` hands this back verbatim + /// instead of rebuilding the join on every keystroke + text: []const u8 = &.{}, + /// slices INTO `text`, absolute grid rows from 0 + rows: [][]const u8 = &.{}, + /// `text` is a prefix of this: blanking a prompt row shortens the join, + /// and the slack is not worth a second allocation to reclaim + text_alloc: []u8 = &.{}, + stale: bool = false, + + pub fn reset(c: *RowsCache, gpa: std.mem.Allocator) void { + if (c.text_alloc.len > 0) gpa.free(c.text_alloc); + if (c.rows.len > 0) gpa.free(c.rows); + c.* = .{}; + } + + /// Free a stale entry. Called at the top of `update`, and nowhere else. + pub fn sweep(c: *RowsCache, gpa: std.mem.Allocator) void { + if (c.stale) c.reset(gpa); + } + + /// `pane`'s grid moved: the entry no longer describes it. + pub fn markStale(c: *RowsCache, pane: *const Pane) void { + if (c.pane == pane) c.stale = true; + } + + pub fn dropPane(c: *RowsCache, pane: *const Pane) void { + if (c.pane != pane) return; + c.pane = null; + c.stale = true; + } +}; + +const Rows = struct { + text_alloc: []u8, + text: []const u8, + rows: [][]const u8, +}; + +const empty_grid = [1][]const u8{""}; + +/// What LEAVING raw tty mode does to one prompt row, decided from its cells +/// alone. See config.tty_blank for why any of this happens. +const PromptCut = union(enum) { + /// show the row exactly as ghostty dumped it + keep, + /// show nothing at all + blank, + /// drop this many leading COLUMNS — the prompt — and keep the rest, which + /// is what was typed at it + cut: usize, +}; + +fn promptCut(pin: ghostty_vt.Pin) PromptCut { + if (config.tty_blank == .prompt_and_input) return .blank; + const cells = pin.cells(.all); + var cols: usize = 0; + while (cols < cells.len and cells[cols].semantic_content == .prompt) cols += 1; + // Flagged, but with no prompt cells at the FRONT: a right-side prompt, or + // a repaint that has moved on. Nothing here is the prompt, so hide nothing. + if (cols == 0) return .keep; + // ...and all prompt, nothing typed yet: the row is chrome end to end. + if (cols >= cells.len) return .blank; + return .{ .cut = cols }; +} + +pub fn promptPrefixBytes(pane: *Pane, row: i32, raw: []const u8) usize { + if (comptime !enabled) return 0; + if (row < 0) return 0; + const state = pane.terminal orelse return 0; + const pin = state.vt.screens.active.pages.pin(.{ .screen = .{ .x = 0, .y = @intCast(row) } }) orelse return 0; + if (pin.rowAndCell().row.semantic_prompt == .none) return 0; + return switch (promptCut(pin)) { + .keep => 0, + .blank => raw.len, + .cut => |cols| @min(raw.len, File.rawAtDisplay(raw, cols)), + }; +} + +fn promptRow(pin: ghostty_vt.Pin, raw: []const u8) []const u8 { + const cols = switch (promptCut(pin)) { + .keep => return raw, + .blank => return "", + .cut => |n| n, + }; + const cells = pin.cells(.all); + var at: usize = 0; + var col: usize = 0; + while (col < cols and at < raw.len) { + const cell = &cells[col]; + at = @min(raw.len, at + dumpedBytes(pin, cell)); + // the tail cell of a wide glyph spells nothing of its own + col += if (cell.wide == .wide) @as(usize, 2) else 1; + } + return std.mem.trimEnd(u8, raw[at..], " \t"); +} + +fn dumpedBytes(pin: ghostty_vt.Pin, cell: *const ghostty_vt.Cell) usize { + switch (cell.wide) { + .spacer_head, .spacer_tail => return 0, + .narrow, .wide => {}, + } + var n: usize = switch (cell.content_tag) { + .codepoint, .codepoint_grapheme => std.unicode.utf8CodepointSequenceLength( + cell.codepoint(), + ) catch 1, + // A cell carrying only a colour still spells one blank in the dump. + else => 1, + }; + if (cell.content_tag == .codepoint_grapheme) { + if (pin.grapheme(cell)) |extra| for (extra) |cp| { + n += std.unicode.utf8CodepointSequenceLength(cp) catch 1; + }; + } + return n; +} + +pub fn shellRows(p: *Pardes, pane: *Pane) ![]const []const u8 { + if (comptime !enabled) return &empty_grid; + if (pane.terminal == null) return &empty_grid; + const c = &p.shell_rows; + if (!c.stale and c.pane == pane) return c.rows; + if (c.pane != null) { + c.stale = true; + return (try buildRows(p.scratch.allocator(), p, pane)).rows; + } + const built = try buildRows(p.gpa, p, pane); + c.* = .{ + .pane = pane, + .text = built.text, + .rows = built.rows, + .text_alloc = built.text_alloc, + }; + return c.rows; +} + +/// The full modal motion surface: shell history with the live edit overlay +/// spliced into the rows it covers. +pub fn cursorLines(p: *Pardes, pane: *Pane) ![]const []const u8 { + const rows = try shellRows(p, pane); + if (pane.ovl == null) return rows; + var last = rows.len; + if (pane.ovl) |overlay| + last = @max(last, @as(usize, @intCast(@max(0, overlay.row + overlay.rows)))); + var count = last; + if (pane.ovl) |overlay| { + if (overlay.row >= 0 and @as(usize, @intCast(overlay.row)) < last) + count = count - @min( + @as(usize, @intCast(overlay.rows)), + last - @as(usize, @intCast(overlay.row)), + ) + @max(1, modal.lineCount(overlay.text)); + } + const lines = try p.scratch.allocator().alloc([]const u8, count); + var n: usize = 0; + var grid_row: usize = 0; + while (grid_row < last) : (grid_row += 1) { + if (pane.ovl) |overlay| if (overlay.row >= 0 and grid_row == @as(usize, @intCast(overlay.row))) { + var overlay_lines = std.mem.splitScalar(u8, overlay.text, '\n'); + while (overlay_lines.next()) |line| : (n += 1) lines[n] = line; + grid_row += @intCast(overlay.rows - 1); + continue; + }; + lines[n] = if (grid_row < rows.len) rows[grid_row] else ""; + n += 1; + } + return lines[0..n]; +} + +/// Flatten `cursorLines` without rebuilding the common cached/no-overlay +/// case. Scratch-owned when a join is required. +pub fn flatSurface(p: *Pardes, pane: *Pane, lines: []const []const u8) ![]const u8 { + const cache = &p.shell_rows; + if (!cache.stale and cache.pane == pane and + lines.ptr == cache.rows.ptr and lines.len == cache.rows.len) return cache.text; + var total: usize = if (lines.len > 0) lines.len - 1 else 0; + for (lines) |line| total += line.len; + const text = try p.scratch.allocator().alloc(u8, total); + var at: usize = 0; + for (lines, 0..) |line, i| { + if (i > 0) { + text[at] = '\n'; + at += 1; + } + @memcpy(text[at..][0..line.len], line); + at += line.len; + } + return text; +} + +/// Materialize or extend the terminal edit overlay with one exact allocation. +/// Row slices are scratch-owned/borrowed; only the joined text is installed. +pub fn editText(p: *Pardes, pane: *Pane, lo: i32, hi: i32, col: i32) ?EditText { + const want_lo = @max(0, @min(lo, hi)); + const want_hi = @max(want_lo, @max(lo, hi)); + const fresh = pane.ovl == null; + const old: EditBuffer = pane.ovl orelse .{ .row = want_lo, .rows = 1, .text = &.{} }; + const lines: i32 = if (fresh) 1 else @intCast(modal.lineCount(old.text)); + const up = old.row - want_lo; + const down = want_hi - (old.row + lines - 1); + const extending = fresh or up > 0 or down > 0; + var row0 = old.row; + var covered = old.rows; + var text = old.text; + var owned = false; + if (extending) { + const rows = shellRows(p, pane) catch return null; + row0 = old.row - @max(0, up); + covered = old.rows + @max(0, up) + @max(0, down); + const up_len: usize = @intCast(@max(0, up)); + const down_len: usize = @intCast(@max(0, down)); + const parts = p.scratch.allocator().alloc([]const u8, up_len + 1 + down_len) catch return null; + for (parts[0..up_len], 0..) |*part, i| { + const src = @as(usize, @intCast(row0)) + i; + part.* = if (src < rows.len) rows[src] else ""; + } + const middle: usize = @intCast(old.row); + parts[up_len] = if (fresh) + (if (middle < rows.len) rows[middle] else "") + else + old.text; + for (parts[up_len + 1 ..], 0..) |*part, i| { + const src = @as(usize, @intCast(old.row + old.rows)) + i; + part.* = if (src < rows.len) rows[src] else ""; + } + text = std.mem.join(p.gpa, "\n", parts) catch return null; + owned = true; + } + + const row: usize = @intCast(@max(0, want_lo - row0)); + const line_len: i32 = @intCast(modal.lineSlice(text, row).len); + if (col > line_len) { + const spaces = p.scratch.allocator().alloc(u8, @intCast(col - line_len)) catch { + if (owned) p.gpa.free(text); + return null; + }; + @memset(spaces, ' '); + const padded = modal.insertAt(p.gpa, text, .{ .row = row, .col = @intCast(line_len) }, spaces) catch { + if (owned) p.gpa.free(text); + return null; + }; + if (owned) p.gpa.free(text); + text = padded; + owned = true; + } + if (owned) { + if (pane.ovl) |overlay| p.gpa.free(overlay.text); + pane.ovl = .{ .row = row0, .rows = covered, .text = text }; + } + return .{ .text = pane.ovl.?.text, .row0 = pane.ovl.?.row }; +} + +/// Consume a rewritten overlay, freeing the terminal edit text it replaces. +pub fn setEditText(p: *Pardes, pane: *Pane, new: []u8) void { + const overlay = if (pane.ovl) |*value| value else return pardes.edit.retireEditText(p, new); + for (0..pane.sel.len) |button| { + pane.clearPointerSelection(button); + pane.sel[button].state = .none; + } + p.gpa.free(overlay.text); + overlay.text = new; +} + +/// The shell's screen and scrollback (the primary screen, even under a +/// full-screen program) as VT that replays to what was shown: styled +/// text, soft-wrapped lines rejoined so they reflow at another width. +fn screenVt(pane: *const Pane, arena: std.mem.Allocator) ![]const u8 { + const screen = pane.terminal.?.vt.screens.get(.primary) orelse return &.{}; + var out: std.Io.Writer.Allocating = .init(arena); + try ghostty_vt.formatter.ScreenFormatter.init(screen, .{ .emit = .vt, .unwrap = true }).format(&out.writer); + return out.written(); +} + +/// Serialize terminal-only state; the core supplies shared pane metadata. +pub fn dumpPane( + pane: *Pane, + arena: std.mem.Allocator, + tag: []const u8, + body: []const u8, + scroll: usize, +) !dump.Pane { + if (!enabled or pane.terminal == null) { + const text = if (pane.ovl) |overlay| overlay.text else ""; + return .{ + .kind = .terminal, + .tag = tag, + .body = body, + .scroll = scroll, + .cols = pane.cols, + .rows = pane.rows, + .vweight = pane.vweight, + .collapsed = pane.collapsed, + .terminal = .{ + .cwd = try arena.dupe(u8, pane.cwdSlice()), + .shell = try arena.dupe(u8, pane.shell orelse ""), + .command = try arena.dupe(u8, pane.command orelse ""), + .status = pane.command_status, + .stream = try arena.dupe(u8, text), + .stream_b64 = &.{}, + .cursor = .{ .col = 0, .row = 0 }, + }, + }; + } + const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(arena, .{ .screen = .{} }); + const extra = if (pane.ovl) |overlay| overlay.text.len else 0; + const stream = try arena.alloc(u8, try std.math.add(usize, full.len, extra)); + var len: usize = 0; + var lines = std.mem.splitAny(u8, full, "\n"); + var prompts = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); + var row: i32 = 0; + var skip: i32 = 0; + while (lines.next()) |raw| : (row += 1) { + // Hidden overlay rows still consume prompt pins to keep them aligned. + const prompt = if (pane.body.mode != .tty) prompts.next() else null; + if (skip > 0) { + skip -= 1; + continue; + } + if (row > 0) { + stream[len] = '\n'; + len += 1; + } + if (pane.body.mode != .tty) if (pane.ovl) |overlay| if (row == overlay.row) { + @memcpy(stream[len..][0..overlay.text.len], overlay.text); + len += overlay.text.len; + skip = overlay.rows - 1; + continue; + }; + const shown = if (prompt) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw + else + raw; + @memcpy(stream[len..][0..shown.len], shown); + len += shown.len; + } + return .{ + .kind = .terminal, + .tag = tag, + .body = body, + .scroll = scroll, + .cols = pane.cols, + .rows = pane.rows, + .vweight = pane.vweight, + .collapsed = pane.collapsed, + .terminal = .{ + .cwd = try arena.dupe(u8, pane.cwdSlice()), + .shell = try arena.dupe(u8, pane.shell orelse ""), + .command = try arena.dupe(u8, pane.command orelse ""), + .status = pane.command_status, + .stream = stream[0..len], + .stream_b64 = try dump.encodeBytes(arena, try screenVt(pane, arena)), + .stream_is_screen = true, + .cursor = .{ + .col = pane.terminal.?.vt.screens.active.cursor.x, + .row = pane.terminal.?.vt.screens.active.cursor.y, + }, + }, + }; +} + +fn buildRows(alloc: std.mem.Allocator, p: *Pardes, pane: *Pane) !Rows { + const full = try pane.terminal.?.vt.screens.active.dumpStringAlloc(p.scratch.allocator(), .{ .screen = .{} }); + var pit = pane.terminal.?.vt.screens.active.pages.rowIterator(.right_down, .{ .screen = .{} }, null); + // split yields one more item than delimiters; the extra final slot is the + // cursor row retained below. + const n_rows = std.mem.count(u8, full, "\n") + 2; + const rows = try alloc.alloc([]const u8, n_rows); + errdefer alloc.free(rows); + // Blanking a prompt row only ever SHORTENS it and the retained cursor row + // adds one separator, so the dump's length plus one bounds the join. + const text = try alloc.alloc(u8, full.len + 1); + errdefer alloc.free(text); + var at: usize = 0; + var n: usize = 0; + var it = std.mem.splitScalar(u8, full, '\n'); + while (it.next()) |raw| { + const shown = if (pit.next()) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, raw) else raw + else + raw; + if (n > 0) { + text[at] = '\n'; + at += 1; + } + @memcpy(text[at..][0..shown.len], shown); + rows[n] = text[at..][0..shown.len]; + at += shown.len; + n += 1; + } + text[at] = '\n'; + at += 1; + rows[n] = text[at..][0..0]; + n += 1; + std.debug.assert(n == n_rows); + return .{ .text_alloc = text, .text = text[0..at], .rows = rows }; +} + +pub fn bodyText(arena: std.mem.Allocator, pane: *Pane) ![]const u8 { + const vp: []const []const u8 = if (comptime !enabled) &.{} else vp: { + const state = pane.terminal orelse break :vp &.{}; + const screen = state.vt.screens.active; + var tl = screen.pages.getTopLeft(.viewport); + tl.x = 0; + const br = screen.pages.getBottomRight(.viewport) orelse return error.UnknownPoint; + var rows_out: std.Io.Writer.Allocating = .init(arena); + try screen.dumpString(&rows_out.writer, .{ .tl = tl, .br = br, .unwrap = false }); + const raw = try rows_out.toOwnedSlice(); + var prompts = screen.pages.rowIterator(.right_down, .{ .viewport = .{} }, null); + const vp = try arena.alloc([]const u8, std.mem.count(u8, raw, "\n") + 1); + var lines = std.mem.splitScalar(u8, raw, '\n'); + var n: usize = 0; + while (lines.next()) |ln| { + vp[n] = if (pane.body.mode != .tty) + if (prompts.next()) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, ln) else ln + else + ln + else + ln; + n += 1; + } + std.debug.assert(n == vp.len); + break :vp vp; + }; + + const len = fillBody(null, pane, vp); + const out = try arena.alloc(u8, len); + const filled = fillBody(out, pane, vp); + std.debug.assert(filled == out.len); + return out; +} + +pub const BodyRow = union(enum) { + grid: i32, + edit: struct { line: []const u8, idx: usize }, +}; + +const BodyWalk = struct { + pane: *Pane, + goff: i32, + g: i32, + /// the buffer can start above the viewport: drop the lines scrolled past + skip: usize, + n: usize = 0, + lines: ?std.mem.SplitIterator(u8, .scalar) = null, + covered: i32 = 0, + line_idx: usize = 0, + + fn init(pane: *Pane) BodyWalk { + const off = pane.scroll(); + const goff = gridOffset(pane); + return .{ + .pane = pane, + .goff = goff, + .g = if (pane.body.mode == .tty) goff else pane.gridRow(off), + .skip = if (pane.ovl) |o| @intCast(@max(0, off - pane.surfRow(o.row))) else 0, + }; + } + + fn next(w: *BodyWalk) ?BodyRow { + while (w.n < w.pane.rows) { + if (w.lines) |*it| { + if (it.next()) |line| { + const idx = w.line_idx; + w.line_idx += 1; + // Lines scrolled off the top still count: the index names a + // line of the BUFFER, not of the visible body. + if (w.skip > 0) { + w.skip -= 1; + continue; + } + w.n += 1; + return .{ .edit = .{ .line = line, .idx = idx } }; + } + // The buffer stands in for `rows` shell rows however many lines + // it actually spelled, which is the whole slide. + w.g += w.covered; + w.skip = 0; + w.lines = null; + continue; + } + if (w.pane.body.mode != .tty) if (w.pane.ovl) |o| if (w.g == o.row) { + w.lines = std.mem.splitScalar(u8, o.text, '\n'); + w.covered = o.rows; + w.line_idx = 0; + continue; + }; + const vi = w.g - w.goff; + w.g += 1; + w.n += 1; + return .{ .grid = vi }; + } + return null; + } +}; + +/// Run the terminal body row walk. A null destination counts bytes; a slice +/// fills the exact allocation made from that count. +fn fillBody(dst: ?[]u8, pane: *Pane, viewport: []const []const u8) usize { + var walk: BodyWalk = .init(pane); + var written: usize = 0; + var first = true; + while (walk.next()) |row| { + if (!first) { + if (dst) |out| out[written] = '\n'; + written += 1; + } + first = false; + const bytes = switch (row) { + .edit => |e| e.line, + .grid => |vi| if (vi >= 0 and @as(usize, @intCast(vi)) < viewport.len) + viewport[@intCast(vi)] + else + "", + }; + if (dst) |out| @memcpy(out[written..][0..bytes.len], bytes); + written += bytes.len; + } + return written; +} + +// Match surviving edit-buffer rows to their original terminal styles. +const EditAnchors = struct { + /// the buffer's own text, walked in order: a line the VIEWPORT skipped still + /// consumes the row it came from, so the lines below it stay aligned + text: []const u8 = &.{}, + at: usize = 0, + shell: []const []const u8 = &.{}, + /// the covered span, absolute grid rows, as `[first, end)` + first: usize = 0, + end: usize = 0, + lines: usize = 0, + /// the line `at` names, and the first row still unclaimed + idx: usize = 0, + cursor: usize = 0, + budget: usize = 0, + active: bool = false, + + fn init(p: *Pardes, pane: *Pane, o: EditBuffer) EditAnchors { + if (o.rows <= 0 or o.row < 0) return .{}; + const first: usize = @intCast(o.row); + const screen = pane.terminal.?.vt.screens.active; + const total = screen.pages.scrollbar().total; + if (first >= total) return .{}; + const covered: usize = @intCast(o.rows); + const count = @min(covered, total - first); + const tl = screen.pages.pin(.{ .screen = .{ .y = @intCast(first) } }) orelse return .{}; + const br = screen.pages.pin(.{ .screen = .{ + .x = screen.pages.cols - 1, + .y = @intCast(first + count - 1), + } }) orelse return .{}; + const arena = p.scratch.allocator(); + var output: std.Io.Writer.Allocating = .init(arena); + screen.dumpString(&output.writer, .{ .tl = tl, .br = br, .unwrap = false }) catch return .{}; + const shell = arena.alloc([]const u8, count) catch return .{}; + var raw = std.mem.splitScalar(u8, output.written(), '\n'); + var pins = tl.rowIterator(.right_down, br); + for (shell) |*row| { + const text = raw.next() orelse ""; + row.* = if (pins.next()) |pin| + if (pin.rowAndCell().row.semantic_prompt != .none) promptRow(pin, text) else text + else + text; + } + const lines = std.mem.count(u8, o.text, "\n") + 1; + return .{ + .text = o.text, + .shell = shell, + .first = first, + .end = first + count, + .lines = lines, + .cursor = first, + .budget = covered + 4 * lines, + .active = true, + }; + } + + fn shellRow(a: *EditAnchors, idx: usize) ?Anchor { + if (!a.active or idx >= a.lines) return null; + var found: ?Anchor = null; + while (a.idx <= idx) : (a.idx += 1) found = a.claim(a.nextLine() orelse return null); + return found; + } + + fn nextLine(a: *EditAnchors) ?[]const u8 { + if (a.at > a.text.len) return null; + const rest = a.text[a.at..]; + if (std.mem.indexOfScalar(u8, rest, '\n')) |n| { + a.at += n + 1; + return rest[0..n]; + } + // The last line has no terminator; one past the end ends the walk. + a.at = a.text.len + 1; + return rest; + } + + /// Where this line still stands over the grid, if anywhere. + fn claim(a: *EditAnchors, line: []const u8) ?Anchor { + const end = if (line.len == 0) @min(a.cursor + 1, a.end) else a.end; + var k = a.cursor; + while (k < end) : (k += 1) { + if (a.budget == 0) return null; + a.budget -= 1; + if (!std.mem.eql(u8, line, a.shell[k - a.first])) continue; + a.cursor = k + 1; + return .{ .row = @intCast(k) }; + } + if (a.cursor >= a.end) return null; + const shell = a.shell[a.cursor - a.first]; + var p: usize = 0; + while (p < line.len and p < shell.len and line[p] == shell[p]) p += 1; + var s: usize = 0; + const room = @min(line.len, shell.len) - p; + while (s < room and line[line.len - 1 - s] == shell[shell.len - 1 - s]) s += 1; + if (p + s == 0) return null; + if (line.len != p + s and shell.len - (p + s) > shell.len / 2) return null; + const row = a.cursor; + if (s > 0 or p >= shell.len) a.cursor += 1; + return .{ .row = @intCast(row), .prefix = p, .suffix = s, .shell_len = shell.len }; + } +}; + +const Anchor = struct { + /// the row, absolute while it comes from `EditAnchors`, viewport once + /// `recolorAnsi` has subtracted the walk's offset + row: i32, + prefix: usize = std.math.maxInt(usize), + suffix: usize = 0, + /// the row's own dumped length — what the suffix is measured from on the + /// GRID side, where the edit may have changed the byte count + shell_len: usize = 0, + + fn whole(an: Anchor) bool { + return an.prefix == std.math.maxInt(usize); + } +}; + +pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void { + // No emulator, no ANSI cells: the whole pass — and the 256-colour theme + // projection behind it — is compiled out. + if (comptime !enabled) return; + if (pane.terminal == null) return; + const body_y = p.bodyTop(pane, r); + var filtered_storage: FilteredColors = undefined; + const filtered: ?*FilteredColors = if (pane.tty_filter) blk: { + const tz_filter = tracy.zone(@src(), "filterInit"); + defer tz_filter.end(); + filtered_storage = FilteredColors.init(p, pane); + break :blk &filtered_storage; + } else null; + // DECSCNM, read once: the filtered palette folds it in itself, the raw + // path needs it per cell. + const scnm = pane.terminal.?.vt.modes.get(.reverse_colors); + const pages = &pane.terminal.?.vt.screens.active.pages; + const vp_rows: i32 = @intCast(scrollbar(pane).len); + // Which buffer lines the user has not actually changed, so a row swallowed + // by a growing buffer keeps the colour it still stands over. + var anchors: ?EditAnchors = null; + var walk: BodyWalk = .init(pane); + var lines = std.mem.splitScalar(u8, body, '\n'); + var vr: u16 = 0; + while (walk.next()) |row| : (vr += 1) { + if (vr >= body_h) break; + // Before any early exit below, or the lines fall out of step with rows. + const text = lines.next() orelse ""; + const anchor: Anchor = switch (row) { + .edit => |e| blk: { + if (anchors == null) anchors = .init(p, pane, pane.ovl.?); + var an = anchors.?.shellRow(e.idx) orelse continue; + an.row -= walk.goff; + break :blk an; + }, + .grid => |v| .{ .row = v }, + }; + const vi = anchor.row; + if (vi < 0 or vi >= vp_rows) continue; + const row_pin = pages.pin(.{ .viewport = .{ .y = @intCast(vi) } }) orelse continue; + const cut: u16 = if (pane.body.mode == .tty) 0 else cut: { + if (row_pin.rowAndCell().row.semantic_prompt == .none) break :cut 0; + break :cut switch (promptCut(row_pin)) { + .keep => 0, + // Blanked end to end: the row shows nothing of the grid, so + // projecting the prompt's own colours onto it would be a lie. + .blank => continue, + .cut => |n| std.math.cast(u16, n) orelse continue, + }; + }; + if (cut > 0 and text.len == 0) continue; + var at: usize = 0; + var sc: u16 = 0; + var gc: u16 = cut; + var sb: usize = 0; + const mine_from = @min(anchor.prefix, text.len); + const mine_to = text.len - @min(anchor.suffix, text.len); + var crossed = false; + while (at < text.len and sc < tw) { + const stop = modal.nextGrapheme(text, at); + if (stop <= at) break; + const span: u16 = if (sc + 1 < tw and s.at(tx + sc + 1, body_y + vr).len == 0) 2 else 1; + if (at >= mine_from and at < mine_to) { + sc += span; + at = stop; + continue; + } + if (at >= mine_to and !crossed) { + crossed = true; + const upto = anchor.shell_len - @min(anchor.suffix, anchor.shell_len); + while (sb < upto) { + const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; + sb += dumpedBytes(row_pin, ci.cell); + gc = std.math.add(u16, gc, 1) catch break; + } + } + const want = stop - at; + // Consume every cell that contributed to this grapheme. A cluster + // ghostty split across several cells is still ONE printed glyph. + var covered: usize = 0; + var style: ?pardes.CellStyle = null; + while (covered < want) { + const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; + if (style == null and ci.cell.wide != .spacer_tail and ci.cell.wide != .spacer_head) + style = cellStyle(p, ci, filtered, scnm); + covered += dumpedBytes(row_pin, ci.cell); + gc = std.math.add(u16, gc, 1) catch break; + // A spacer contributes no bytes; without this the loop would + // spin on a row that ends in one. + if (covered == 0 and gc >= pane.cols) break; + } + while (pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } })) |t| { + if (t.cell.wide != .spacer_tail) break; + gc = std.math.add(u16, gc, 1) catch break; + } + if (style) |st| for (0..span) |k| { + const cell = s.at(tx + sc + @as(u16, @intCast(k)), body_y + vr); + if (cell.default and filtered == null) continue; + cell.default = false; + cell.style = st; + }; + sb += covered; + sc += span; + at = stop; + } + var tail: ?pardes.CellStyle = null; + if (anchor.whole() or anchor.suffix > 0) { + while (sc < tw) { + const ci = pages.getCell(.{ .viewport = .{ .x = gc, .y = @intCast(vi) } }) orelse break; + gc = std.math.add(u16, gc, 1) catch break; + if (ci.cell.wide == .spacer_tail) continue; + const cell = s.at(tx + sc, body_y + vr); + sc += 1; + const style = cellStyle(p, ci, filtered, scnm); + tail = style; + if (cell.default and filtered == null) continue; + cell.default = false; + cell.style = style; + } + if (tail) |style| while (sc < tw) : (sc += 1) { + const cell = s.at(tx + sc, body_y + vr); + if (cell.default and filtered == null) continue; + cell.default = false; + cell.style = style; + }; + } + } +} + +fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColors, scnm: bool) pardes.CellStyle { + const style = ci.style(); + var cs: pardes.CellStyle = .{ + .fg = if (filtered) |colors| colors.fg(style) else ghostColor(p, style.fg_color, scnm), + .bg = if (filtered) |colors| colors.bg(style, ci.cell) else ghostColor(p, style.bg_color, !scnm), + .bold = style.flags.bold, + .dim = style.flags.faint, + .italic = style.flags.italic, + .blink = style.flags.blink, + .reverse = style.flags.inverse, + .invisible = style.flags.invisible, + .strikethrough = style.flags.strikethrough, + .ul = switch (style.flags.underline) { + .none => .off, + .single => .single, + .double => .double, + .curly => .curly, + .dotted => .dotted, + .dashed => .dashed, + }, + }; + if (filtered == null) switch (ci.cell.content_tag) { + .bg_color_palette => cs.bg = palColor(p, ci.cell.content.color_palette.data), + .bg_color_rgb => { + const rgb = ci.cell.content.color_rgb; + cs.bg = .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }; + }, + else => {}, + }; + return cs; +} + +const FilteredColors = struct { + source: GColor.Palette, + target: *const GColor.Palette, + theme_bg: GColor.RGB, + theme_fg: GColor.RGB, + dynamic_bg: ?GColor.RGB, + dynamic_fg: ?GColor.RGB, + default_bg: GColor.RGB, + /// What a foreground too near `default_bg` becomes instead. + fallback_fg: GColor.RGB, + default_bg_luminance: f64, + fg_for_palette: [256]pardes.Color = undefined, + bg_for_palette: [256]pardes.Color = undefined, + /// The two answers for a cell that names no colour of its own. + fg_default: pardes.Color = undefined, + bg_default: pardes.Color = undefined, + cache_rgb: [256]GColor.RGB = undefined, + cache_key: [256]u8 = undefined, + cache_valid: [256]bool = @splat(false), + + fn init(p: *Pardes, pane: *const Pane) FilteredColors { + var source = GColor.default; + for (&source, 0..) |*rgb, i| + rgb.* = pane.terminal.?.vt.colorForXterm(.{ .palette = @intCast(i) }) orelse rgb.*; + const theme = p.theme(); + var theme_bg = asGhostRgb(theme.bg orelse theme.tag_bg); + var theme_fg = asGhostRgb(theme.fg orelse theme.tag_fg); + var dynamic_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }); + var dynamic_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }); + if (pane.terminal.?.vt.modes.get(.reverse_colors)) { + std.mem.swap(GColor.RGB, &theme_bg, &theme_fg); + std.mem.swap(?GColor.RGB, &dynamic_bg, &dynamic_fg); + } + var self: FilteredColors = .{ + .source = source, + .target = p.tty_filter_palette.get(theme), + .theme_bg = theme_bg, + .theme_fg = theme_fg, + .dynamic_bg = dynamic_bg, + .dynamic_fg = dynamic_fg, + .default_bg = theme_bg, + .fallback_fg = theme_fg, + .default_bg_luminance = luminanceOf(theme_bg), + }; + if (dynamic_bg) |rgb| self.default_bg = self.keyedRgb(rgb); + self.default_bg_luminance = luminanceOf(self.default_bg); + if (self.theme_bg.contrast(self.default_bg) > self.theme_fg.contrast(self.default_bg)) + self.fallback_fg = self.theme_bg; + + self.fg_default = asPardesColor(self.legible( + if (self.dynamic_fg) |rgb| self.keyedRgb(rgb) else self.theme_fg, + )); + self.bg_default = asPardesColor(self.default_bg); + for (&self.source, 0..) |current, i| { + const idx: u8 = @intCast(i); + const mapped = self.paletteRgb(idx, current); + self.fg_for_palette[idx] = asPardesColor(self.legible(mapped)); + self.bg_for_palette[idx] = asPardesColor(mapped); + } + return self; + } + + fn fg(self: *FilteredColors, style: ghostty_vt.Style) pardes.Color { + return switch (style.fg_color) { + .none => self.fg_default, + .palette => |idx| self.fg_for_palette[idx], + .rgb => asPardesColor(self.legible(self.keyedRgb(style.fg(.{ + .default = self.dynamic_fg orelse self.theme_fg, + .palette = &self.source, + .bold = null, + })))), + }; + } + + fn bg(self: *FilteredColors, style: ghostty_vt.Style, cell: *const ghostty_vt.Cell) pardes.Color { + switch (cell.content_tag) { + .bg_color_palette => return self.bg_for_palette[cell.content.color_palette.data], + .bg_color_rgb => {}, + else => switch (style.bg_color) { + .none => return self.bg_default, + .palette => |idx| return self.bg_for_palette[idx], + .rgb => {}, + }, + } + // Truecolour, from either the cell or its style. + return asPardesColor(self.keyedRgb(style.bg(cell, &self.source).?)); + } + + fn legible(self: *const FilteredColors, rgb: GColor.RGB) GColor.RGB { + if (contrastOf(luminanceOf(rgb), self.default_bg_luminance) >= + config.tty_filter_min_contrast) return rgb; + return self.fallback_fg; + } + + fn paletteRgb(self: *FilteredColors, idx: u8, current: GColor.RGB) GColor.RGB { + if (current.eql(GColor.default[idx])) return self.target[idx]; + return self.keyedRgb(current); + } + + fn keyedRgb(self: *FilteredColors, rgb: GColor.RGB) GColor.RGB { + return self.target[self.nearestKey(rgb)]; + } + + fn nearestKey(self: *FilteredColors, rgb: GColor.RGB) u8 { + const rgb24 = (@as(u32, rgb.r) << 16) | (@as(u32, rgb.g) << 8) | rgb.b; + const slot: u8 = @truncate((rgb24 *% 0x9e3779b1) >> 24); + if (self.cache_valid[slot] and self.cache_rgb[slot].eql(rgb)) + return self.cache_key[slot]; + + var best: u8 = 0; + var best_distance: u32 = std.math.maxInt(u32); + for (GColor.default, 0..) |candidate, i| { + const distance = colorDistance(rgb, candidate); + // Strict comparison makes duplicate-colour ties stable at the + // lowest canonical xterm key. + if (distance < best_distance) { + best_distance = distance; + best = @intCast(i); + } + } + self.cache_rgb[slot] = rgb; + self.cache_key[slot] = best; + self.cache_valid[slot] = true; + return best; + } +}; + +const channel_luminance: [256]f64 = blk: { + @setEvalBranchQuota(20000); + var table: [256]f64 = undefined; + for (&table, 0..) |*slot, c| { + const normalized: f64 = @as(f64, @floatFromInt(c)) / 255; + slot.* = if (normalized <= 0.03928) + normalized / 12.92 + else + std.math.pow(f64, (normalized + 0.055) / 1.055, 2.4); + } + break :blk table; +}; + +fn luminanceOf(rgb: GColor.RGB) f64 { + return 0.2126 * channel_luminance[rgb.r] + + 0.7152 * channel_luminance[rgb.g] + + 0.0722 * channel_luminance[rgb.b]; +} + +/// ghostty's `RGB.contrast` with both luminances already in hand. +fn contrastOf(a_luminance: f64, b_luminance: f64) f64 { + const lighter = @max(a_luminance, b_luminance); + const darker = @min(a_luminance, b_luminance); + return (lighter + 0.05) / (darker + 0.05); +} + +fn colorDistance(a: GColor.RGB, b: GColor.RGB) u32 { + const dr = @as(i32, a.r) - @as(i32, b.r); + const dg = @as(i32, a.g) - @as(i32, b.g); + const db = @as(i32, a.b) - @as(i32, b.b); + return @intCast(dr * dr + dg * dg + db * db); +} + +test "the luminance table answers exactly what ghostty computes" { + for (0..256) |i| { + const c: u8 = @intCast(i); + const grey: GColor.RGB = .{ .r = c, .g = c, .b = c }; + try std.testing.expectEqual(grey.luminance(), luminanceOf(grey)); + } + // Channel weights are asymmetric, so a grey ramp alone would not catch a + // transposed coefficient. The palette is what the tables enumerate. + for (GColor.default) |candidate| { + try std.testing.expectEqual(candidate.luminance(), luminanceOf(candidate)); + for (GColor.default) |page| { + try std.testing.expectEqual( + candidate.contrast(page), + contrastOf(luminanceOf(candidate), luminanceOf(page)), + ); + } + } +} + +test "terminal Filter keys indexed truecolor OSC and background-only cells through the theme" { + const testing = std.testing; + // Raw index assertions require a theme that inherits the ANSI palette. + const p = try Pardes.init(testing.allocator, .{ .startup_config = "Theme helix\n", .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + pane.tag_expanded = false; // a one-row tag keeps this small screen's rows + p.sync(); + try testing.expect(pane.tty_filter); + pane.tty_filter = false; + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[31mA" ++ + "\x1b[38;5;196mB" ++ + "\x1b[38;2;255;0;0mC" ++ + "\x1b[0;48;5;25mD" ++ + "\x1b[0;48;2;0;95;175mE" ++ + "\x1b[0;1;2;3;4;5;7;8;9mF" ++ + "\x1b[0;48;5;25m\x1b[K" ++ + "\r\n\x1b[0;38;5;2m界" } }); + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = p.bodyTop(pane, r); + + const raw = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .index = 1 }, raw.at(tx, body_y).style.fg); + try testing.expectEqual(pardes.Color{ .index = 196 }, raw.at(tx + 1, body_y).style.fg); + try testing.expectEqual(pardes.Color{ .rgb = .{ 255, 0, 0 } }, raw.at(tx + 2, body_y).style.fg); + + pane.tty_filter = true; + _ = frame.reset(.retain_capacity); + const filtered = try p.render(frame.allocator()); + var expected_cache: FilterPalette = .{}; + const expected = expected_cache.get(p.theme()); + try testing.expectEqual(asPardesColor(expected[1]), filtered.at(tx, body_y).style.fg); + try testing.expectEqual(asPardesColor(expected[196]), filtered.at(tx + 1, body_y).style.fg); + try testing.expectEqual(filtered.at(tx + 1, body_y).style.fg, filtered.at(tx + 2, body_y).style.fg); + try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 3, body_y).style.bg); + try testing.expectEqual(filtered.at(tx + 3, body_y).style.bg, filtered.at(tx + 4, body_y).style.bg); + + const attrs = filtered.at(tx + 5, body_y).style; + try testing.expect(attrs.bold); + try testing.expect(attrs.dim); + try testing.expect(attrs.italic); + try testing.expect(attrs.blink); + try testing.expect(attrs.reverse); + try testing.expect(attrs.invisible); + try testing.expect(attrs.strikethrough); + try testing.expectEqual(.single, attrs.ul); + + const erased = pane.terminal.?.vt.screens.active.pages.getCell(.{ .viewport = .{ .x = 6, .y = 0 } }).?; + try testing.expectEqual(.bg_color_palette, erased.cell.content_tag); + try testing.expectEqual(asPardesColor(expected[25]), filtered.at(tx + 6, body_y).style.bg); + try testing.expectEqual(asPardesColor(expected[2]), filtered.at(tx, body_y + 1).style.fg); + try testing.expectEqual(filtered.at(tx, body_y + 1).style, filtered.at(tx + 1, body_y + 1).style); + // A filtered terminal never delegates either colour to a backend palette, + // including cells which were empty/default before the pass. + for (0..r.w - config.GUTTER) |col| { + const cell = filtered.at(tx + @as(u16, @intCast(col)), body_y); + try testing.expect(!cell.default); + switch (cell.style.fg) { + .rgb => {}, + else => return error.FilteredForegroundWasNotRgb, + } + switch (cell.style.bg) { + .rgb => {}, + else => return error.FilteredBackgroundWasNotRgb, + } + } + + // Colors remains the global master gate. The pane remembers Filter while + // ANSI projection is dormant, and resumes it without replaying VT bytes. + p.settings.colors = false; + _ = frame.reset(.retain_capacity); + const plain = try p.render(frame.allocator()); + try testing.expect(pane.tty_filter); + try testing.expectEqual(asPardesColor(asGhostRgb(p.theme().fg.?)), plain.at(tx, body_y).style.fg); + p.settings.colors = true; + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]4;1;#ff0000\x1b\\" } }); + const osc_red = pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?; + try testing.expect(osc_red.eql(.{ .r = 255, .g = 0, .b = 0 })); + pane.tty_filter = false; + pane.tty_filter = true; + try testing.expect(osc_red.eql(pane.terminal.?.vt.colorForXterm(.{ .palette = 1 }).?)); + _ = frame.reset(.retain_capacity); + const osc_palette = try p.render(frame.allocator()); + try testing.expectEqual(asPardesColor(expected[196]), osc_palette.at(tx, body_y).style.fg); + + // Dynamic default foreground/background colours key every default cell, + // including the otherwise blank end of the row. + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]10;#ff0000\x1b\\" ++ + "\x1b]11;#5f5f5f\x1b\\" } }); + const dyn_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }).?; + const dyn_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }).?; + try testing.expect(dyn_fg.eql(.{ .r = 255, .g = 0, .b = 0 })); + try testing.expect(dyn_bg.eql(.{ .r = 95, .g = 95, .b = 95 })); + _ = frame.reset(.retain_capacity); + const dynamic = try p.render(frame.allocator()); + const blank = dynamic.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; + try testing.expectEqual(asPardesColor(expected[196]), blank.fg); + try testing.expectEqual(asPardesColor(expected[59]), blank.bg); + + const explicit_before_reverse = dynamic.at(tx, body_y).style.fg; + try testing.expectEqual(asPardesColor(expected[196]), explicit_before_reverse); + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); + _ = frame.reset(.retain_capacity); + const reversed = try p.render(frame.allocator()); + const reversed_blank = reversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; + try testing.expectEqual(asPardesColor(expected[59]), reversed_blank.fg); + try testing.expectEqual(asPardesColor(expected[196]), reversed_blank.bg); + const reversed_explicit = reversed.at(tx, body_y).style; + try testing.expectEqual(asPardesColor(expected[196]), reversed_explicit.bg); + try testing.expectEqual(pardes.Color{ .rgb = p.theme().bg.? }, reversed_explicit.fg); + try testing.expect(!std.meta.eql(reversed_explicit.fg, reversed_explicit.bg)); + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5l" } }); + _ = frame.reset(.retain_capacity); + const unreversed = try p.render(frame.allocator()); + const unreversed_blank = unreversed.at(tx + r.w - config.GUTTER - 1, body_y + 2).style; + try testing.expectEqual(asPardesColor(expected[196]), unreversed_blank.fg); + try testing.expectEqual(asPardesColor(expected[59]), unreversed_blank.bg); + + // The cache is keyed by values, not a theme name. Replacing a custom + // theme in place immediately recolours already-rendered indexed cells. + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]104;1\x1b\\" } }); + var custom = p.theme().*; + custom.name = try p.gpa.dupe(u8, "same-name"); + custom.palette = null; + custom.kw = .{ 1, 2, 3 }; + p.custom_theme = custom; + _ = frame.reset(.retain_capacity); + const custom_first = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .rgb = .{ 1, 2, 3 } }, custom_first.at(tx, body_y).style.fg); + if (p.custom_theme) |*theme| theme.kw = .{ 4, 5, 6 }; + _ = frame.reset(.retain_capacity); + const custom_second = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .rgb = .{ 4, 5, 6 } }, custom_second.at(tx, body_y).style.fg); +} + +test "terminal Filter keeps extended keys dark-to-light on a light theme" { + const p = try Pardes.init(std.testing.allocator, .{ .startup_config = "Theme acme\n", .tty_only = true }); + defer p.deinit(); + try std.testing.expectEqualStrings("acme", p.theme().name); + var cache: FilterPalette = .{}; + const palette = cache.get(p.theme()); + try std.testing.expect(palette[16].eql(asGhostRgb(p.theme().fg.?))); + try std.testing.expect(palette[231].eql(asGhostRgb(p.theme().bg.?))); +} + +test "terminal Filter preserves exact palette-null light theme default roles" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 5 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + + var light = p.theme().*; + light.name = try p.gpa.dupe(u8, "filter-light-defaults"); + light.bg = .{ 0xf8, 0xf8, 0xf8 }; + light.fg = .{ 0x38, 0x38, 0x38 }; + light.palette = null; + p.custom_theme = light; + + const pane = p.panes[0].?; + try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground })); + try testing.expectEqual(@as(?GColor.RGB, null), pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background })); + pane.tty_filter = true; + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = p.bodyTop(pane, r); + const ordinary = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, ordinary.at(tx, body_y).style.fg); + try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, ordinary.at(tx, body_y).style.bg); + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?5h" } }); + _ = frame.reset(.retain_capacity); + const reversed = try p.render(frame.allocator()); + try testing.expectEqual(pardes.Color{ .rgb = light.bg.? }, reversed.at(tx, body_y).style.fg); + try testing.expectEqual(pardes.Color{ .rgb = light.fg.? }, reversed.at(tx, body_y).style.bg); +} + +test "terminal Filter maps the default roles before it maps anything else" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + try testing.expect(pane.tty_filter); + + // Native dark/light palettes plus legacy helix/dark/acme, including + // the null-page fallback that only the legacy dark theme exercises. + for (0..9) |t| { + p.settings.theme = @intCast(t); + const stage_one = FilteredColors.init(p, pane); + // `dark` declares no background of its own, which is exactly why the + // resolver reads the tag colours as the fallback rather than `.?`. + const theme = p.theme(); + try testing.expect(stage_one.theme_bg.eql(asGhostRgb(theme.bg orelse theme.tag_bg))); + try testing.expect(stage_one.theme_fg.eql(asGhostRgb(theme.fg orelse theme.tag_fg))); + // With no OSC 11 in play the mapped page IS that anchor, and the + // fallback is the other one: a background never contrasts with itself. + try testing.expect(stage_one.default_bg.eql(stage_one.theme_bg)); + try testing.expect(stage_one.fallback_fg.eql(stage_one.theme_fg)); + } + + p.settings.theme = 0; + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]11;#5f5f5f\x1b\\" } }); + var moved = FilteredColors.init(p, pane); + try testing.expect(!moved.default_bg.eql(moved.theme_bg)); + try testing.expect(moved.default_bg.eql(moved.keyedRgb(.{ .r = 0x5f, .g = 0x5f, .b = 0x5f }))); +} + +test "terminal Filter refuses a foreground that would collapse onto the page" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + try testing.expect(pane.tty_filter); + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[38;2;255;255;255mW" ++ + "\x1b[0;30mB" ++ + "\x1b[0;31mR" } }); + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = p.bodyTop(pane, r); + + for (0..9) |t| { + p.settings.theme = @intCast(t); + var fc = FilteredColors.init(p, pane); + const page = asPardesColor(fc.default_bg); + const rescued = asPardesColor(fc.fallback_fg); + _ = frame.reset(.retain_capacity); + const g = try p.render(frame.allocator()); + + // The colour each of the three would have been given with no floor. + const raw_white = fc.keyedRgb(.{ .r = 255, .g = 255, .b = 255 }); + const raw_black = fc.paletteRgb(0, GColor.default[0]); + const raw_red = fc.paletteRgb(1, GColor.default[1]); + + for ([_]struct { at: u16, raw: GColor.RGB }{ + .{ .at = 0, .raw = raw_white }, + .{ .at = 1, .raw = raw_black }, + .{ .at = 2, .raw = raw_red }, + }) |case| { + const cell = g.at(tx + case.at, body_y).style; + try testing.expectEqual(page, cell.bg); + if (case.raw.contrast(fc.default_bg) < config.tty_filter_min_contrast) { + // Refused: the projection's answer is not painted, the anchor is. + try testing.expectEqual(rescued, cell.fg); + try testing.expect(!std.meta.eql(cell.fg, cell.bg)); + } else { + // Cleared the floor, so stage two leaves it exactly alone. + try testing.expectEqual(asPardesColor(case.raw), cell.fg); + } + // Either way a filtered cell delegates neither colour to a backend. + switch (cell.fg) { + .rgb => |ink| try testing.expect(asGhostRgb(ink).contrast(fc.default_bg) >= + config.tty_filter_min_contrast), + else => return error.FilteredForegroundWasNotRgb, + } + } + + // At least one of the three has to have been a real collapse, or this + // theme proved nothing: white on the light theme, black on the dark. + try testing.expect(raw_white.contrast(fc.default_bg) < config.tty_filter_min_contrast or + raw_black.contrast(fc.default_bg) < config.tty_filter_min_contrast); + // A saturated red is never the page on any curated theme. + try testing.expect(raw_red.contrast(fc.default_bg) >= config.tty_filter_min_contrast); + } +} + +test "terminal Filter holds every projected foreground off the page" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + + for (0..9) |t| { + p.settings.theme = @intCast(t); + var fc = FilteredColors.init(p, pane); + var refused: usize = 0; + for (fc.target, 0..) |projected, key| { + const ink = fc.legible(projected); + try testing.expect(ink.contrast(fc.default_bg) >= config.tty_filter_min_contrast); + if (!ink.eql(projected)) { + refused += 1; + try testing.expect(ink.eql(fc.fallback_fg)); + // Only ever refused for being too near the page. + try testing.expect(projected.contrast(fc.default_bg) < config.tty_filter_min_contrast); + } + // The key a background asks for is handed back untouched, including + // the one whose value is the page itself. + try testing.expect(fc.keyedRgb(GColor.default[key]).eql(fc.target[fc.nearestKey(GColor.default[key])])); + } + // Every curated theme owns at least one collapsing key — that is why + // the floor exists — and the floor must not be flattening the palette. + try testing.expect(refused > 0); + try testing.expect(refused < fc.target.len / 8); + } +} + +test "tty ansi colors follow the prompt hug into normal mode" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 18, .rows = 6 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + pane.tty_filter = false; + + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32mPP\x1b]133;B\x1b\\\x1b[31mR\x1b[34mB\x1b[0m out" } }); + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = p.bodyTop(pane, r); + const red: pardes.Color = .{ .rgb = p.theme().palette.?[1] }; + const blue: pardes.Color = .{ .rgb = p.theme().palette.?[4] }; + + // tty mode projects the emulator's ansi colours cell for cell. + pane.body.mode = .tty; + p.shell_rows.stale = true; + const tty = try p.render(frame.allocator()); + try testing.expectEqual(red, tty.at(tx + 2, body_y).style.fg); + try testing.expectEqual(blue, tty.at(tx + 3, body_y).style.fg); + + pane.body.mode = .normal; + p.shell_rows.stale = true; + _ = frame.reset(.retain_capacity); + const norm = try p.render(frame.allocator()); + try testing.expectEqualStrings("R", norm.at(tx, body_y).grapheme()); + try testing.expectEqualStrings("B", norm.at(tx + 1, body_y).grapheme()); + try testing.expectEqual(red, norm.at(tx, body_y).style.fg); + try testing.expectEqual(blue, norm.at(tx + 1, body_y).style.fg); +} + +test "a prompt row hidden end to end paints nothing at all" { + const testing = std.testing; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 12, .rows = 8 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + pane.tag_expanded = false; // a 12x8 screen: the body, not the tag + p.sync(); + pane.tty_filter = false; + pane.body.mode = .normal; + p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]133;A\x1b\\\x1b[32maaaaaaaaa\x1b]133;B\x1b\\\x1b[41;36m\u{754C}\x1b[0m\r\n" } }); + + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const r = p.rects[0]; + const tx = r.x + config.GUTTER; + const body_y = p.bodyTop(pane, r); + p.shell_rows.stale = true; + const s = try p.render(frame.allocator()); + + try testing.expectEqualStrings(" ", s.at(tx, body_y).grapheme()); + try testing.expect(!std.meta.eql(pardes.Color{ .rgb = p.theme().palette.?[1] }, s.at(tx, body_y).style.bg)); +} + +pub fn palColor(p: *Pardes, idx: u8) pardes.Color { + if (p.theme().palette) |pal| if (idx < 16) return .{ .rgb = pal[idx] }; + return .{ .index = idx }; +} + +pub fn ghostColor(p: *Pardes, color: ghostty_vt.Style.Color, is_bg: bool) pardes.Color { + return switch (color) { + .none => blk: { + const t = if (is_bg) p.theme().bg else p.theme().fg; + break :blk if (t) |c| .{ .rgb = c } else .default; + }, + .palette => |idx| palColor(p, idx), + .rgb => |rgb| .{ .rgb = .{ rgb.r, rgb.g, rgb.b } }, + }; +} + +/// executing at a prompt with typed text below it: pad the output area +/// with newlines so the command's output doesn't overwrite the buffer +pub fn padOutputBelowEdits(p: *Pardes, id: usize) void { + // Nothing to pad away from: with no emulator there is no prompt and no + // child whose output could land on top of the edit buffer. + if (comptime !enabled) return; + const pane = p.panes[id] orelse return; + const o = pane.ovl orelse return; + if (!pane.isTerminal()) return; + const state = pane.terminal orelse return; + if (!state.vt.cursorIsAtPrompt()) return; + // the buffer's LAST surface row: its lines may outnumber the shell + // rows it covers, and it is the bottom one output must clear + const max_row = o.row + @as(i32, @intCast(modal.lineCount(o.text))) - 1; + const goff: i32 = @intCast(state.vt.screens.active.pages.scrollbar().offset); + const cursor_abs = pane.surfRow(goff + @as(i32, @intCast(state.vt.screens.active.cursor.y))); + const pad = std.math.clamp(max_row - cursor_abs, 0, @as(i32, pane.rows)); + var i: i32 = 0; + while (i < pad) : (i += 1) p.emitWrite(id, "\r"); +} + +pub fn pushUndo(p: *Pardes, pane: *Pane) void { + pane.body.remember(p.gpa, pane.ovl); +} + +pub fn undo(p: *Pardes, pane: *Pane) void { + const back_to = pane.body.step(p.gpa, pane.ovl, true) orelse return; + if (pane.ovl) |o| p.gpa.free(o.text); + pane.ovl = back_to.ovl; + pane.ensureCursorVisible(); +} + +pub fn redo(p: *Pardes, pane: *Pane) void { + const forward_to = pane.body.step(p.gpa, pane.ovl, false) orelse return; + if (pane.ovl) |o| p.gpa.free(o.text); + pane.ovl = forward_to.ovl; + pane.ensureCursorVisible(); +} + +pub fn ptyReport(handler: *ghostty_vt.TerminalStream.Handler, data: [:0]const u8) void { + const state: *State = @alignCast(@fieldParentPtr("vt", handler.terminal)); + const room = state.reply.len - state.reply_len; + const n = @min(room, data.len); + @memcpy(state.reply[state.reply_len..][0..n], data[0..n]); + state.reply_len += @intCast(n); +} + +const DeviceAttrs = @typeInfo(@typeInfo(@typeInfo( + @FieldType(ghostty_vt.TerminalStream.Handler.Effects, "device_attributes"), +).optional.child).pointer.child).@"fn".return_type.?; +pub fn ptyDeviceAttrs(_: *ghostty_vt.TerminalStream.Handler) DeviceAttrs { + return .{}; +} diff --git a/src/tty/tty.zig b/src/tty/tty.zig index f5ae078a..3902271c 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -1915,7 +1915,7 @@ test "TTY queued results reject old PTY generations and LSP request IDs" { shell.gens[0] = 2; _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 1, .bytes = try gpa.dupe(u8, "old session\n") } }); _ = shell.apply(.{ .pty_read = .{ .id = 0, .gen = 2, .bytes = try gpa.dupe(u8, "current session\n") } }); - const text = try pardes.panes.Terminal.screenTextAlloc(core.panes[0].?, gpa); + const text = try pardes.panes.terminal.screenTextAlloc(core.panes[0].?, gpa); defer gpa.free(text); try std.testing.expect(std.mem.indexOf(u8, text, "old session") == null); try std.testing.expect(std.mem.indexOf(u8, text, "current session") != null); diff --git a/test/mode.zig b/test/mode.zig index cba93c30..767cda93 100644 --- a/test/mode.zig +++ b/test/mode.zig @@ -26,7 +26,7 @@ fn customTag(pane: *pardes.Pane, text: []const u8) !void { } test "Mode cycles terminal modes and keeps legacy toggle and custom tags" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100 }); defer p.deinit(); p.presentation.enabled = false; diff --git a/test/panes.zig b/test/panes.zig index 3b2bea0a..f7ca9fc5 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -864,7 +864,7 @@ const TtySelectionTests = struct { } test "tty selection yields to a new modal cursor selection" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); p.presentation.enabled = false; @@ -889,7 +889,7 @@ const TtySelectionTests = struct { } test "tty selection preserves its exact stream through yank clipboard and mode changes" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; for ([_]bool{ false, true }) |prompt| { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); @@ -949,7 +949,7 @@ const TtySelectionTests = struct { } test "tty selection pastes across panes once with existing bracket and mouse protocols" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; for ([_]bool{ false, true }) |bracketed| { for ([_]bool{ false, true }) |reports_mouse| { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 24 }); @@ -1028,14 +1028,14 @@ const TtySelectionTests = struct { // than the text goes and reads the desktop clipboard on its own account, // and a coding agent reading it is looking for an image, not for words. test "raw tty paste chords type at the program instead of reaching it as keys" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; for ([_]bool{ false, true }) |bracketed| { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); const pane = p.panes[0].?; try std.testing.expectEqual(panes.Text.Mode.tty, pane.body.mode); if (bracketed) p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b[?2004h" } }); - try std.testing.expectEqual(bracketed, panes.Terminal.bracketedPaste(pane)); + try std.testing.expectEqual(bracketed, panes.terminal.bracketedPaste(pane)); p.registers.put(p.gpa, '"', "one\ntwo", 0, 1, true); // what a `y` anywhere left behind var buf: [256]u8 = undefined; _ = childInput(p, &buf); @@ -1833,7 +1833,7 @@ test "terminal overlay recoloring never materializes unrelated history" { _ = try p.render(frame.allocator()); try testing.expect(p.shell_rows.pane == null); - pane.ovl.?.row = panes.Terminal.gridOffset(pane); + pane.ovl.?.row = panes.terminal.gridOffset(pane); p.gpa.free(pane.ovl.?.text); pane.ovl.?.text = try p.gpa.dupe(u8, "caf\xc3\xa9 \xe7\x95\x8c"); _ = frame.reset(.retain_capacity); @@ -1847,7 +1847,7 @@ test "terminal overlay recoloring never materializes unrelated history" { } test "terminal output keeps following new rows after scrollback eviction" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -1863,9 +1863,9 @@ test "terminal output keeps following new rows after scrollback eviction" { for (0..3) |phase| { if (phase > 0) { pane.body.mode = .normal; - panes.Terminal.scrollGrid(pane, -30); + panes.terminal.scrollGrid(pane, -30); try std.testing.expect(pages.scrollbar().offset < pages.scrollbar().total - pane.rows); - panes.Terminal.enterTty(p, 0); + panes.terminal.enterTty(p, 0); } for (phase * 20_000..(phase + 1) * 20_000) |n| { var buf: [64]u8 = undefined; @@ -1878,7 +1878,7 @@ test "terminal output keeps following new rows after scrollback eviction" { try std.testing.expect(pages.page_size <= pages.maxSize()); const sb = pages.scrollbar(); try std.testing.expectEqual(sb.total - pane.rows, sb.offset); - const full = try panes.Terminal.screenTextAlloc(pane, gpa); + const full = try panes.terminal.screenTextAlloc(pane, gpa); defer gpa.free(full); var last_buf: [16]u8 = undefined; const last = try std.fmt.bufPrint(&last_buf, "row-{d:0>5}", .{(phase + 1) * 20_000 - 1}); @@ -1908,7 +1908,7 @@ test "terminal output keeps following new rows after scrollback eviction" { } test "terminal edit stays on its surviving row when old scrollback is evicted" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -1946,7 +1946,7 @@ test "terminal edit stays on its surviving row when old scrollback is evicted" { } } try std.testing.expect(removed > 0 and removed < original_row); - const full = try panes.Terminal.screenTextAlloc(pane, gpa); + const full = try panes.terminal.screenTextAlloc(pane, gpa); defer gpa.free(full); const row = original_row - @as(i32, @intCast(removed)); try std.testing.expectEqualStrings(last, modal.lineSlice(full, @intCast(row))); @@ -1956,7 +1956,7 @@ test "terminal edit stays on its surviving row when old scrollback is evicted" { } test "terminal edits and undo survive partial history clearing and whole-screen loss" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const Action = enum { clear_history, partial_clear_history, reset_primary, reset_alternate, evict_all, hidden_undo }; for (std.enums.values(Action)) |action| { @@ -1978,7 +1978,7 @@ test "terminal edits and undo survive partial history clearing and whole-screen pane.body.cur_col = 4; pane.body.cur_pinned = true; pane.body.vsel = .{ .active = true, .row = row, .col = 1 }; - panes.Terminal.pushUndo(p, pane); + panes.terminal.pushUndo(p, pane); const overlay = pane.ovl.?; pane.body.ed_redo[0] = .{ .ovl = .{ .row = overlay.row, .rows = overlay.rows, .text = try gpa.dupe(u8, overlay.text) }, @@ -1990,7 +1990,7 @@ test "terminal edits and undo survive partial history clearing and whole-screen if (action == .hidden_undo) { gpa.free(pane.ovl.?.text); pane.ovl = null; - panes.Terminal.enterTty(p, 0); + panes.terminal.enterTty(p, 0); } const bytes = switch (action) { .clear_history, .partial_clear_history => "\x1b[3J", @@ -2006,20 +2006,20 @@ test "terminal edits and undo survive partial history clearing and whole-screen try std.testing.expectEqual(expected + 1, pane.body.cur_row); try std.testing.expectEqual(expected, pane.body.vsel.row); } - for ([_]panes.Terminal.Snapshot{ pane.body.ed_undo[0], pane.body.ed_redo[0] }) |snapshot| { + for ([_]panes.terminal.Snapshot{ pane.body.ed_undo[0], pane.body.ed_redo[0] }) |snapshot| { try std.testing.expectEqual(expected, snapshot.ovl.?.row); try std.testing.expectEqual(expected + 1, snapshot.cur_row); try std.testing.expectEqualStrings("edit one\nedit two", snapshot.ovl.?.text); } try std.testing.expectEqual(@as(usize, 2), pane.terminal.?.vt.screens.active.pages.countTrackedPins()); - panes.Terminal.undo(p, pane); + panes.terminal.undo(p, pane); try std.testing.expectEqualStrings("edit one\nedit two", pane.ovl.?.text); try std.testing.expectEqual(expected, pane.ovl.?.row); } } test "terminal lower scroll regions do not move edits above them" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -2030,23 +2030,23 @@ test "terminal lower scroll regions do not move edits above them" { pane.ovl = .{ .row = 1, .rows = 1, .text = try gpa.dupe(u8, "unsent") }; pane.body.cur_row = 1; pane.body.cur_pinned = true; - panes.Terminal.pushUndo(p, pane); - const total = panes.Terminal.scrollbar(pane).total; + panes.terminal.pushUndo(p, pane); + const total = panes.terminal.scrollbar(pane).total; var setup: [64]u8 = undefined; const bytes = try std.fmt.bufPrint(&setup, "\x1b[4;{d}r\x1b[{d};1H", .{ pane.rows, pane.rows }); p.update(.{ .output = .{ .pane = 0, .bytes = bytes } }); p.update(.{ .output = .{ .pane = 0, .bytes = "tail\r\n" ** 50 } }); - try std.testing.expectEqual(total, panes.Terminal.scrollbar(pane).total); + try std.testing.expectEqual(total, panes.terminal.scrollbar(pane).total); try std.testing.expectEqual(@as(i32, 1), pane.ovl.?.row); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); try std.testing.expectEqual(@as(i32, 1), pane.body.ed_undo[0].ovl.?.row); - const full = try panes.Terminal.screenTextAlloc(pane, gpa); + const full = try panes.terminal.screenTextAlloc(pane, gpa); defer gpa.free(full); try std.testing.expect(std.mem.startsWith(u8, full, "top\nsecond\nthird\n")); } test "terminal eviction and lower-region scrolling in one read preserve a surviving edit" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); @@ -2071,7 +2071,7 @@ test "terminal eviction and lower-region scrolling in one read preserve a surviv pane.ovl = .{ .row = old_row, .rows = 1, .text = try gpa.dupe(u8, "kept edit") }; pane.body.cur_row = old_row; pane.body.cur_pinned = true; - panes.Terminal.pushUndo(p, pane); + panes.terminal.pushUndo(p, pane); const old_total = pages.total_rows; var buf: [128]u8 = undefined; const bytes = try std.fmt.bufPrint(&buf, "new\r\n\x1b[4;{d}r\x1b[{d};1Hregion\r\n", .{ pane.rows, pane.rows }); @@ -3342,11 +3342,11 @@ const TerminalTests = struct { // Tests asserting raw ANSI indices explicitly select helix, whose palette // is inherited. Native-palette coverage lives in the overlay/eviction and // trailing-blank tests and checks their concrete RGB values instead. - const gridOffset = panes.Terminal.gridOffset; - const scrollGrid = panes.Terminal.scrollGrid; - const promptInputReady = panes.Terminal.promptInputReady; - const forwardKey = panes.Terminal.forwardKey; - const enterTty = panes.Terminal.enterTty; + const gridOffset = panes.terminal.gridOffset; + const scrollGrid = panes.terminal.scrollGrid; + const promptInputReady = panes.terminal.promptInputReady; + const forwardKey = panes.terminal.forwardKey; + const enterTty = panes.terminal.enterTty; // Align normal-mode glyphs with the VT grid and compare their styles. fn modeStyleDiffs(p: *Pardes, pane: *Pane, gpa: std.mem.Allocator, note: []const u8) !usize { @@ -4798,7 +4798,7 @@ test "Zig keywords keep every rendered byte colored across line-number widths" { } test "terminal overlays preserve trailing blank styles without coloring inserted rows" { - if (comptime !panes.Terminal.enabled) return error.SkipZigTest; + if (comptime !panes.terminal.enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); diff --git a/test/perf-baseline-gui-Debug.json b/test/perf-baseline-gui-Debug.json index 56a5da91..567a8b02 100644 --- a/test/perf-baseline-gui-Debug.json +++ b/test/perf-baseline-gui-Debug.json @@ -1 +1 @@ -{"harness":"5cbb536cdc74cbcf","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2022,"med_us":2284,"p90_us":2363,"max_us":2431},{"op":"render","fixture":"medium","min_us":80,"med_us":83,"p90_us":90,"max_us":94},{"op":"key-down","fixture":"medium","min_us":79,"med_us":82,"p90_us":87,"max_us":97},{"op":"key-right","fixture":"medium","min_us":82,"med_us":83,"p90_us":91,"max_us":95},{"op":"page-down","fixture":"medium","min_us":79,"med_us":83,"p90_us":84,"max_us":86},{"op":"wheel","fixture":"medium","min_us":79,"med_us":82,"p90_us":85,"max_us":87},{"op":"edit-char","fixture":"medium","min_us":1190,"med_us":1621,"p90_us":1843,"max_us":2008},{"op":"body-2m","fixture":"medium","min_us":9178,"med_us":16872,"p90_us":20886,"max_us":22596}]} +{"harness":"75a55b9f838d3f0","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2022,"med_us":2284,"p90_us":2363,"max_us":2431},{"op":"render","fixture":"medium","min_us":80,"med_us":83,"p90_us":90,"max_us":94},{"op":"key-down","fixture":"medium","min_us":79,"med_us":82,"p90_us":87,"max_us":97},{"op":"key-right","fixture":"medium","min_us":82,"med_us":83,"p90_us":91,"max_us":95},{"op":"page-down","fixture":"medium","min_us":79,"med_us":83,"p90_us":84,"max_us":86},{"op":"wheel","fixture":"medium","min_us":79,"med_us":82,"p90_us":85,"max_us":87},{"op":"edit-char","fixture":"medium","min_us":1190,"med_us":1621,"p90_us":1843,"max_us":2008},{"op":"body-2m","fixture":"medium","min_us":9178,"med_us":16872,"p90_us":20886,"max_us":22596}]} diff --git a/test/perf-baseline-tty-Debug.json b/test/perf-baseline-tty-Debug.json index 9c4b5ebe..8ba0cdec 100644 --- a/test/perf-baseline-tty-Debug.json +++ b/test/perf-baseline-tty-Debug.json @@ -1 +1 @@ -{"harness":"5cbb536cdc74cbcf","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1902,"med_us":2386,"p90_us":2484,"max_us":2686},{"op":"render","fixture":"medium","min_us":83,"med_us":87,"p90_us":93,"max_us":118},{"op":"key-down","fixture":"medium","min_us":88,"med_us":94,"p90_us":100,"max_us":156},{"op":"key-right","fixture":"medium","min_us":83,"med_us":86,"p90_us":88,"max_us":92},{"op":"page-down","fixture":"medium","min_us":78,"med_us":84,"p90_us":89,"max_us":101},{"op":"wheel","fixture":"medium","min_us":77,"med_us":84,"p90_us":89,"max_us":132},{"op":"edit-char","fixture":"medium","min_us":1177,"med_us":1519,"p90_us":1721,"max_us":1909},{"op":"body-2m","fixture":"medium","min_us":8533,"med_us":15772,"p90_us":21361,"max_us":23276}]} +{"harness":"75a55b9f838d3f0","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1902,"med_us":2386,"p90_us":2484,"max_us":2686},{"op":"render","fixture":"medium","min_us":83,"med_us":87,"p90_us":93,"max_us":118},{"op":"key-down","fixture":"medium","min_us":88,"med_us":94,"p90_us":100,"max_us":156},{"op":"key-right","fixture":"medium","min_us":83,"med_us":86,"p90_us":88,"max_us":92},{"op":"page-down","fixture":"medium","min_us":78,"med_us":84,"p90_us":89,"max_us":101},{"op":"wheel","fixture":"medium","min_us":77,"med_us":84,"p90_us":89,"max_us":132},{"op":"edit-char","fixture":"medium","min_us":1177,"med_us":1519,"p90_us":1721,"max_us":1909},{"op":"body-2m","fixture":"medium","min_us":8533,"med_us":15772,"p90_us":21361,"max_us":23276}]} diff --git a/test/perf-baseline-tty-ReleaseFast.json b/test/perf-baseline-tty-ReleaseFast.json index 984d480a..ab5ed3b6 100644 --- a/test/perf-baseline-tty-ReleaseFast.json +++ b/test/perf-baseline-tty-ReleaseFast.json @@ -1 +1 @@ -{"harness":"5cbb536cdc74cbcf","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2061,"med_us":2326,"p90_us":2462,"max_us":2503},{"op":"render","fixture":"medium","min_us":76,"med_us":80,"p90_us":86,"max_us":98},{"op":"key-down","fixture":"medium","min_us":78,"med_us":83,"p90_us":91,"max_us":95},{"op":"key-right","fixture":"medium","min_us":77,"med_us":81,"p90_us":86,"max_us":90},{"op":"page-down","fixture":"medium","min_us":77,"med_us":81,"p90_us":89,"max_us":90},{"op":"wheel","fixture":"medium","min_us":75,"med_us":82,"p90_us":87,"max_us":94},{"op":"edit-char","fixture":"medium","min_us":1277,"med_us":1713,"p90_us":1948,"max_us":2063},{"op":"body-2m","fixture":"medium","min_us":9261,"med_us":17043,"p90_us":23512,"max_us":23722}]} +{"harness":"75a55b9f838d3f0","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2061,"med_us":2326,"p90_us":2462,"max_us":2503},{"op":"render","fixture":"medium","min_us":76,"med_us":80,"p90_us":86,"max_us":98},{"op":"key-down","fixture":"medium","min_us":78,"med_us":83,"p90_us":91,"max_us":95},{"op":"key-right","fixture":"medium","min_us":77,"med_us":81,"p90_us":86,"max_us":90},{"op":"page-down","fixture":"medium","min_us":77,"med_us":81,"p90_us":89,"max_us":90},{"op":"wheel","fixture":"medium","min_us":75,"med_us":82,"p90_us":87,"max_us":94},{"op":"edit-char","fixture":"medium","min_us":1277,"med_us":1713,"p90_us":1948,"max_us":2063},{"op":"body-2m","fixture":"medium","min_us":9261,"med_us":17043,"p90_us":23512,"max_us":23722}]} diff --git a/test/perf.zig b/test/perf.zig index 38c640b4..fca4a3b0 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -275,12 +275,12 @@ fn measureCreation(io: std.Io, reps: usize, json: bool) !void { const allocator = counter.allocator(); const begin = nowNs(); const pane = if (terminal) - try pardes.panes.Terminal.create(allocator, screen_cols, screen_rows) + try pardes.panes.terminal.create(allocator, screen_cols, screen_rows) else - try pardes.panes.Terminal.createDoc(allocator, screen_cols, screen_rows); + try pardes.panes.terminal.createDoc(allocator, screen_cols, screen_rows); const constructed = nowNs(); const retained = counter.live; - pardes.panes.Terminal.deinitEmulator(pane, allocator); + pardes.panes.terminal.deinitEmulator(pane, allocator); allocator.destroy(pane); const destroyed = nowNs(); if (counter.live != 0) return error.LeakedPaneMemory; @@ -707,7 +707,7 @@ fn checkTerminalTail(core: *pardes.Pardes, surface: *pardes.Surface, batch: usiz const pane = core.panes[0] orelse return error.MissingTerminal; const rect = core.rects[0]; const x = rect.x + pardes.config.GUTTER; - const y = (if (core.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H) + pardes.panes.Terminal.gridCursor(pane).y; + const y = (if (core.settings.tag_bottom) rect.y else rect.y + pardes.BOX_H) + pardes.panes.terminal.gridCursor(pane).y; var expected_buffer: [32]u8 = undefined; const expected = try std.fmt.bufPrint(&expected_buffer, "TURN {d:0>10} READY", .{batch}); for (expected, 0..) |byte, col| { @@ -773,7 +773,7 @@ fn measureUndoOutput(core: *pardes.Pardes, counter: *Allocations, arena: *std.he pane.body.cur_row = first + 1; pane.body.cur_col = 1; pane.body.vsel = .{ .active = true, .row = first, .col = 0 }; - pardes.panes.Terminal.pushUndo(core, pane); + pardes.panes.terminal.pushUndo(core, pane); core.gpa.free(pane.ovl.?.text); pane.ovl = null; if (pane.body.ed_undo_len != index + 1) return error.TerminalUndoSnapshotFailed; @@ -782,7 +782,7 @@ fn measureUndoOutput(core: *pardes.Pardes, counter: *Allocations, arena: *std.he for (pane.body.ed_undo[0..pane.body.ed_undo_len]) |snapshot| if (snapshot.ovl) |overlay| core.gpa.free(overlay.text); pane.body.ed_undo_len = 0; } - pardes.panes.Terminal.enterTty(core, 0); + pardes.panes.terminal.enterTty(core, 0); pump(core); const tracked_before = pages.countTrackedPins(); const start = try pages.trackPin(pages.pin(.{ .screen = .{ .y = @intCast(first) } }).?); @@ -895,7 +895,7 @@ fn measureTerminalSession(io: std.Io, mib: usize, reps: usize, json: bool) !void } const stream_wall_ns = nowNs() - stream_begin; const live_after_output = counter.live; - const first_row = @as(i32, @intCast(state.vt.screens.active.pages.scrollbar().offset)) + @as(i32, pardes.panes.Terminal.gridCursor(pane).y); + const first_row = @as(i32, @intCast(state.vt.screens.active.pages.scrollbar().offset)) + @as(i32, pardes.panes.terminal.gridCursor(pane).y); _ = arena.reset(.retain_capacity); const modal_begin = nowNs(); core.update(.{ .key = .{ .cp = core.opts.tty_toggle, .ctrl = true } }); @@ -943,7 +943,7 @@ fn measureTerminalSession(io: std.Io, mib: usize, reps: usize, json: bool) !void const begin = nowNs(); core.update(.{ .output = .{ .pane = 0, .bytes = update } }); pump(core); - const cursor_row = pardes.panes.Terminal.gridOffset(pane) + @as(i32, pardes.panes.Terminal.gridCursor(pane).y); + const cursor_row = pardes.panes.terminal.gridOffset(pane) + @as(i32, pardes.panes.terminal.gridCursor(pane).y); pane.ovl.?.row = if (phase == 0) 0 else cursor_row - 1; pane.body.cur_row = pane.ovl.?.row; pane.body.cur_col = 0; -- cgit v1.3 From d4960472375ea68f709c56a677d8a37571419ff7 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 29 Sep 2026 22:27:38 -0300 Subject: Config opens the startup file, DumpConfig the settings report, and the workspace tag reads Dump Themes Config Debug Exit Config (SPC f c) opens init, found as the settings report finds it (opts.startup_config_path: $XDG_CONFIG_HOME/pardes/init or ~/.config/pardes/init, and the macOS and Windows paths config.md gives). A pane that already holds it is gone to instead; a file on disk is looked at; with none, an empty pane is named for it, and Save makes its directory and any above it first (File.make_dirs, fs.makeDirs) before writing. Without a configuration directory it says so and opens nothing. The report Config used to open, the startup path and every live setting, is DumpConfig, in a +DumpConfig pane. No alias keeps the old meaning. The workspace tag's default words put Themes where NextColor was, NextColor staying a builtin, and Config beside it. A tag the user edited is kept as it was: a dump stores only an edited one (topbar_custom), and a restore puts back only that. theme.snap types NextColor onto the workspace tag to click it, and tagnav's walk back to Dump takes five long-word steps. The rest of the re-recorded goldens differ in the workspace words and their widths only. Co-Authored-By: Claude Opus 5.5 --- docs/config.md | 11 ++-- docs/macos.md | 4 +- docs/tags.md | 4 +- docs/themes.md | 2 +- docs/ui-review.md | 2 +- src/CHANGELOG.md | 10 +++ src/File.zig | 4 ++ src/Messages.zig | 2 +- src/Output.zig | 2 +- src/builtins.zig | 32 +++++++++- src/config.zig | 11 ++-- src/crash.zig | 2 +- src/fs.zig | 19 ++++++ src/ninep/ctl.zig | 6 +- src/pardes.zig | 10 +-- src/tutor.txt | 4 +- test/appearance_gallery.py | 4 +- test/font_size.py | 4 +- test/output.zig | 98 +++++++++++++++++++++++++++--- test/snapshots/argv.golden | 8 +-- test/snapshots/badutf.golden | 2 +- test/snapshots/boot.golden | 2 +- test/snapshots/builtins.golden | 2 +- test/snapshots/chordcut.golden | 2 +- test/snapshots/cmdexit.golden | 2 +- test/snapshots/cmdword.golden | 2 +- test/snapshots/colgrip.golden | 2 +- test/snapshots/collapse.golden | 6 +- test/snapshots/cornerdrag-left.golden | 2 +- test/snapshots/cornerdrag.golden | 2 +- test/snapshots/cursorline.golden | 2 +- test/snapshots/delask.golden | 2 +- test/snapshots/doccol.golden | 2 +- test/snapshots/dump.golden | 2 +- test/snapshots/edit.golden | 2 +- test/snapshots/emptycol.golden | 2 +- test/snapshots/exec-bigdrag.golden | 2 +- test/snapshots/exec.golden | 2 +- test/snapshots/fileedit.golden | 2 +- test/snapshots/filewatch.golden | 2 +- test/snapshots/find.golden | 2 +- test/snapshots/fsearch.golden | 2 +- test/snapshots/ghostty-mid.golden | 2 +- test/snapshots/grep.golden | 2 +- test/snapshots/headersweep-restored.golden | 4 +- test/snapshots/headersweep.golden | 6 +- test/snapshots/hscroll.golden | 2 +- test/snapshots/images.golden | 4 +- test/snapshots/jumps.golden | 2 +- test/snapshots/layout-close.golden | 2 +- test/snapshots/layout-open.golden | 2 +- test/snapshots/leader.golden | 2 +- test/snapshots/load.golden | 2 +- test/snapshots/logquiet.golden | 2 +- test/snapshots/look-center.golden | 2 +- test/snapshots/look-dir.golden | 2 +- test/snapshots/look-file-1col.golden | 2 +- test/snapshots/look-file.golden | 2 +- test/snapshots/lookloaded.golden | 2 +- test/snapshots/lookpanes.golden | 2 +- test/snapshots/lookrange.golden | 2 +- test/snapshots/lsp-client-edit.golden | 2 +- test/snapshots/lsp-client.golden | 2 +- test/snapshots/lsp-rename.golden | 2 +- test/snapshots/lsp.golden | 2 +- test/snapshots/lspcomplete.golden | 8 +-- test/snapshots/lspcompletemoved.golden | 2 +- test/snapshots/lspdebug.golden | 2 +- test/snapshots/lsprelpath.golden | 4 +- test/snapshots/markup.golden | 4 +- test/snapshots/mini.golden | 12 ++-- test/snapshots/modal.golden | 2 +- test/snapshots/msg.golden | 4 +- test/snapshots/multicursor.golden | 2 +- test/snapshots/nested.golden | 6 +- test/snapshots/ninep.golden | 12 ++-- test/snapshots/pipe.golden | 2 +- test/snapshots/psearch.golden | 2 +- test/snapshots/reflow.golden | 2 +- test/snapshots/respawn.golden | 2 +- test/snapshots/restore.golden | 2 +- test/snapshots/rsearch.golden | 2 +- test/snapshots/savepane.golden | 2 +- test/snapshots/scroll.golden | 2 +- test/snapshots/scrolloff.golden | 2 +- test/snapshots/selarg.golden | 2 +- test/snapshots/selregex.golden | 2 +- test/snapshots/shellset.golden | 2 +- test/snapshots/shrinktag.golden | 2 +- test/snapshots/splitparent.golden | 6 +- test/snapshots/stepgrain.golden | 2 +- test/snapshots/syntax.golden | 2 +- test/snapshots/tag.golden | 2 +- test/snapshots/tagalign.golden | 10 +-- test/snapshots/tagalign2col.golden | 2 +- test/snapshots/tagbottom.golden | 2 +- test/snapshots/tagbottomimage.golden | 2 +- test/snapshots/tagbottomshort.golden | 12 ++-- test/snapshots/tagcmd.golden | 2 +- test/snapshots/tagnav.golden | 8 +-- test/snapshots/tagnav.snap | 4 +- test/snapshots/tagpath.golden | 2 +- test/snapshots/theme.golden | 40 ++++++------ test/snapshots/theme.snap | 8 +++ test/snapshots/themesel.golden | 2 +- test/snapshots/tinywin.golden | 6 +- test/snapshots/topbarexec.golden | 2 +- test/snapshots/tty.golden | 2 +- test/snapshots/ttyclick.golden | 2 +- test/snapshots/ttyedit.golden | 2 +- test/snapshots/ttyfollow.golden | 2 +- test/snapshots/ttyhelp.golden | 2 +- test/snapshots/ttylook.golden | 2 +- test/snapshots/ttyonly.golden | 2 +- test/snapshots/ttypaste.golden | 2 +- test/snapshots/ttyprompt.golden | 2 +- test/snapshots/ttytaken.golden | 2 +- test/snapshots/tutor.golden | 2 +- test/snapshots/wheeldrift.golden | 2 +- test/snapshots/winch.golden | 4 +- test/snapshots/windownav.golden | 2 +- test/snapshots/windowops.golden | 4 +- test/snapshots/wrap.golden | 2 +- test/snapshots/yankpaste.golden | 2 +- test/window_opacity.py | 12 ++-- 125 files changed, 371 insertions(+), 218 deletions(-) (limited to 'src/File.zig') diff --git a/docs/config.md b/docs/config.md index f25c8746..bc4acf12 100644 --- a/docs/config.md +++ b/docs/config.md @@ -31,10 +31,13 @@ not stop later ones. Text that is no builtin is not run as a shell command (`Exec ...` still is). Key bindings are compile-time choices in `src/config.zig`; `init` does not remap them. -`Config` (`SPC f c`) opens a `+Config` pane with the startup path (a right -click opens it) and every live setting; a setting the frontend cannot show -reads `unsupported`. The root `ctl` file reads the settings back in the -words a write takes ([fs.md](fs.md#the-root-ctl)). +`Config` (`SPC f c`) opens `init` itself in a pane, or goes to its pane when +it is open. With no file there yet, the pane is named for it, empty, and +Save writes it, making its directory first. `DumpConfig` opens a +`+DumpConfig` pane with the startup path (a right click opens it) and every +live setting; a setting the frontend cannot show reads `unsupported`. The +root `ctl` file reads the settings back in the words a write takes +([fs.md](fs.md#the-root-ctl)). ## Settings diff --git a/docs/macos.md b/docs/macos.md index 8bb81be6..5512edbd 100644 --- a/docs/macos.md +++ b/docs/macos.md @@ -525,7 +525,7 @@ what is on screen. Cmd+=, Cmd- and Cmd+0 change the point size, rebuild `Metrics`, and report the new cell through the same resize path a window drag uses. They also observe the -effective face/point tuple through `pardes_font_observe`, so the single `Config` +effective face/point tuple through `pardes_font_observe`, so the single `DumpConfig` report follows a host-owned zoom without resolving a pending face request. The initial system face is observed the same way. Cmd+= rather than Cmd++ because AppKit matches the character and `=` is what is under the finger. @@ -759,7 +759,7 @@ separation is currently macOS-specific; other hosts keep the opaque raster path. `WindowBlur <0..100>` controls the strength of that native backdrop independently of `WindowOpacity`. It is a macOS-only builtin, also accepted in the startup -config and reported by `Config`. It defaults to 0 (off); 100 shows the full +config and reported by `DumpConfig`. It defaults to 0 (off); 100 shows the full AppKit material and intermediate values blend the material with the unblurred backdrop using the effect view's alpha. An opaque themed background hides the effect; lowering `WindowOpacity` makes the remembered strength visible again. diff --git a/docs/tags.md b/docs/tags.md index 8fe63804..93c8a6fa 100644 --- a/docs/tags.md +++ b/docs/tags.md @@ -11,8 +11,8 @@ pane's directory. Over 9P the tags are `/tag`, `/col//tag` and ## Default words -- Workspace: `Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor - Debug Exit`. +- Workspace: `Newcol Joincol Find Grep Help Changelog Tutor Dump Themes + Config Debug Exit`. - Column: `New Tty Find Grep Joincol Delcol`. - File pane: `Save Tty Collapse Del`; a source file with a grammar adds `TreeContext`, a result list `LocationsConfig`. PDF: `manual.pdf [1/12] diff --git a/docs/themes.md b/docs/themes.md index d163b243..c7204173 100644 --- a/docs/themes.md +++ b/docs/themes.md @@ -174,7 +174,7 @@ colors switch directly so syntax and ANSI content stay coherent. `FocusTint` toggles the focused pane's tag tint, which is on by default. `SyntaxBold` toggles bold syntax keywords, which are off by default. Both commands take no argument, work in GUI and TTY, and report their states in -`Config`. Use them in the startup configuration to reverse the defaults. +`DumpConfig`. Use them in the startup configuration to reverse the defaults. The original required roles remain unchanged: nullable `bg` and `fg`, `sel_bg`, `sel_fg`, `tag_bg`, `tag_fg`, `box`, `box_dim`, `kw`, `str`, `num`, diff --git a/docs/ui-review.md b/docs/ui-review.md index decf042d..6702ce31 100644 --- a/docs/ui-review.md +++ b/docs/ui-review.md @@ -206,7 +206,7 @@ pass does not change that environment code or skip the affected tests. The appearance checks cover native palette contrast, old ThemeFile documents, wrapped search matches, selection precedence, immediate body colors during theme fades, light-theme carets and both quiet and bold syntax preferences. -The 9P walkthrough also verifies `FocusTint` and `SyntaxBold` through `Config`. +The 9P walkthrough also verifies `FocusTint` and `SyntaxBold` through `DumpConfig`. All 97 terminal snapshot scripts passed without retries after reviewing and refreshing 32 appearance goldens. Of those, 27 preserve identical visible text, diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index 50149551..ca37856e 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -1,5 +1,15 @@ # Changelog +## Unreleased + +- `Config` (`SPC f c`) opens the startup file, `init`, in a pane, or goes + to its pane when it is open. With no file yet, it opens an empty pane of + that name, and Save writes it, making the directory first. The settings + report `Config` used to open is `DumpConfig`, in a `+DumpConfig` pane. +- The workspace tag reads `… Dump Themes Config Debug Exit`: `Themes` in + place of `NextColor`, which stays a builtin, and `Config` beside it. A + workspace tag you edited, and one a dump kept, stays as it is. + ## 0.0.5 - Over a slow link the terminal build keeps at most one frame in flight: it diff --git a/src/File.zig b/src/File.zig index 8babb27d..e8a9e2f8 100644 --- a/src/File.zig +++ b/src/File.zig @@ -58,6 +58,10 @@ pub const State = struct { /// as an undo to the save point is in acme. saved_hash: ?u64 = null, watch_after_save: bool = false, + /// Save makes the file's directory, and any above it, first: `Config`'s + /// pane for an init file that is not there yet, whose directory may not + /// be either. + make_dirs: bool = false, /// The file changed on disk under unsaved edits, which were kept (see /// `changed`): its hash, so the same change is said once, until a Save /// or get settles it. A Save warns once before overwriting it, as acme's diff --git a/src/Messages.zig b/src/Messages.zig index 7dcb22ed..d1478ac7 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -782,7 +782,7 @@ test "a message falls in, lingers past the input that dismisses it, and dissolve try std.testing.expect(p.executeBuiltinLine(p.active, "MessageDissolve 0")); try std.testing.expectEqual(@as(u16, 3), messageFrames(p.settings.message_fall_ms)); try std.testing.expectEqual(@as(u16, 1), messageFrames(p.settings.message_dissolve_ms)); - // The Config report reads back as configuration. + // The DumpConfig report reads back as configuration. try std.testing.expect(p.executeBuiltinLine(p.active, "MessageAnimation")); try std.testing.expect(!p.settings.message_animation); try std.testing.expect(p.executeBuiltinLine(p.active, "Msg plain")); diff --git a/src/Output.zig b/src/Output.zig index fb8fe7a3..69e9644c 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -835,7 +835,7 @@ pub fn openConfig(p: *Pardes, id: usize) !void { .state = &p.settings, }); const content = try out.toOwnedSlice(); - return openRead(p, id, .{ .cmd = .Config }, "", content); + return openRead(p, id, .{ .cmd = .DumpConfig }, "", content); } /// The message-row log, oldest first — the lines that were said in passing and diff --git a/src/builtins.zig b/src/builtins.zig index c549b17f..c40b2e00 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1283,10 +1283,38 @@ pub const Help = struct { } }; -/// Open the settings in effect, each a word to click. +/// Open the startup file, `init`, in a pane: its pane when it is open, else +/// the file, else a pane of that name for Save to make it and its directory. pub const Config = struct { pub const scope: Scope = .session; - pub const output: OutputTraits = .{ .name = config.config_buffer }; + pub fn run(c: Ctx) void { + const path = c.p.opts.startup_config_path orelse + return c.p.reportFailure(c.id, "Config: no startup file here: no configuration directory"); + var real_buf: [4096]u8 = undefined; + const real = if (pardes.filesystem.resolveOs(path, &real_buf)) |r| r.path else null; + for (c.p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + const f = pane.file orelse continue; + if (f.output != null) continue; + if (!std.mem.eql(u8, f.path, path) and !(if (real) |r| std.mem.eql(u8, f.path, r) else false)) continue; + return look.focusPaneLine(c.p, id, .{}, .keep); + } + if (real != null) return look.lookAt(c.p, c.id, path); + // Not there yet: a pane named for it, which Save makes. + const free = c.p.freeSlot() orelse return c.p.reportError(c.id, "Config", error.NoPaneSlots); + c.p.newScratchFor(c.id, .scratch); + const pane = c.p.panes[free] orelse return; + @import("ninep/pane.zig").nameBuffer(c.p, free, path, false) catch |err| return c.p.reportError(c.id, "Config", err); + pane.file.?.make_dirs = true; + c.p.active = free; + } +}; + +/// Open the settings in effect, each a word to click, and the startup +/// file's path. +pub const DumpConfig = struct { + pub const scope: Scope = .session; + pub const output: OutputTraits = .{ .name = config.dump_config_buffer }; pub fn run(c: Ctx) void { panes.Output.openConfig(c.p, c.id) catch |err| c.p.reportError(c.id, "config", err); } diff --git a/src/config.zig b/src/config.zig index ea7a877a..bb033823 100644 --- a/src/config.zig +++ b/src/config.zig @@ -68,6 +68,7 @@ pub const leader_path = paths: { .Recent = "fr", .Grep = "fg", .Config = "fc", + .DumpConfig = null, .LocationsConfig = null, .Tutor = "ht", .Changelog = "hc", @@ -266,7 +267,7 @@ pub const child_term = "xterm-256color"; pub const child_colorterm = "truecolor"; pub const child_term_program = "pardes"; -pub const topbar_str = "Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit"; +pub const topbar_str = "Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit"; pub const pane_builtins_str = "Tty Collapse Del"; pub const pdf_pane_builtins_str = "Tty PdfSections PdfTint Collapse Del"; @@ -452,7 +453,7 @@ pub const pipe_marker = " |"; pub const search_buffer = "+Search"; pub const help_buffer = "+Help"; -pub const config_buffer = "+Config"; +pub const dump_config_buffer = "+DumpConfig"; pub const effect_code_buffer = "+EffectCode"; pub const jumps_buffer = "+Jumps"; pub const recent_buffer = "+Recent"; @@ -968,7 +969,7 @@ pub const Runtime = struct { } }; - // The builtin registry and Config report share this command table. + // The builtin registry and DumpConfig report share this command table. pub const settings = [_]Setting{ .{ .word = "Colors", .action = .{ .toggle = .colors }, .doc = "Syntax colours in text panes, on or off." }, .{ .word = "Wrap", .action = .{ .toggle = .wrap }, .doc = "Long lines wrap onto the next row, on or off." }, @@ -1292,7 +1293,7 @@ pub const Runtime = struct { /// Each line reads as the command that would set it: the word, then the /// value you would type after it. No colons, no units — `WindowOpacity 70` - /// is both what Config prints and what you write back. + /// is both what DumpConfig prints and what you write back. pub fn writeReport(out: *std.Io.Writer, context: ReportContext) !void { const state = context.state; var wrote_transition = false; @@ -1653,7 +1654,7 @@ pub const Runtime = struct { try std.testing.expect(FontSpec.parse(bad) == null); } - test "Config report observes every simple setting and all live context" { + test "DumpConfig report observes every simple setting and all live context" { var state: Runtime = .{}; // Every setting, every context line: the report outgrows 4K. var storage: [8192]u8 = undefined; diff --git a/src/crash.zig b/src/crash.zig index 10d38591..99822aad 100644 --- a/src/crash.zig +++ b/src/crash.zig @@ -23,7 +23,7 @@ const std = @import("std"); const builtin = @import("builtin"); const pardes = @import("pardes.zig"); -/// Beside `init`, so `Config` opens the directory that holds both. +/// The crash log's name, beside `init` in the configuration directory. pub const name = "crashes"; /// The config directory `config.User.load` resolved, COPIED rather than diff --git a/src/fs.zig b/src/fs.zig index fc3eb98f..1d0bbc22 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -637,6 +637,25 @@ test "a path with a part over 255 bytes is NameTooLong, never a panic" { try std.testing.expectError(error.NameTooLong, statPath(std.testing.io, long, .{})); } +/// Make `dir` and each directory above it that is missing, as `mkdir -p` +/// does: one already there is no failure. A failure shows at the open +/// that follows. +pub fn makeDirs(dir: []const u8) void { + if (comptime !platform_has_fs) return; + var z: [4096:0]u8 = undefined; + if (dir.len == 0 or dir.len >= z.len) return; + @memcpy(z[0..dir.len], dir); + z[dir.len] = 0; + pardes.turn.yield(); + defer pardes.turn.back(); + for (z[1..dir.len], 1..) |c, i| if (c == '/') { + z[i] = 0; + _ = libc.mkdir(z[0..i :0], 0o755); + z[i] = '/'; + }; + _ = libc.mkdir(z[0..dir.len :0], 0o755); +} + pub fn localPath(path: []const u8) ?[]const u8 { if (std.mem.eql(u8, path, "/n/os")) return "/"; if (std.mem.startsWith(u8, path, "/n/os/")) return path[5..]; diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 060e0d6c..5ed03c58 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -485,7 +485,7 @@ const e_prompt = "control message needs its argument"; /// Every setting, one a line, in the words a write of it takes, so that the /// file read back is the configuration, as webfs's ctl reads (webfs(4)). /// What is not a setting -- platform, themes, where the config came from -- -/// is /status's or the Config window's. +/// is /status's or the DumpConfig window's. fn writeSettings(p: *Pardes, w: *std.Io.Writer) !void { try writeSettingsOf(p, &p.settings, w); try w.writeAll("LocationsConfig "); @@ -523,7 +523,7 @@ pub fn writeSettingsOf(p: *Pardes, s: *const config.Runtime, w: *std.Io.Writer) inline else => |field| try w.print("{s} {s}\n", .{ word, @tagName(@field(s, @tagName(field))) }), }, .message_ms => |which| try w.print("{s} {d}\n", .{ word, @field(s, "message_" ++ @tagName(which) ++ "_ms") }), - // The directory in effect, as Config reports it; bare only when + // The directory in effect, as DumpConfig reports it; bare only when // there is none (no home to put the default in). .dump_dir => { var buf: [900]u8 = undefined; @@ -1165,7 +1165,7 @@ test "the root ctl reads the settings as a write takes them, and takes the sessi try testing.expectEqual(@as(u64, settings.len), call(p, .{ .tag = 1, .op = .getattr, .node = root_ctl }).reply.attr.size); try testing.expect(std.mem.indexOf(u8, settings, "Verbose on\n") != null); try testing.expect(std.mem.indexOf(u8, settings, "LocationsConfig ") != null); - // Settings only: nothing /status or the Config window says. + // Settings only: nothing /status or the DumpConfig window says. try testing.expect(std.mem.indexOf(u8, settings, "Platform") == null); try testing.expect(std.mem.indexOf(u8, settings, "requested") == null); diff --git a/src/pardes.zig b/src/pardes.zig index 18794975..e3db97d9 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -1329,7 +1329,7 @@ test "acme placement: New and 9P's new take the bottom half of the last pane" { try std.testing.expect(p.rects[made].y > was.y + BOX_H); } -test "Placement pardes brings back the old rules, and says so in Config" { +test "Placement pardes brings back the old rules, and says so in DumpConfig" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); defer p.deinit(); try std.testing.expect(p.executeBuiltinLine(p.active, "Placement pardes")); @@ -3493,7 +3493,7 @@ test "s in a header selects in the header's own text" { var ranges: [Text.max_selections]modal.Selection = undefined; const text = try edit.flatSurface(p, &p.global_tag); const got = p.global_tag.ranges(text, 0, &ranges); - try std.testing.expectEqual(@as(usize, 3), got.n); // Newcol, Joincol, NextColor + try std.testing.expectEqual(@as(usize, 2), got.n); // Newcol, Joincol try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); } @@ -5261,7 +5261,7 @@ pub const Pardes = struct { } /// Resolve the request already handed to the GUI host. Requested and - /// effective tuples deliberately remain separate so Config can show both. + /// effective tuples deliberately remain separate so DumpConfig can show both. pub fn acknowledgeFont( p: *Pardes, effective_name: []const u8, @@ -5596,6 +5596,8 @@ pub const Pardes = struct { const was = f.saved_revision; const failures = p.fs.failures; f.saved_revision = f.revision; + if (f.make_dirs) if (filesystem.localPath(f.path)) |local| + filesystem.makeDirs(std.fs.path.dirname(local) orelse "/"); p.hostWriteFile(sf.pane, f.path, f.content); const saved_pane = p.panes[sf.pane] orelse return; if (saved_pane.serial != serial) return; @@ -6721,7 +6723,7 @@ pub const Pardes = struct { } /// A native post pass proved unavailable: the chain is emptied, which - /// Config then reports. + /// DumpConfig then reports. pub fn disableSceneEffects(p: *Pardes) void { p.settings.post.clear(); } diff --git a/src/tutor.txt b/src/tutor.txt index c59deeae..f8aa7aef 100644 --- a/src/tutor.txt +++ b/src/tutor.txt @@ -65,8 +65,8 @@ Every pane has Collapse: hide its body, then execute again to expand it. The top bar is: - Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor - Debug Exit + Newcol Joincol Find Grep Help Changelog Tutor Dump Themes + Config Debug Exit Reach it from the keyboard with `k` off the topmost tagline; `j` comes back down. diff --git a/test/appearance_gallery.py b/test/appearance_gallery.py index 46b17dd9..c321c7c0 100644 --- a/test/appearance_gallery.py +++ b/test/appearance_gallery.py @@ -91,8 +91,8 @@ def run(args): def config_report(): before = set(panes(client)) - command(client, right, 'Config') - pane = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'Config output missing') + command(client, right, 'DumpConfig') + pane = require(wait_for(lambda: next((s for s in panes(client) if s not in before), None)), 'DumpConfig output missing') text = client.read(f'/pane/{pane}/body').decode() client.write(f'/pane/{pane}/exec', b'Del\n') return text diff --git a/test/font_size.py b/test/font_size.py index b7104099..ef685a9e 100644 --- a/test/font_size.py +++ b/test/font_size.py @@ -25,10 +25,10 @@ def run(args): control = new_pane(client, b'') def report(size): - execute(client, control, 'Config') + execute(client, control, 'DumpConfig') def ready(): for serial, tag in panes(client).items(): - if '/+Config ' in tag: + if '/+DumpConfig ' in tag: body = client.read(f'/pane/{serial}/body').decode() if f'Font effective size {size:.2f} pixels' in body: return body diff --git a/test/output.zig b/test/output.zig index 1b1b80c9..da17eccc 100644 --- a/test/output.zig +++ b/test/output.zig @@ -89,7 +89,7 @@ fn resultId(p: *Pardes) !usize { } test "output callers opt into location highlighting instead of matching prose colons" { - for ([_]panes.Output.Origin{ .{ .cmd = .LocationsConfig }, .{ .cmd = .Config }, .{ .query = .hover } }) |origin| { + for ([_]panes.Output.Origin{ .{ .cmd = .LocationsConfig }, .{ .cmd = .DumpConfig }, .{ .query = .hover } }) |origin| { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 140, .rows = 30 }); defer p.deinit(); p.locations_config.layout = .@"inline"; @@ -533,12 +533,12 @@ test "Mini failures leave its existing snapshot and focus unchanged" { try std.testing.expectEqual(next, p.freeSlot()); } -test "Config prints the startup path and refreshes its one output" { +test "DumpConfig prints the startup path and refreshes its one output" { const path = "/home/pardes-test/.config/pardes/init"; const p = try Pardes.init(std.testing.allocator, .{ .startup_config_path = path }); defer p.deinit(); - try std.testing.expect(p.executeBuiltinLine(0, "Config")); + try std.testing.expect(p.executeBuiltinLine(0, "DumpConfig")); const opened = p.active; const out = p.panes[opened].?.file.?; for ([_][]const u8{ @@ -549,28 +549,106 @@ test "Config prints the startup path and refreshes its one output" { }) |line| try std.testing.expect(std.mem.indexOf(u8, out.content, line) != null); var default_line: [256]u8 = undefined; try std.testing.expect(std.mem.indexOf(u8, out.content, try std.fmt.bufPrint(&default_line, "Shell requested (new panes) {s} (default)\n", .{config.defaultShell()})) != null); - try std.testing.expectEqualStrings(config.config_buffer, std.fs.path.basename(out.path)); - try std.testing.expectEqual(panes.Output.Origin{ .cmd = .Config }, out.output.?.from); + try std.testing.expectEqualStrings(config.dump_config_buffer, std.fs.path.basename(out.path)); + try std.testing.expectEqual(panes.Output.Origin{ .cmd = .DumpConfig }, out.output.?.from); - try std.testing.expect(p.executeBuiltinLine(0, "Config")); + try std.testing.expect(p.executeBuiltinLine(0, "DumpConfig")); try std.testing.expectEqual(opened, p.active); var buffers: usize = 0; for (p.panes) |slot| { const f = (slot orelse continue).file orelse continue; const origin = (f.output orelse continue).from; - buffers += @intFromBool(std.meta.eql(origin, panes.Output.Origin{ .cmd = .Config })); + buffers += @intFromBool(std.meta.eql(origin, panes.Output.Origin{ .cmd = .DumpConfig })); } try std.testing.expectEqual(@as(usize, 1), buffers); } -test "Config reports the absence of a per-user config path" { +test "DumpConfig reports the absence of a per-user config path" { const p = try Pardes.init(std.testing.allocator, .{}); defer p.deinit(); - try std.testing.expect(p.executeBuiltinLine(0, "Config")); + try std.testing.expect(p.executeBuiltinLine(0, "DumpConfig")); const report = p.panes[p.active].?.file.?.content; try std.testing.expect(std.mem.indexOf(u8, report, "no per-user config path") != null); } +/// The file Config names, in a fresh temporary directory: `pardes/init` +/// under it, written with `content` unless that is null. +fn configFixture(tmp: *std.testing.TmpDir, content: ?[]const u8, buf: *[4096]u8) ![]const u8 { + if (content) |text| { + try tmp.dir.createDirPath(std.testing.io, "pardes"); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "pardes/init", .data = text }); + } + const len = try tmp.dir.realPath(std.testing.io, buf); + return std.fmt.bufPrint(buf[len..], "{s}/pardes/init", .{buf[0..len]}) catch unreachable; +} + +test "Config opens the startup file, and a second Config goes back to its pane" { + if (comptime !pardes.hosted) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [4096]u8 = undefined; + const path = try configFixture(&tmp, "Theme orchard\n", &buf); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .startup_config_path = path }); + defer p.deinit(); + const first = p.active; + + try std.testing.expect(p.executeBuiltinLine(first, "Config")); + const opened = p.active; + try std.testing.expect(opened != first); + const f = p.panes[opened].?.file.?; + try std.testing.expectEqualStrings(path, f.path); + try std.testing.expectEqualStrings("Theme orchard\n", f.content); + try std.testing.expect(f.output == null); + + p.active = first; + try std.testing.expect(p.executeBuiltinLine(first, "Config")); + try std.testing.expectEqual(opened, p.active); + var named: usize = 0; + for (p.panes) |slot| if (slot) |pane| if (pane.file) |file| { + named += @intFromBool(std.mem.eql(u8, file.path, path)); + }; + try std.testing.expectEqual(@as(usize, 1), named); +} + +test "Config with no startup file opens a pane of its name, and Save makes its directory" { + if (comptime !pardes.hosted) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [4096]u8 = undefined; + const path = try configFixture(&tmp, null, &buf); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .startup_config_path = path }); + defer p.deinit(); + const first = p.active; + + try std.testing.expect(p.executeBuiltinLine(first, "Config")); + const opened = p.active; + try std.testing.expect(opened != first); + const f = p.panes[opened].?.file.?; + try std.testing.expectEqualStrings(path, f.path); + try std.testing.expectEqualStrings("", f.content); + try std.testing.expect(f.output == null); + + // Again: the same pane, not a second one. + p.active = first; + try std.testing.expect(p.executeBuiltinLine(first, "Config")); + try std.testing.expectEqual(opened, p.active); + + try std.testing.expectError(error.FileNotFound, tmp.dir.statFile(std.testing.io, "pardes", .{})); + // Save's effect, as a host performs it. + try std.testing.expect(p.executeBuiltinLine(opened, "Save")); + p.perform(.{ .save_file = .{ .pane = @intCast(opened) } }); + const made = try tmp.dir.statFile(std.testing.io, "pardes", .{}); + try std.testing.expectEqual(std.Io.File.Kind.directory, made.kind); +} + +test "Config without a configuration directory says so and opens nothing" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const before = p.freeSlot(); + try std.testing.expect(p.executeBuiltinLine(p.active, "Config")); + try std.testing.expectEqual(before, p.freeSlot()); +} + test "EffectCode lists readable virtual sources used by this backend" { if (comptime !builtins.EffectCode.enabled) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); @@ -651,7 +729,7 @@ test "every enabled setting builtin mutates the State Config reports" { } } - try std.testing.expect(p.executeBuiltinLine(p.active, "Config")); + try std.testing.expect(p.executeBuiltinLine(p.active, "DumpConfig")); const report = p.panes[p.active].?.file.?.content; for ([_][]const u8{ "Colors off\n", diff --git a/test/snapshots/argv.golden b/test/snapshots/argv.golden index e4d41d6c..65b0ac71 100644 --- a/test/snapshots/argv.golden +++ b/test/snapshots/argv.golden @@ -1,5 +1,5 @@ == snap noargs grid=100x31 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/argv/cwd Tty+bash Save Mode Filter Collapse Del | $ echo ARGV''TTY @@ -23,7 +23,7 @@ | /tmp/pardes-snap/argv/cwd/+New Save Tty Collapse Del | 1 == snap filearg grid=100x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/argv/cwd/notes.txt Save Tty Collapse Del | 3 line 3 @@ -34,7 +34,7 @@ | 8 line 8 | 9 == snap filearg-n3 grid=100x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/argv/cwd/notes.txt Save Tty Collapse Del | 1 line 1 @@ -47,7 +47,7 @@ | 8 line 8 | 9 == snap dirarg grid=100x31 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/argv/cwd/sub Tty+bash Save Mode Filter Collapse Del | ls diff --git a/test/snapshots/badutf.golden b/test/snapshots/badutf.golden index d013a610..14aa71dc 100644 --- a/test/snapshots/badutf.golden +++ b/test/snapshots/badutf.golden @@ -1,5 +1,5 @@ == snap badbytes grid=100x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/badutf/cwd/bad.txt Save Tty Collapse Del | 1 hello �� world diff --git a/test/snapshots/boot.golden b/test/snapshots/boot.golden index 3aedceff..ac674ed2 100644 --- a/test/snapshots/boot.golden +++ b/test/snapshots/boot.golden @@ -1,5 +1,5 @@ == snap boot grid=100x31 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/boot/cwd Tty+bash Save Mode Filter Collapse Del | ls diff --git a/test/snapshots/builtins.golden b/test/snapshots/builtins.golden index f40d563e..6b79d47f 100644 --- a/test/snapshots/builtins.golden +++ b/test/snapshots/builtins.golden @@ -1,5 +1,5 @@ == snap boot grid=120x67 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/builtins/cwd/notes.txt Save Tty Collapse Del | 1 line 1 diff --git a/test/snapshots/chordcut.golden b/test/snapshots/chordcut.golden index f0443a01..817c534c 100644 --- a/test/snapshots/chordcut.golden +++ b/test/snapshots/chordcut.golden @@ -1,5 +1,5 @@ == snap opened grid=120x31 cursor=7,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/chordcut/cwd Tty+bash Save Mode Filter C /tmp/pardes-snap/chordcut/cwd Tty+bash Save Mode Filter C | ollapse Del ollapse Del diff --git a/test/snapshots/cmdexit.golden b/test/snapshots/cmdexit.golden index c5c314b9..7d950a43 100644 --- a/test/snapshots/cmdexit.golden +++ b/test/snapshots/cmdexit.golden @@ -1,5 +1,5 @@ == snap opened grid=120x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/cmdexit/cwd/cmds.txt Save Tty Collapse Del | 1 sleep 30 & echo BG''STARTED diff --git a/test/snapshots/cmdword.golden b/test/snapshots/cmdword.golden index 748bf06b..af2fbcb8 100644 --- a/test/snapshots/cmdword.golden +++ b/test/snapshots/cmdword.golden @@ -1,5 +1,5 @@ == snap opened grid=120x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/cmdword/cwd/cmds.txt Save Tty Collapse Del | 1 @`echo ZZ''E` @`echo ZZ''L` Look p.txt @`Look .` diff --git a/test/snapshots/colgrip.golden b/test/snapshots/colgrip.golden index 1491a1f3..26a0b1c0 100644 --- a/test/snapshots/colgrip.golden +++ b/test/snapshots/colgrip.golden @@ -26,7 +26,7 @@ == style held grid=100x24 |1: 0-1 d,#887455, 2-2 d,#1d2824, 3-49 #b2c3b8,#1d2824, 50-51 #b2c3b8,#f4c086, 52-52 #b2c3b8,#314738, 53-99 #becfc4,#314738, == snap resize-drag grid=100x24 cursor=54,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/colgrip/cwd/w.txt S╎ve Tty Col /tmp/pardes-snap/colgrip/cwd Tty+bash Save Mode | lapse Del ╎ Filter Collapse Del diff --git a/test/snapshots/collapse.golden b/test/snapshots/collapse.golden index 23dfa8f3..57aafc8f 100644 --- a/test/snapshots/collapse.golden +++ b/test/snapshots/collapse.golden @@ -1,5 +1,5 @@ == snap before grid=160x25 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/collapse/cwd/kept.txt Save Tty Collapse Del | 1 KEEP-FIRST @@ -10,8 +10,8 @@ |4: |5: == 9p middle-collapsed-cursor grid=160x25 cursor=none -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit -@0: 0-70 #b2c3b8,#1d2824,,tagline 71-159 d,#1d2824,,tagline +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +@0: 0-74 #b2c3b8,#1d2824,,tagline 75-159 d,#1d2824,,tagline |1: New Tty Find Grep Joincol Delcol @1: 0-1 #ffffff,#887455,,tagline 2-2 d,#314738,,tagline 3-34 #becfc4,#314738,,tagline 35-159 d,#314738,,tagline |2: /tmp/pardes-snap/collapse/cwd/kept.txt Save Tty Collapse Del diff --git a/test/snapshots/cornerdrag-left.golden b/test/snapshots/cornerdrag-left.golden index 22bdd5b7..a5f36319 100644 --- a/test/snapshots/cornerdrag-left.golden +++ b/test/snapshots/cornerdrag-left.golden @@ -1,5 +1,5 @@ == snap right-split grid=100x31 cursor=54,11 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash S /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash S | ave Mode Filter Collapse Del ave Mode Filter Collapse Del diff --git a/test/snapshots/cornerdrag.golden b/test/snapshots/cornerdrag.golden index 30c1830a..8dd21eff 100644 --- a/test/snapshots/cornerdrag.golden +++ b/test/snapshots/cornerdrag.golden @@ -1,5 +1,5 @@ == snap hover-corner grid=100x31 cursor=4,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save ╎ /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save M | ode Filter Collapse Del ╎ ode Filter Collapse Del diff --git a/test/snapshots/cursorline.golden b/test/snapshots/cursorline.golden index 85c23f7f..6b99a30a 100644 --- a/test/snapshots/cursorline.golden +++ b/test/snapshots/cursorline.golden @@ -1,5 +1,5 @@ == snap top grid=150x31 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/cursorline/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/cursorline/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/delask.golden b/test/snapshots/delask.golden index ed5dd66a..d1487a36 100644 --- a/test/snapshots/delask.golden +++ b/test/snapshots/delask.golden @@ -1,5 +1,5 @@ == snap three grid=100x36 cursor=18,20 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/delask/cwd/top.txt Save Tty Collapse Del | 1 top-marker diff --git a/test/snapshots/doccol.golden b/test/snapshots/doccol.golden index db2b0074..21424456 100644 --- a/test/snapshots/doccol.golden +++ b/test/snapshots/doccol.golden @@ -1,5 +1,5 @@ == snap boot grid=100x31 cursor=7,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/doccol/cwd/a.txt Save Tty Coll /tmp/pardes-snap/doccol/cwd Tty+bash Save Mode | apse Del Filter Collapse Del diff --git a/test/snapshots/dump.golden b/test/snapshots/dump.golden index 9220c450..b9608741 100644 --- a/test/snapshots/dump.golden +++ b/test/snapshots/dump.golden @@ -4,7 +4,7 @@ .version = 1, .screen = .{ .cols = 100, .rows = 31 }, .active = 0, - .topbar = "Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit", + .topbar = "Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit", .topbar_custom = null, .theme = "orchard", .locations_config = .{ diff --git a/test/snapshots/edit.golden b/test/snapshots/edit.golden index f03f7e24..aa39ed9c 100644 --- a/test/snapshots/edit.golden +++ b/test/snapshots/edit.golden @@ -1,5 +1,5 @@ == snap inserted grid=100x31 cursor=16,10 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/edit/cwd Tty+bash Save Mode Fi /tmp/pardes-snap/edit/cwd Tty+bash Save Mode Fi | lter Collapse Del lter Collapse Del diff --git a/test/snapshots/emptycol.golden b/test/snapshots/emptycol.golden index 1e3f916d..9bac8492 100644 --- a/test/snapshots/emptycol.golden +++ b/test/snapshots/emptycol.golden @@ -1,5 +1,5 @@ == snap newcol grid=100x24 cursor=53,1 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/emptycol/cwd/notes.txt Save Tt | y Collapse Del diff --git a/test/snapshots/exec-bigdrag.golden b/test/snapshots/exec-bigdrag.golden index c74fd8f9..a2ac6610 100644 --- a/test/snapshots/exec-bigdrag.golden +++ b/test/snapshots/exec-bigdrag.golden @@ -1,5 +1,5 @@ == snap alive grid=200x61 cursor=119,38 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/exec-bigdrag/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/exec-bigdrag/cwd Tty+bash Save Mode Filter Collapse Del | ls 2 diff --git a/test/snapshots/exec.golden b/test/snapshots/exec.golden index 216327b3..a9f8716e 100644 --- a/test/snapshots/exec.golden +++ b/test/snapshots/exec.golden @@ -1,5 +1,5 @@ == snap exec grid=140x31 cursor=16,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/exec/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/exec/cwd Tty+bash Save Mode Filter Collapse Del | ls Exec ls diff --git a/test/snapshots/fileedit.golden b/test/snapshots/fileedit.golden index 4c651d3c..5ba6e18a 100644 --- a/test/snapshots/fileedit.golden +++ b/test/snapshots/fileedit.golden @@ -1,5 +1,5 @@ == snap edited grid=150x31 cursor=17,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/fileedit/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/fileedit/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/filewatch.golden b/test/snapshots/filewatch.golden index 589cfc3a..36f51582 100644 --- a/test/snapshots/filewatch.golden +++ b/test/snapshots/filewatch.golden @@ -1,5 +1,5 @@ == snap edited grid=210x31 cursor=15,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/filewatch/cwd Tty+bash Save Mode Filter Collapse Del | ls diff --git a/test/snapshots/find.golden b/test/snapshots/find.golden index 61716d87..c9c6b755 100644 --- a/test/snapshots/find.golden +++ b/test/snapshots/find.golden @@ -1,5 +1,5 @@ == snap group grid=120x41 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/find/cwd/here.txt Save Tty Collapse Del | 1 Find SPC f diff --git a/test/snapshots/fsearch.golden b/test/snapshots/fsearch.golden index d459f8c7..7ba94492 100644 --- a/test/snapshots/fsearch.golden +++ b/test/snapshots/fsearch.golden @@ -1,5 +1,5 @@ == snap opened grid=180x31 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/fsearch/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/fsearch/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/ghostty-mid.golden b/test/snapshots/ghostty-mid.golden index ab117f8a..4bd8bf1f 100644 --- a/test/snapshots/ghostty-mid.golden +++ b/test/snapshots/ghostty-mid.golden @@ -1,5 +1,5 @@ == snap ghostty-mid grid=100x31 cursor=4,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/ghostty-mid/cwd Tty+bash Save /tmp/pardes-snap/ghostty-mid/cwd Tty+bash Save | Mode Filter Collapse Del Mode Filter Collapse Del diff --git a/test/snapshots/grep.golden b/test/snapshots/grep.golden index 65b2fd5b..687d7099 100644 --- a/test/snapshots/grep.golden +++ b/test/snapshots/grep.golden @@ -1,5 +1,5 @@ == snap opened grid=180x31 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/grep/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/grep/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/headersweep-restored.golden b/test/snapshots/headersweep-restored.golden index 765f221f..38b505e7 100644 --- a/test/snapshots/headersweep-restored.golden +++ b/test/snapshots/headersweep-restored.golden @@ -21,7 +21,7 @@ |19: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, |20: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, == snap col-swept grid=120x21 cursor=4,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit Restore /tmp/pardes-snap/headersweep-restored/du +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit Restore /tmp/pardes-snap/headersweep-restore | New Tty Find Grep Joincol Delcol echo RE''STORED-COL New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/headersweep-restored/cwd Tty+bash Save M /tmp/pardes-snap/headersweep-restored/cwd Tty+bash Save M | ode Filter Collapse Del ode Filter Collapse Del @@ -44,6 +44,6 @@ |7: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, |8: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, == snap ws-swept grid=120x21 cursor=4,11 -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit Restore /tmp/pardes-snap/headersweep-restored ec +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit Restore /tmp/pardes-snap/headersweep-rest ec |9: echo RE''STORED-WS |10: RESTORED-WS diff --git a/test/snapshots/headersweep.golden b/test/snapshots/headersweep.golden index 92d23a1b..38004c08 100644 --- a/test/snapshots/headersweep.golden +++ b/test/snapshots/headersweep.golden @@ -21,7 +21,7 @@ |19: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, |20: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, == snap col-swept grid=120x21 cursor=4,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol echo SW''EPT-COL New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/headersweep/cwd Tty+bash Save Mode Filte /tmp/pardes-snap/headersweep/cwd Tty+bash Save Mode Filte | r Collapse Del r Collapse Del @@ -38,11 +38,11 @@ | ls | hay.txt == snap ws-swept grid=120x21 cursor=4,10 -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit echo SW''EPT-WS +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit echo SW''EPT-WS |8: echo SW''EPT-WS |9: SWEPT-WS == snap ws-looked grid=120x21 cursor=7,19 -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit echo SW''EPT-WS xxhay.txtxx +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit echo SW''EPT-WS xxhay.txtxx |17: /tmp/pardes-snap/headersweep/cwd/hay.txt Save Tty Collaps |18: e Del |19: 1 ZQNEEDLE diff --git a/test/snapshots/hscroll.golden b/test/snapshots/hscroll.golden index ddd7bab7..e73bf4c3 100644 --- a/test/snapshots/hscroll.golden +++ b/test/snapshots/hscroll.golden @@ -1,5 +1,5 @@ == snap opened grid=90x31 cursor=7,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/hscroll/cwd Tty+bash Save /tmp/pardes-snap/hscroll/cwd Tty+bash Save | Mode Filter Collapse Del Mode Filter Collapse Del diff --git a/test/snapshots/images.golden b/test/snapshots/images.golden index 940e293e..e888460d 100644 --- a/test/snapshots/images.golden +++ b/test/snapshots/images.golden @@ -1,5 +1,5 @@ == snap img-open grid=150x31 cursor=11,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/images/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/images/cwd Tty+bash Save Mode Filter Collapse Del | ls ls @@ -75,7 +75,7 @@ |15: │█🬝▄ |16: 🬝🬹 == snap tag-edit grid=400x31 cursor=87,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/images/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/images/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/jumps.golden b/test/snapshots/jumps.golden index 65435443..27884f6a 100644 --- a/test/snapshots/jumps.golden +++ b/test/snapshots/jumps.golden @@ -1,5 +1,5 @@ == snap start grid=150x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/jumps/cwd/big.txt Save Tty Collapse Del | 1 line 1 diff --git a/test/snapshots/layout-close.golden b/test/snapshots/layout-close.golden index d708d764..95806a16 100644 --- a/test/snapshots/layout-close.golden +++ b/test/snapshots/layout-close.golden @@ -1,5 +1,5 @@ == snap built grid=140x41 cursor=4,16 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/layout-close/cwd Tty+bash Save Mode Filter Collaps /tmp/pardes-snap/layout-close/cwd Tty+bash Save Mode Filter Collaps | e Del e Del diff --git a/test/snapshots/layout-open.golden b/test/snapshots/layout-open.golden index 91d41790..a3d9dfdd 100644 --- a/test/snapshots/layout-open.golden +++ b/test/snapshots/layout-open.golden @@ -1,5 +1,5 @@ == snap before grid=100x31 cursor=2,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/layout-open/cwd Tty+bash Save /tmp/pardes-snap/layout-open/cwd Tty+bash Save | Mode Filter Collapse Del Mode Filter Collapse Del diff --git a/test/snapshots/leader.golden b/test/snapshots/leader.golden index 6c154c6c..52528cde 100644 --- a/test/snapshots/leader.golden +++ b/test/snapshots/leader.golden @@ -1,5 +1,5 @@ == snap spc grid=100x41 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/leader/cwd/cmds.txt Save Tty Collapse Del | 1 Help SPC diff --git a/test/snapshots/load.golden b/test/snapshots/load.golden index d18fd235..38a6d59b 100644 --- a/test/snapshots/load.golden +++ b/test/snapshots/load.golden @@ -1,5 +1,5 @@ == snap loaded grid=100x31 cursor=4,16 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/load/cwd Tty+bash Save Mode Fi /tmp/pardes-snap/load/cwd Tty+bash Save Mode Fi | lter Collapse Del lter Collapse Del diff --git a/test/snapshots/logquiet.golden b/test/snapshots/logquiet.golden index 366fc0f7..45b643db 100644 --- a/test/snapshots/logquiet.golden +++ b/test/snapshots/logquiet.golden @@ -1,5 +1,5 @@ == snap quiet grid=100x31 cursor=62,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/logquiet/cwd Tty+bash Save Mode Filter Collapse Del | $ ls diff --git a/test/snapshots/look-center.golden b/test/snapshots/look-center.golden index e5db101e..c861bb8f 100644 --- a/test/snapshots/look-center.golden +++ b/test/snapshots/look-center.golden @@ -1,5 +1,5 @@ == snap center-open grid=150x31 cursor=15,12 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/look-center/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/look-center/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/look-dir.golden b/test/snapshots/look-dir.golden index 7f20fdc6..29e67d5f 100644 --- a/test/snapshots/look-dir.golden +++ b/test/snapshots/look-dir.golden @@ -1,5 +1,5 @@ == snap dir-open grid=100x31 cursor=4,11 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/look-dir/cwd Tty+bash Save Mod /tmp/pardes-snap/look-dir/cwd Tty+bash Save Mod | e Filter Collapse Del e Filter Collapse Del diff --git a/test/snapshots/look-file-1col.golden b/test/snapshots/look-file-1col.golden index 45f9f20f..81ba4ded 100644 --- a/test/snapshots/look-file-1col.golden +++ b/test/snapshots/look-file-1col.golden @@ -1,5 +1,5 @@ == snap file-open-1col grid=100x31 cursor=14,19 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/look-file-1col/cwd Tty+bash Save Mode Filter Collapse Del | ls diff --git a/test/snapshots/look-file.golden b/test/snapshots/look-file.golden index 695fd2c1..4d4bbdfe 100644 --- a/test/snapshots/look-file.golden +++ b/test/snapshots/look-file.golden @@ -1,5 +1,5 @@ == snap file-open grid=150x31 cursor=14,12 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/look-file/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/look-file/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/lookloaded.golden b/test/snapshots/lookloaded.golden index 70b42102..a968a6dc 100644 --- a/test/snapshots/lookloaded.golden +++ b/test/snapshots/lookloaded.golden @@ -1,5 +1,5 @@ == snap file-open grid=100x31 cursor=14,13 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lookloaded/cwd Tty+bash Save M /tmp/pardes-snap/lookloaded/cwd Tty+bash Save M | ode Filter Collapse Del ode Filter Collapse Del diff --git a/test/snapshots/lookpanes.golden b/test/snapshots/lookpanes.golden index 98dfd8b9..e0f55f5f 100644 --- a/test/snapshots/lookpanes.golden +++ b/test/snapshots/lookpanes.golden @@ -1,5 +1,5 @@ == snap shells grid=130x51 cursor=122,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lookpanes/cwd/beta/bmark.txt Save Tty Collaps /tmp/pardes-snap/lookpanes/cwd Tty+bash Save Mode Filter Colla | e Del pse Del diff --git a/test/snapshots/lookrange.golden b/test/snapshots/lookrange.golden index 25306ce1..f57ee457 100644 --- a/test/snapshots/lookrange.golden +++ b/test/snapshots/lookrange.golden @@ -1,5 +1,5 @@ == snap opened grid=150x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lookrange/cwd/look.txt Save Tty Collapse Del | 1 r.txt:3-5 diff --git a/test/snapshots/lsp-client-edit.golden b/test/snapshots/lsp-client-edit.golden index 29ec05af..c36d15be 100644 --- a/test/snapshots/lsp-client-edit.golden +++ b/test/snapshots/lsp-client-edit.golden @@ -1,5 +1,5 @@ == snap formatted grid=100x25 cursor=7,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | * /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext | 1 // formatted by mock formatted 1 range(s) diff --git a/test/snapshots/lsp-client.golden b/test/snapshots/lsp-client.golden index 17eb0d40..23d86e11 100644 --- a/test/snapshots/lsp-client.golden +++ b/test/snapshots/lsp-client.golden @@ -1,5 +1,5 @@ == snap gd-jumped grid=100x25 cursor=16,12 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lsp-client/cwd/main.rs Save Tty Collapse Del TreeContext | 1 mod lib; --:--:-- lsp rust-analyzer: ready diff --git a/test/snapshots/lsp-rename.golden b/test/snapshots/lsp-rename.golden index 03fb2311..ba19d8f0 100644 --- a/test/snapshots/lsp-rename.golden +++ b/test/snapshots/lsp-rename.golden @@ -1,5 +1,5 @@ == snap renamed grid=110x25 cursor=17,10 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | * /tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse Del TreeContext | 1 const std = @import("std"); renamed 2 range(s) diff --git a/test/snapshots/lsp.golden b/test/snapshots/lsp.golden index be0090fb..153ae5cc 100644 --- a/test/snapshots/lsp.golden +++ b/test/snapshots/lsp.golden @@ -1,5 +1,5 @@ == snap opened grid=120x41 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lsp/cwd/a.zig Save Tty Collapse Del TreeContext | 1 const std = @import("std"); diff --git a/test/snapshots/lspcomplete.golden b/test/snapshots/lspcomplete.golden index 0b29034f..29a81f93 100644 --- a/test/snapshots/lspcomplete.golden +++ b/test/snapshots/lspcomplete.golden @@ -1,5 +1,5 @@ == snap opened grid=120x41 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext | 1 const Shade = enum { @@ -31,13 +31,13 @@ == snap step grid=120x41 cursor=19,4 |2: * /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext == snap txtindent grid=120x41 cursor=15,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |^* /tmp/pardes-snap/lspcomplete/cwd/notes.txt Save Tty Collapse Del | 1 abc. def ghi | 2 == snap nosemi grid=100x19 cursor=29,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |^* /tmp/pardes-snap/lspcomplete/cwd/c.zig Save Tty Collapse Del TreeContext | 1 const Shade = enum { @@ -53,7 +53,7 @@ | 2 c.zig:3:5-12 cinnabar cinnabar, | 3 == snap nobrace grid=100x19 cursor=16,10 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |^* /tmp/pardes-snap/lspcomplete/cwd/d.zig Save Tty Collapse Del TreeContext | 1 const Shade = enum { diff --git a/test/snapshots/lspcompletemoved.golden b/test/snapshots/lspcompletemoved.golden index a033ed56..e759cbd8 100644 --- a/test/snapshots/lspcompletemoved.golden +++ b/test/snapshots/lspcompletemoved.golden @@ -1,5 +1,5 @@ == snap typedthrough grid=120x21 cursor=16,14 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |^* /tmp/pardes-snap/lspcompletemoved/cwd/a.zig Save Tty Collapse Del TreeContext | 1 const Shade = enum { diff --git a/test/snapshots/lspdebug.golden b/test/snapshots/lspdebug.golden index cf2eb097..650b41b2 100644 --- a/test/snapshots/lspdebug.golden +++ b/test/snapshots/lspdebug.golden @@ -1,5 +1,5 @@ == snap opened grid=120x45 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/lspdebug/cwd/z.zig Save Tty Collapse Del TreeContext | 1 const std = @import("std"); diff --git a/test/snapshots/lsprelpath.golden b/test/snapshots/lsprelpath.golden index 201f6dd4..904e076a 100644 --- a/test/snapshots/lsprelpath.golden +++ b/test/snapshots/lsprelpath.golden @@ -1,5 +1,5 @@ == snap absrow grid=100x35 cursor=16,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |^* /tmp/pardes-snap/lsprelpath/cwd/sub/parent.zig Save Tty Collapse Del TreeContext | 1 const shade = @import("../shade.zig"); @@ -58,7 +58,7 @@ |33: 0-0 d,#608269, 1-99 d,#0d1410, |34: 0-0 d,#608269, 1-99 d,#0d1410, == snap subrow grid=100x35 cursor=16,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |^* /tmp/pardes-snap/lsprelpath/cwd/sub/subdir.zig Save Tty Collapse Del TreeContext | 1 const tint = @import("inner/tint.zig"); diff --git a/test/snapshots/markup.golden b/test/snapshots/markup.golden index 8c712a58..6991cdf6 100644 --- a/test/snapshots/markup.golden +++ b/test/snapshots/markup.golden @@ -1,5 +1,5 @@ == snap typst grid=92x25 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/markup/cwd/paper.typ Save Tty Collapse Del TreeContext | 1 = Typst heading @@ -38,7 +38,7 @@ |23: 0-0 d,#608269, 1-91 d,#0d1410, |24: 0-0 d,#608269, 1-91 d,#0d1410, == snap markdown grid=92x25 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/markup/cwd/notes.md Save Tty Collapse Del TreeContext | 1 # Markdown heading with *italic* diff --git a/test/snapshots/mini.golden b/test/snapshots/mini.golden index cc8dd612..8d0205f7 100644 --- a/test/snapshots/mini.golden +++ b/test/snapshots/mini.golden @@ -1,5 +1,5 @@ == snap opened grid=90x23 cursor=7,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del | 1 @`Mini demo.zig` Mini @@ -34,8 +34,8 @@ |21: 0-0 d,#608269, 1-89 d,#0d1410, |22: 0-0 d,#608269, 1-89 d,#0d1410, == 9p opened grid=90x23 cursor=7,6,block -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit -@0: 0-70 #b2c3b8,#1d2824,,tagline 71-89 d,#1d2824,,tagline +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +@0: 0-74 #b2c3b8,#1d2824,,tagline 75-89 d,#1d2824,,tagline |1: New Tty Find Grep Joincol Delcol @1: 0-1 #ffffff,#887455,,tagline 2-2 d,#314738,,tagline 3-34 #becfc4,#314738,,tagline 35-89 d,#314738,,tagline |2: /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del @@ -105,7 +105,7 @@ |7: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-8 #b9f480,#0d1410, 9-11 #c9a7ed,#0d1410, 12-89 #b9f480,#0d1410, |8: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-19 #f8c082,#0d1410, 20-89 #e5eee5,#0d1410, == snap resized grid=105x27 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del | 1 @`Mini demo.zig` @@ -117,8 +117,8 @@ | 3 ⠉⠉⠁⠉⠉⠉⠈⠈⠉⠉⠉⠉⠉⠉ | 4 == 9p resized grid=105x27 cursor=7,7,block -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit -@0: 0-70 #b2c3b8,#1d2824,,tagline 71-104 d,#1d2824,,tagline +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +@0: 0-74 #b2c3b8,#1d2824,,tagline 75-104 d,#1d2824,,tagline |1: New Tty Find Grep Joincol Delcol @1: 0-1 #ffffff,#887455,,tagline 2-2 d,#314738,,tagline 3-34 #becfc4,#314738,,tagline 35-104 d,#314738,,tagline |2: /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del diff --git a/test/snapshots/modal.golden b/test/snapshots/modal.golden index 4ade84f2..6dc6376d 100644 --- a/test/snapshots/modal.golden +++ b/test/snapshots/modal.golden @@ -1,5 +1,5 @@ == snap top grid=100x31 cursor=2,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/modal/cwd Tty+bash Save Mode F /tmp/pardes-snap/modal/cwd Tty+bash Save Mode F | ilter Collapse Del ilter Collapse Del diff --git a/test/snapshots/msg.golden b/test/snapshots/msg.golden index ff7b39a0..caa234d3 100644 --- a/test/snapshots/msg.golden +++ b/test/snapshots/msg.golden @@ -1,5 +1,5 @@ == snap opened grid=70x15 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exi +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/msg/cwd/a.txt Save Tty Collapse Del | 1 line 1 @@ -12,7 +12,7 @@ == snap saved grid=70x15 cursor=7,3 |3: 1 line 1 --:--:-- saved /tmp/pardes-snap/msg/cwd/a.txt == snap repainted grid=70x17 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exi +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/msg/cwd/a.txt Save Tty Collapse Del | 1 line 1 --:--:-- saved /tmp/pardes-snap/msg/cwd/a.txt diff --git a/test/snapshots/multicursor.golden b/test/snapshots/multicursor.golden index c3d5dbe2..0b3bbcb2 100644 --- a/test/snapshots/multicursor.golden +++ b/test/snapshots/multicursor.golden @@ -1,5 +1,5 @@ == snap three-cursors grid=150x31 cursor=7,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/multicursor/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/multicursor/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/nested.golden b/test/snapshots/nested.golden index 9758c491..07d6148d 100644 --- a/test/snapshots/nested.golden +++ b/test/snapshots/nested.golden @@ -1,5 +1,5 @@ == snap file-arg grid=100x31 cursor=7,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/nested/cwd Tty+bash Save Mode Filter Collapse Del | $ $(readlink /proc/$PPID/exe) nested.txt @@ -23,7 +23,7 @@ | /tmp/pardes-snap/nested/cwd/+New Save Tty Collapse Del | 1 == snap no-arg grid=100x31 cursor=4,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/nested/cwd Tty+bash Save Mode Filter Collapse Del | $ $(readlink /proc/$PPID/exe) @@ -47,7 +47,7 @@ | /tmp/pardes-snap/nested/cwd/+New Save Tty Collapse Del | 1 == snap dir-arg grid=100x31 cursor=4,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/nested/cwd Tty+bash Save Mode Filter Collapse Del | $ $(readlink /proc/$PPID/exe) nestdir diff --git a/test/snapshots/ninep.golden b/test/snapshots/ninep.golden index f3733ab4..c6b5f0af 100644 --- a/test/snapshots/ninep.golden +++ b/test/snapshots/ninep.golden @@ -1,5 +1,5 @@ == snap opened grid=90x15 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext | 1 const greeting = "café λ 界 é"; @@ -26,8 +26,8 @@ |13: 0-0 d,#608269, 1-89 d,#0d1410, |14: 0-0 d,#608269, 1-89 d,#0d1410, == 9p opened grid=90x15 cursor=7,3,block -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit -@0: 0-70 #b2c3b8,#1d2824,,tagline 71-89 d,#1d2824,,tagline +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +@0: 0-74 #b2c3b8,#1d2824,,tagline 75-89 d,#1d2824,,tagline |1: New Tty Find Grep Joincol Delcol @1: 0-1 #ffffff,#887455,,tagline 2-2 d,#314738,,tagline 3-34 #becfc4,#314738,,tagline 35-89 d,#314738,,tagline |2: /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext @@ -148,8 +148,8 @@ |18: 0-0 d,#608269, 1-104 d,#0d1410, |19: 0-0 d,#608269, 1-104 d,#0d1410, == 9p resized grid=105x20 cursor=7,4,block -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit -@0: 0-70 #b2c3b8,#1d2824,,tagline 71-104 d,#1d2824,,tagline +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +@0: 0-74 #b2c3b8,#1d2824,,tagline 75-104 d,#1d2824,,tagline |1: New Tty Find Grep Joincol Delcol @1: 0-1 #ffffff,#887455,,tagline 2-2 d,#314738,,tagline 3-34 #becfc4,#314738,,tagline 35-104 d,#314738,,tagline |2: * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext @@ -191,7 +191,7 @@ |19: @19: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body == snap resized grid=105x20 cursor=7,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext | 1 // café λ 界 Colors diff --git a/test/snapshots/pipe.golden b/test/snapshots/pipe.golden index b7a8da86..2fd54c27 100644 --- a/test/snapshots/pipe.golden +++ b/test/snapshots/pipe.golden @@ -1,5 +1,5 @@ == snap prompt grid=180x13 cursor=179,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/pipe/cwd/pipe.txt Save Tty Collapse Del | 1 alpha beta |tr a-z A-Z diff --git a/test/snapshots/psearch.golden b/test/snapshots/psearch.golden index 544086c5..e830a206 100644 --- a/test/snapshots/psearch.golden +++ b/test/snapshots/psearch.golden @@ -1,5 +1,5 @@ == snap output grid=140x31 cursor=4,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/psearch/cwd Tty+bash Save Mode Filter Collapse Del | printf 'x MA''RK a\nzz\nx MA''RK b\nzz\nx MA''RK c\n' diff --git a/test/snapshots/reflow.golden b/test/snapshots/reflow.golden index afd4b93f..17c42d0d 100644 --- a/test/snapshots/reflow.golden +++ b/test/snapshots/reflow.golden @@ -1,5 +1,5 @@ == snap widened grid=200x25 cursor=4,16 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/reflow/cwd Tty+bash Save Mode Filter Collapse Del | yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy diff --git a/test/snapshots/respawn.golden b/test/snapshots/respawn.golden index d6d21a81..1e6425d2 100644 --- a/test/snapshots/respawn.golden +++ b/test/snapshots/respawn.golden @@ -1,5 +1,5 @@ == snap respawn grid=140x31 cursor=4,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/respawn/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/respawn/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/restore.golden b/test/snapshots/restore.golden index af2b82c1..0bb53676 100644 --- a/test/snapshots/restore.golden +++ b/test/snapshots/restore.golden @@ -1,5 +1,5 @@ == snap dumped grid=100x31 cursor=4,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit Restore /tmp/pardes-snap/res +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit Restore /tmp/pardes-snap | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/restore/cwd Tty+bash Save Mode Filter Collapse Del | $ ls Dump diff --git a/test/snapshots/rsearch.golden b/test/snapshots/rsearch.golden index 89c4f7bd..eb98853a 100644 --- a/test/snapshots/rsearch.golden +++ b/test/snapshots/rsearch.golden @@ -1,5 +1,5 @@ == snap opened grid=210x31 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/rsearch/cwd Tty+bash Save Mode Filter Collapse Del | ls diff --git a/test/snapshots/savepane.golden b/test/snapshots/savepane.golden index 8660a437..bea7146b 100644 --- a/test/snapshots/savepane.golden +++ b/test/snapshots/savepane.golden @@ -1,5 +1,5 @@ == snap scratch grid=100x31 cursor=20,18 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/savepane/cwd Tty+bash Save Mode Filter Collapse Del | ls diff --git a/test/snapshots/scroll.golden b/test/snapshots/scroll.golden index 9250590a..44b6b264 100644 --- a/test/snapshots/scroll.golden +++ b/test/snapshots/scroll.golden @@ -1,5 +1,5 @@ == snap bottom grid=100x31 cursor=4,16 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/scroll/cwd Tty+bash Save Mode /tmp/pardes-snap/scroll/cwd Tty+bash Save Mode | Filter Collapse Del Filter Collapse Del diff --git a/test/snapshots/scrolloff.golden b/test/snapshots/scrolloff.golden index 17ca7e7b..299df49d 100644 --- a/test/snapshots/scrolloff.golden +++ b/test/snapshots/scrolloff.golden @@ -1,5 +1,5 @@ == snap top grid=210x16 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/scrolloff/cwd Tty+bash Save Mode Filter Collapse Del | ls diff --git a/test/snapshots/selarg.golden b/test/snapshots/selarg.golden index f41c355b..741864ef 100644 --- a/test/snapshots/selarg.golden +++ b/test/snapshots/selarg.golden @@ -1,5 +1,5 @@ == snap kept grid=100x31 cursor=6,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/selarg/cwd Tty+bash Save Mode /tmp/pardes-snap/selarg/cwd Tty+bash Save Mode | Filter Collapse Del Filter Collapse Del diff --git a/test/snapshots/selregex.golden b/test/snapshots/selregex.golden index c99d48e1..e3f3b2d7 100644 --- a/test/snapshots/selregex.golden +++ b/test/snapshots/selregex.golden @@ -1,5 +1,5 @@ == snap prompt-armed grid=160x25 cursor=159,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse Del TreeContext | 1 const one = 1; Select / diff --git a/test/snapshots/shellset.golden b/test/snapshots/shellset.golden index 0d13f017..9d566be7 100644 --- a/test/snapshots/shellset.golden +++ b/test/snapshots/shellset.golden @@ -1,5 +1,5 @@ == snap boot grid=90x21 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/shellset/cwd/cmd.txt Save Tty Collapse Del | 1 Shell zznosuchshell diff --git a/test/snapshots/shrinktag.golden b/test/snapshots/shrinktag.golden index 9aa29e11..d73c0072 100644 --- a/test/snapshots/shrinktag.golden +++ b/test/snapshots/shrinktag.golden @@ -1,5 +1,5 @@ == snap before grid=100x31 cursor=2,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/shrinktag/cwd Tty+bash Save Mo /tmp/pardes-snap/shrinktag/cwd Tty+bash Save Mo | de Filter Collapse Del de Filter Collapse Del diff --git a/test/snapshots/splitparent.golden b/test/snapshots/splitparent.golden index e626cea7..f83bbb66 100644 --- a/test/snapshots/splitparent.golden +++ b/test/snapshots/splitparent.golden @@ -1,5 +1,5 @@ == snap shrunk grid=100x31 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/splitparent/cwd Tty+bash Save /tmp/pardes-snap/splitparent/cwd Tty+bash Save | Mode Filter Collapse Del Mode Filter Collapse Del @@ -13,14 +13,14 @@ |11: Mode Filter Collapse Del |12: ls == snap tallest grid=100x6 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/splitparent/cwd Tty+bash Save /tmp/pardes-snap/splitparent/cwd Tty+bash Save | /tmp/pardes-snap/splitparent/cwd Tty+bash Save Mode Filter Collapse Del | /tmp/pardes-snap/splitparent/cwd Tty+bash Save ls | e in that column: each keeps its tag and 2 rows == snap regrown grid=100x31 cursor=4,13 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/splitparent/cwd Tty+bash Save /tmp/pardes-snap/splitparent/cwd Tty+bash Save | Mode Filter Collapse Del Mode Filter Collapse Del diff --git a/test/snapshots/stepgrain.golden b/test/snapshots/stepgrain.golden index bdd506e9..7c445492 100644 --- a/test/snapshots/stepgrain.golden +++ b/test/snapshots/stepgrain.golden @@ -1,5 +1,5 @@ == snap results grid=150x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/stepgrain/cwd/a.txt Save Tty Collapse Del | 1 hello ZQMARK one diff --git a/test/snapshots/syntax.golden b/test/snapshots/syntax.golden index 096dab27..2f7a6b74 100644 --- a/test/snapshots/syntax.golden +++ b/test/snapshots/syntax.golden @@ -1,5 +1,5 @@ == snap zig-open grid=150x31 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/syntax/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/syntax/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/tag.golden b/test/snapshots/tag.golden index 0f9af5dc..0d20859a 100644 --- a/test/snapshots/tag.golden +++ b/test/snapshots/tag.golden @@ -1,5 +1,5 @@ == snap tag-focus grid=150x31 cursor=36,2 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tag/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/tag/cwd Tty+bash Save Mode Filter Collapse Del | ls ls diff --git a/test/snapshots/tagalign.golden b/test/snapshots/tagalign.golden index 8a522ced..a557ff95 100644 --- a/test/snapshots/tagalign.golden +++ b/test/snapshots/tagalign.golden @@ -1,5 +1,5 @@ == snap aligned grid=100x31 cursor=4,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty Collapse Del | 1 alpha @@ -9,7 +9,7 @@ | ls | deep == snap fits grid=87x31 cursor=4,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty Co | llapse Del @@ -19,7 +19,7 @@ | ls | deep == snap overby1 grid=86x31 cursor=4,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty C | ollapse Del @@ -29,7 +29,7 @@ | ls | deep == snap clicked grid=100x31 cursor=11,2 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty Collapse Del | 1 alpha @@ -39,7 +39,7 @@ | ls | deep == snap revealed grid=70x31 cursor=30,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exi +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/documen | t.txt Save Tty Collapse Del diff --git a/test/snapshots/tagalign2col.golden b/test/snapshots/tagalign2col.golden index a35edccb..129141b6 100644 --- a/test/snapshots/tagalign2col.golden +++ b/test/snapshots/tagalign2col.golden @@ -1,5 +1,5 @@ == snap onecol grid=160x31 cursor=7,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagalign2col/cwd/deep/proj/document.txt Save Tty Collapse De /tmp/pardes-snap/tagalign2col/cwd Tty+bash Save Mode Filter Collapse Del | l ls Left diff --git a/test/snapshots/tagbottom.golden b/test/snapshots/tagbottom.golden index d5f1f720..8469c741 100644 --- a/test/snapshots/tagbottom.golden +++ b/test/snapshots/tagbottom.golden @@ -1,5 +1,5 @@ == snap boot grid=100x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del | 1 aaa diff --git a/test/snapshots/tagbottomimage.golden b/test/snapshots/tagbottomimage.golden index 89e96f6b..2bf9231e 100644 --- a/test/snapshots/tagbottomimage.golden +++ b/test/snapshots/tagbottomimage.golden @@ -1,5 +1,5 @@ == snap img-top grid=150x31 cursor=11,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagbottomimage/cwd Tty+bash Save Mode Filter Collapse Del | ls diff --git a/test/snapshots/tagbottomshort.golden b/test/snapshots/tagbottomshort.golden index 3fd3b180..efa8b3f1 100644 --- a/test/snapshots/tagbottomshort.golden +++ b/test/snapshots/tagbottomshort.golden @@ -1,5 +1,5 @@ == snap roomy grid=80x11 cursor=79,2 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | 1 one /ZZ | 2 two @@ -11,21 +11,21 @@ | | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del == snap two-body grid=80x5 cursor=79,2 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | 1 one /ZZ | 2 two | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del == snap one-body grid=80x4 cursor=79,2 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | 1 one /ZZ | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del == snap tag-only grid=80x2 cursor=79,1 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del == snap regrown grid=80x11 cursor=79,2 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | 1 one /ZZ | 2 two @@ -37,7 +37,7 @@ | | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del == snap leader-one-body grid=80x4 cursor=7,2 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | 1 one SPC | /tmp/pardes-snap/tagbottomshort/cwd/s.txt Save Tty Collapse Del diff --git a/test/snapshots/tagcmd.golden b/test/snapshots/tagcmd.golden index 8f1dc8d2..2c1ca73f 100644 --- a/test/snapshots/tagcmd.golden +++ b/test/snapshots/tagcmd.golden @@ -1,5 +1,5 @@ == snap edited grid=100x31 cursor=13,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | * /tmp/pardes-snap/tagcmd/cwd/c.txt Save Tty Collapse Del | 1 ZZEDITline 1 diff --git a/test/snapshots/tagnav.golden b/test/snapshots/tagnav.golden index e06c578e..a86854a9 100644 --- a/test/snapshots/tagnav.golden +++ b/test/snapshots/tagnav.golden @@ -1,5 +1,5 @@ == snap start grid=100x31 cursor=7,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagnav/cwd/w.txt Save Tty Coll /tmp/pardes-snap/tagnav/cwd Tty+bash Save Mode | apse Del Filter Collapse Del @@ -34,13 +34,13 @@ |4: 1 alpha ls == snap workspace-tag grid=100x31 cursor=0,0 |4: 1 alpha Up ls -== snap topbar-dollar grid=100x31 cursor=70,0 +== snap topbar-dollar grid=100x31 cursor=74,0 |4: 1 alpha ls == snap topbar-dump-word grid=100x31 cursor=46,0 == snap topbar-exec grid=100x31 cursor=7,4 -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit Restore /tmp/pardes-snap/tag +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit Restore /tmp/pardes-snap |4: 1 alpha Dump ls -== snap topbar-restore-word grid=100x31 cursor=72,0 +== snap topbar-restore-word grid=100x31 cursor=76,0 |4: 1 alpha ls == snap topbar-restored grid=100x31 cursor=7,4 |4: 1 alpha $ ls diff --git a/test/snapshots/tagnav.snap b/test/snapshots/tagnav.snap index f145480e..2f5906bb 100644 --- a/test/snapshots/tagnav.snap +++ b/test/snapshots/tagnav.snap @@ -93,7 +93,7 @@ snap column-word key c-w k stable 400 5000 snap workspace-tag -# `$` is the last cell; four long-word steps back land on `Dump`, and the +# `$` is the last cell; five long-word steps back land on `Dump`, and the # execute key runs it and gives the keyboard back to the body FIRST -- `Exit` # lives up here too, so a builtin that frees the session must never return # into a focused header. Dump grows a `Restore ` word, which is also the @@ -101,7 +101,7 @@ snap workspace-tag key g l stable 400 5000 snap topbar-dollar -key B B B B +key B B B B B stable 400 5000 snap topbar-dump-word key tab diff --git a/test/snapshots/tagpath.golden b/test/snapshots/tagpath.golden index 6f082c7a..1216bdeb 100644 --- a/test/snapshots/tagpath.golden +++ b/test/snapshots/tagpath.golden @@ -1,5 +1,5 @@ == snap start grid=100x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tagpath/cwd/c.txt Save Tty Collapse Del | 1 line 1 diff --git a/test/snapshots/theme.golden b/test/snapshots/theme.golden index 443d639c..351f8905 100644 --- a/test/snapshots/theme.golden +++ b/test/snapshots/theme.golden @@ -1,5 +1,5 @@ -== snap orchard grid=100x31 cursor=4,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +== snap orchard grid=100x31 cursor=85,0 +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit NextColor | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/theme/cwd Tty+bash Save Mode F /tmp/pardes-snap/theme/cwd Tty+bash Save Mode F | ilter Collapse Del ilter Collapse Del @@ -55,7 +55,7 @@ == snap dusk grid=100x31 cursor=4,6 |4: ls NextColor ls == style dusk grid=100x31 -|0: 0-50 #c6b6c5,#2c2630, 51-59 #fff0eb,#654053, 60-60 #fff0eb,#2c2630, 61-99 #c6b6c5,#2c2630, +|0: 0-75 #c6b6c5,#2c2630, 76-84 #fff0eb,#654053, 85-99 #fff0eb,#2c2630, |1: 0-1 d,#757a5f, 2-2 d,#533d4d, 3-49 #d2c2d1,#533d4d, 50-51 #d2c2d1,#757a5f, 52-52 #d2c2d1,#2c2630, 53-99 #c6b6c5,#2c2630, |2: 0-1 d,#edb092, 2-2 d,#533d4d, 3-29 #d2c2d1,#533d4d, 30-38 #a1d5c4,#533d4d, 39-49 #d2c2d1,#533d4d, 50-51 #d2c2d1,#745469, 52-52 #d2c2d1,#2c2630, 53-79 #c6b6c5,#2c2630, 80-88 #96c9b8,#2c2630, 89-99 #c6b6c5,#2c2630, |3: 0-2 d,#533d4d, 3-49 #d2c2d1,#533d4d, 50-52 #d2c2d1,#2c2630, 53-99 #c6b6c5,#2c2630, @@ -88,7 +88,7 @@ |30: 0-0 d,#8e667c, 1-49 d,#39323b, 50-50 d,#8e667c, 51-99 d,#39323b, == snap ink grid=100x31 cursor=4,6 == style ink grid=100x31 -|0: 0-50 #d5e4f1,#15212c, 51-59 #ffffff,#1b547c, 60-60 #ffffff,#15212c, 61-99 #d5e4f1,#15212c, +|0: 0-75 #d5e4f1,#15212c, 76-84 #ffffff,#1b547c, 85-99 #ffffff,#15212c, |1: 0-1 d,#8f7d5b, 2-2 d,#2b4051, 3-49 #e1eef9,#2b4051, 50-51 #e1eef9,#8f7d5b, 52-52 #e1eef9,#15212c, 53-99 #d5e4f1,#15212c, |2: 0-1 d,#86d8ff, 2-2 d,#2b4051, 3-29 #e1eef9,#2b4051, 30-38 #ffeab8,#2b4051, 39-49 #e1eef9,#2b4051, 50-51 #e1eef9,#5f7990, 52-52 #e1eef9,#15212c, 53-79 #d5e4f1,#15212c, 80-88 #f5e0ac,#15212c, 89-99 #d5e4f1,#15212c, |3: 0-2 d,#2b4051, 3-49 #e1eef9,#2b4051, 50-52 #e1eef9,#15212c, 53-99 #d5e4f1,#15212c, @@ -121,7 +121,7 @@ |30: 0-0 d,#86a8c2, 1-49 d,#000000, 50-50 d,#86a8c2, 51-99 d,#000000, == snap paper grid=100x31 cursor=4,6 == style paper grid=100x31 -|0: 0-50 #52625a,#e8eae3, 51-59 #203e31,#c5e2d0, 60-60 #203e31,#e8eae3, 61-99 #52625a,#e8eae3, +|0: 0-75 #52625a,#e8eae3, 76-84 #203e31,#c5e2d0, 85-99 #203e31,#e8eae3, |1: 0-1 d,#bda27e, 2-2 d,#bdd8ca, 3-49 #4a5a52,#bdd8ca, 50-51 #4a5a52,#bda27e, 52-52 #4a5a52,#e8eae3, 53-99 #52625a,#e8eae3, |2: 0-1 d,#367157, 2-2 d,#bdd8ca, 3-29 #4a5a52,#bdd8ca, 30-38 #69447a,#bdd8ca, 39-49 #4a5a52,#bdd8ca, 50-51 #4a5a52,#8fa594, 52-52 #4a5a52,#e8eae3, 53-79 #52625a,#e8eae3, 80-88 #724c83,#e8eae3, 89-99 #52625a,#e8eae3, |3: 0-2 d,#bdd8ca, 3-49 #4a5a52,#bdd8ca, 50-52 #4a5a52,#e8eae3, 53-99 #52625a,#e8eae3, @@ -154,7 +154,7 @@ |30: 0-0 d,#869d8a, 1-49 d,#f5f3ed, 50-50 d,#869d8a, 51-99 d,#f5f3ed, == snap daybreak grid=100x31 cursor=4,6 == style daybreak grid=100x31 -|0: 0-50 #29465e,#edf2f7, 51-59 #10364f,#b9dffb, 60-60 #10364f,#edf2f7, 61-99 #29465e,#edf2f7, +|0: 0-75 #29465e,#edf2f7, 76-84 #10364f,#b9dffb, 85-99 #10364f,#edf2f7, |1: 0-1 d,#b79a7a, 2-2 d,#c7dcec, 3-49 #213e56,#c7dcec, 50-51 #213e56,#b79a7a, 52-52 #213e56,#edf2f7, 53-99 #29465e,#edf2f7, |2: 0-1 d,#006198, 2-2 d,#c7dcec, 3-29 #213e56,#c7dcec, 30-38 #52255f,#c7dcec, 39-49 #213e56,#c7dcec, 50-51 #213e56,#7b9eb7, 52-52 #213e56,#edf2f7, 53-79 #29465e,#edf2f7, 80-88 #5a2d67,#edf2f7, 89-99 #29465e,#edf2f7, |3: 0-2 d,#c7dcec, 3-49 #213e56,#c7dcec, 50-52 #213e56,#edf2f7, 53-99 #29465e,#edf2f7, @@ -187,7 +187,7 @@ |30: 0-0 d,#6685a0, 1-49 d,#ffffff, 50-50 d,#6685a0, 51-99 d,#ffffff, == snap atelier grid=100x31 cursor=4,6 == style atelier grid=100x31 -|0: 0-50 #3d6055,#e4f0ed, 51-59 #35492d,#edf2a5, 60-60 #35492d,#e4f0ed, 61-99 #3d6055,#e4f0ed, +|0: 0-75 #3d6055,#e4f0ed, 76-84 #35492d,#edf2a5, 85-99 #35492d,#e4f0ed, |1: 0-1 d,#bca481, 2-2 d,#bfdcce, 3-49 #35584d,#bfdcce, 50-51 #35584d,#bca481, 52-52 #35584d,#e4f0ed, 53-99 #3d6055,#e4f0ed, |2: 0-1 d,#36826b, 2-2 d,#bfdcce, 3-29 #35584d,#bfdcce, 30-38 #653f6b,#bfdcce, 39-49 #35584d,#bfdcce, 50-51 #35584d,#95baa2, 52-52 #35584d,#e4f0ed, 53-79 #3d6055,#e4f0ed, 80-88 #6e4774,#e4f0ed, 89-99 #3d6055,#e4f0ed, |3: 0-2 d,#bfdcce, 3-49 #35584d,#bfdcce, 50-52 #35584d,#e4f0ed, 53-99 #3d6055,#e4f0ed, @@ -225,7 +225,7 @@ == snap forge grid=100x31 cursor=4,6 |4: ls NextColor ls == style forge grid=100x31 -|0: 0-50 #c5c9d2,#22252b, 51-59 #e2eef4,#1c5172, 60-60 #e2eef4,#22252b, 61-99 #c5c9d2,#22252b, +|0: 0-75 #c5c9d2,#22252b, 76-84 #e2eef4,#1c5172, 85-99 #e2eef4,#22252b, |1: 0-1 d,#6a7b67, 2-2 d,#374253, 3-49 #d1d5de,#374253, 50-51 #d1d5de,#6a7b67, 52-52 #d1d5de,#22252b, 53-99 #c5c9d2,#22252b, |2: 0-1 d,#9cc3f7, 2-2 d,#374253, 3-29 #d1d5de,#374253, 30-38 #f8cba7,#374253, 39-49 #d1d5de,#374253, 50-51 #d1d5de,#55647b, 52-52 #d1d5de,#22252b, 53-79 #c5c9d2,#22252b, 80-88 #ecbf9b,#22252b, 89-99 #c5c9d2,#22252b, |3: 0-2 d,#374253, 3-49 #d1d5de,#374253, 50-52 #d1d5de,#22252b, 53-99 #c5c9d2,#22252b, @@ -258,7 +258,7 @@ |30: 0-0 d,#708095, 1-49 d,#0c0c0e, 50-50 d,#708095, 51-99 d,#0c0c0e, == snap lagoon grid=100x31 cursor=4,6 == style lagoon grid=100x31 -|0: 0-50 #bbd7cb,#29443f, 51-59 #e6f2f3,#325f6c, 60-60 #e6f2f3,#29443f, 61-99 #bbd7cb,#29443f, +|0: 0-75 #bbd7cb,#29443f, 76-84 #e6f2f3,#325f6c, 85-99 #e6f2f3,#29443f, |1: 0-1 d,#9a7662, 2-2 d,#3a6154, 3-49 #c7e3d7,#3a6154, 50-51 #c7e3d7,#9a7662, 52-52 #c7e3d7,#29443f, 53-99 #bbd7cb,#29443f, |2: 0-1 d,#81cfb7, 2-2 d,#3a6154, 3-29 #c7e3d7,#3a6154, 30-38 #f0cef8,#3a6154, 39-49 #c7e3d7,#3a6154, 50-51 #c7e3d7,#548372, 52-52 #c7e3d7,#29443f, 53-79 #bbd7cb,#29443f, 80-88 #e4c2ec,#29443f, 89-99 #bbd7cb,#29443f, |3: 0-2 d,#3a6154, 3-49 #c7e3d7,#3a6154, 50-52 #c7e3d7,#29443f, 53-99 #bbd7cb,#29443f, @@ -291,7 +291,7 @@ |30: 0-0 d,#6e9b8b, 1-49 d,#34464c, 50-50 d,#6e9b8b, 51-99 d,#34464c, == snap solarium grid=100x31 cursor=4,6 == style solarium grid=100x31 -|0: 0-50 #c7d4bd,#123f43, 51-59 #eee8d5,#1f5c64, 60-60 #eee8d5,#123f43, 61-99 #c7d4bd,#123f43, +|0: 0-75 #c7d4bd,#123f43, 76-84 #eee8d5,#1f5c64, 85-99 #eee8d5,#123f43, |1: 0-1 d,#347a9a, 2-2 d,#2f5c5c, 3-49 #d3e0c9,#2f5c5c, 50-51 #d3e0c9,#347a9a, 52-52 #d3e0c9,#123f43, 53-99 #c7d4bd,#123f43, |2: 0-1 d,#e1c266, 2-2 d,#2f5c5c, 3-29 #d3e0c9,#2f5c5c, 30-38 #f5cdec,#2f5c5c, 39-49 #d3e0c9,#2f5c5c, 50-51 #d3e0c9,#467f76, 52-52 #d3e0c9,#123f43, 53-79 #c7d4bd,#123f43, 80-88 #e9c1e0,#123f43, 89-99 #c7d4bd,#123f43, |3: 0-2 d,#2f5c5c, 3-49 #d3e0c9,#2f5c5c, 50-52 #d3e0c9,#123f43, 53-99 #c7d4bd,#123f43, @@ -324,7 +324,7 @@ |30: 0-0 d,#65978c, 1-49 d,#173e45, 50-50 d,#65978c, 51-99 d,#173e45, == snap spectrum grid=100x31 cursor=4,6 == style spectrum grid=100x31 -|0: 0-50 #ddd8bb,#3b3830, 51-59 #fcfcfa,#513f60, 60-60 #fcfcfa,#3b3830, 61-99 #ddd8bb,#3b3830, +|0: 0-75 #ddd8bb,#3b3830, 76-84 #fcfcfa,#513f60, 85-99 #fcfcfa,#3b3830, |1: 0-1 d,#706596, 2-2 d,#5a523a, 3-49 #e9e4c7,#5a523a, 50-51 #e9e4c7,#706596, 52-52 #e9e4c7,#3b3830, 53-99 #ddd8bb,#3b3830, |2: 0-1 d,#ffd866, 2-2 d,#5a523a, 3-29 #e9e4c7,#5a523a, 30-38 #d7e3ff,#5a523a, 39-49 #e9e4c7,#5a523a, 50-51 #e9e4c7,#92844f, 52-52 #e9e4c7,#3b3830, 53-79 #ddd8bb,#3b3830, 80-88 #c5d7ff,#3b3830, 89-99 #ddd8bb,#3b3830, |3: 0-2 d,#5a523a, 3-49 #e9e4c7,#5a523a, 50-52 #e9e4c7,#3b3830, 53-99 #ddd8bb,#3b3830, @@ -357,7 +357,7 @@ |30: 0-0 d,#948d6f, 1-49 d,#100e11, 50-50 d,#948d6f, 51-99 d,#100e11, == snap harvest grid=100x31 cursor=4,6 == style harvest grid=100x31 -|0: 0-50 #d5d8b8,#343b2e, 51-59 #f3f2cc,#4f5834, 60-60 #f3f2cc,#343b2e, 61-99 #d5d8b8,#343b2e, +|0: 0-75 #d5d8b8,#343b2e, 76-84 #f3f2cc,#4f5834, 85-99 #f3f2cc,#343b2e, |1: 0-1 d,#9b583f, 2-2 d,#4a583e, 3-49 #e1e4c4,#4a583e, 50-51 #e1e4c4,#9b583f, 52-52 #e1e4c4,#343b2e, 53-99 #d5d8b8,#343b2e, |2: 0-1 d,#d8bd83, 2-2 d,#4a583e, 3-29 #e1e4c4,#4a583e, 30-38 #c5e7f7,#4a583e, 39-49 #e1e4c4,#4a583e, 50-51 #e1e4c4,#7b7e4e, 52-52 #e1e4c4,#343b2e, 53-79 #d5d8b8,#343b2e, 80-88 #badbeb,#343b2e, 89-99 #d5d8b8,#343b2e, |3: 0-2 d,#4a583e, 3-49 #e1e4c4,#4a583e, 50-52 #e1e4c4,#343b2e, 53-99 #d5d8b8,#343b2e, @@ -390,7 +390,7 @@ |30: 0-0 d,#888e5e, 1-49 d,#100e0b, 50-50 d,#888e5e, 51-99 d,#100e0b, == snap clay grid=100x31 cursor=4,6 == style clay grid=100x31 -|0: 0-50 #d7d6b6,#343f36, 51-59 #fbf1c7,#505c38, 60-60 #fbf1c7,#343f36, 61-99 #d7d6b6,#343f36, +|0: 0-75 #d7d6b6,#343f36, 76-84 #fbf1c7,#505c38, 85-99 #fbf1c7,#343f36, |1: 0-1 d,#875e65, 2-2 d,#4d5c48, 3-49 #e3e2c2,#4d5c48, 50-51 #e3e2c2,#875e65, 52-52 #e3e2c2,#343f36, 53-99 #d7d6b6,#343f36, |2: 0-1 d,#8ac874, 2-2 d,#4d5c48, 3-29 #e3e2c2,#4d5c48, 30-38 #b5ecec,#4d5c48, 39-49 #e3e2c2,#4d5c48, 50-51 #e3e2c2,#687c4d, 52-52 #e3e2c2,#343f36, 53-79 #d7d6b6,#343f36, 80-88 #aae0e0,#343f36, 89-99 #d7d6b6,#343f36, |3: 0-2 d,#4d5c48, 3-49 #e3e2c2,#4d5c48, 50-52 #e3e2c2,#343f36, 53-99 #d7d6b6,#343f36, @@ -423,7 +423,7 @@ |30: 0-0 d,#8c9467, 1-49 d,#10100e, 50-50 d,#8c9467, 51-99 d,#10100e, == snap forge-black grid=100x31 cursor=4,6 == style forge-black grid=100x31 -|0: 0-50 #c5c9d2,#22252b, 51-59 #e2eef4,#1c5172, 60-60 #e2eef4,#22252b, 61-99 #c5c9d2,#22252b, +|0: 0-75 #c5c9d2,#22252b, 76-84 #e2eef4,#1c5172, 85-99 #e2eef4,#22252b, |1: 0-1 d,#6a7b67, 2-2 d,#374253, 3-49 #d1d5de,#374253, 50-51 #d1d5de,#6a7b67, 52-52 #d1d5de,#22252b, 53-99 #c5c9d2,#22252b, |2: 0-1 d,#9cc3f7, 2-2 d,#374253, 3-29 #d1d5de,#374253, 30-38 #f8cba7,#374253, 39-49 #d1d5de,#374253, 50-51 #d1d5de,#55647b, 52-52 #d1d5de,#22252b, 53-79 #c5c9d2,#22252b, 80-88 #ecbf9b,#22252b, 89-99 #c5c9d2,#22252b, |3: 0-2 d,#374253, 3-49 #d1d5de,#374253, 50-52 #d1d5de,#22252b, 53-99 #c5c9d2,#22252b, @@ -456,7 +456,7 @@ |30: 0-0 d,#708095, 1-49 d,#000000, 50-50 d,#708095, 51-99 d,#000000, == snap forge-soft grid=100x31 cursor=4,6 == style forge-soft grid=100x31 -|0: 0-50 #c5c9d2,#2a2d34, 51-59 #e2eef4,#1c5172, 60-60 #e2eef4,#2a2d34, 61-99 #c5c9d2,#2a2d34, +|0: 0-75 #c5c9d2,#2a2d34, 76-84 #e2eef4,#1c5172, 85-99 #e2eef4,#2a2d34, |1: 0-1 d,#6d7f6c, 2-2 d,#404a58, 3-49 #d1d5de,#404a58, 50-51 #d1d5de,#6d7f6c, 52-52 #d1d5de,#2a2d34, 53-99 #c5c9d2,#2a2d34, |2: 0-1 d,#9cc3f7, 2-2 d,#404a58, 3-29 #d1d5de,#404a58, 30-38 #f8cba7,#404a58, 39-49 #d1d5de,#404a58, 50-51 #d1d5de,#55647b, 52-52 #d1d5de,#2a2d34, 53-79 #c5c9d2,#2a2d34, 80-88 #ecbf9b,#2a2d34, 89-99 #c5c9d2,#2a2d34, |3: 0-2 d,#404a58, 3-49 #d1d5de,#404a58, 50-52 #d1d5de,#2a2d34, 53-99 #c5c9d2,#2a2d34, @@ -489,7 +489,7 @@ |30: 0-0 d,#708095, 1-49 d,#35383e, 50-50 d,#708095, 51-99 d,#35383e, == snap orchard-black grid=100x31 cursor=4,6 == style orchard-black grid=100x31 -|0: 0-50 #b2c3b8,#1d2824, 51-59 #f5f7ee,#3c614a, 60-60 #f5f7ee,#1d2824, 61-99 #b2c3b8,#1d2824, +|0: 0-75 #b2c3b8,#1d2824, 76-84 #f5f7ee,#3c614a, 85-99 #f5f7ee,#1d2824, |1: 0-1 d,#887455, 2-2 d,#314738, 3-49 #becfc4,#314738, 50-51 #becfc4,#887455, 52-52 #becfc4,#1d2824, 53-99 #b2c3b8,#1d2824, |2: 0-1 d,#add38a, 2-2 d,#314738, 3-29 #becfc4,#314738, 30-38 #dfbce5,#314738, 39-49 #becfc4,#314738, 50-51 #becfc4,#496656, 52-52 #becfc4,#1d2824, 53-79 #b2c3b8,#1d2824, 80-88 #d3b0d9,#1d2824, 89-99 #b2c3b8,#1d2824, |3: 0-2 d,#314738, 3-49 #becfc4,#314738, 50-52 #becfc4,#1d2824, 53-99 #b2c3b8,#1d2824, @@ -522,7 +522,7 @@ |30: 0-0 d,#608269, 1-49 d,#000000, 50-50 d,#608269, 51-99 d,#000000, == snap acme grid=100x31 cursor=4,6 == style acme grid=100x31 -|0: 0-50 #000000,#eaffff, 51-59 #000000,#9eeeee, 60-99 #000000,#eaffff, +|0: 0-75 #000000,#eaffff, 76-84 #000000,#9eeeee, 85-99 #000000,#eaffff, |1: 0-1 d,#8888cc, 2-2 d,#eaffff, 3-49 #000000,#eaffff, 50-51 #000000,#8888cc, 52-99 #000000,#eaffff, |2: 0-1 d,#8888cc, 2-2 d,#eaffff, 3-29 #000000,#eaffff, 30-38 #000099,#eaffff, 39-49 #000000,#eaffff, 50-51 #000000,#b9c3e5, 52-79 #000000,#eaffff, 80-88 #000099,#eaffff, 89-99 #000000,#eaffff, |3: 0-2 d,#eaffff, 3-99 #000000,#eaffff, @@ -555,7 +555,7 @@ |30: 0-99 d,#ffffea, == snap lapis grid=100x31 cursor=4,6 == style lapis grid=100x31 -|0: 0-50 #9aa6d9,#0f1a4a, 51-59 #0f1a4a,#e8c46a, 60-60 #0f1a4a,#0f1a4a, 61-99 #9aa6d9,#0f1a4a, +|0: 0-75 #9aa6d9,#0f1a4a, 76-84 #0f1a4a,#e8c46a, 85-99 #0f1a4a,#0f1a4a, |1: 0-1 d,#8a3a3a, 2-2 d,#25397d, 3-49 #eee6d2,#25397d, 50-51 #eee6d2,#8a3a3a, 52-52 #eee6d2,#0f1a4a, 53-99 #9aa6d9,#0f1a4a, |2: 0-1 d,#e8c46a, 2-2 d,#25397d, 3-29 #eee6d2,#25397d, 30-38 #f2d280,#25397d, 39-49 #eee6d2,#25397d, 50-51 #eee6d2,#6a78b1, 52-52 #eee6d2,#0f1a4a, 53-79 #9aa6d9,#0f1a4a, 80-88 #e8c46a,#0f1a4a, 89-99 #9aa6d9,#0f1a4a, |3: 0-2 d,#25397d, 3-49 #eee6d2,#25397d, 50-52 #eee6d2,#0f1a4a, 53-99 #9aa6d9,#0f1a4a, @@ -588,7 +588,7 @@ |30: 0-0 d,#e8c46a, 1-49 d,#0a1030, 50-50 d,#e8c46a, 51-99 d,#0a1030, == snap dark-plus grid=100x31 cursor=4,6 == style dark-plus grid=100x31 -|0: 0-50 #a7a7a7,#3c3c3c, 51-59 #d4d4d4,#264f78, 60-60 #d4d4d4,#3c3c3c, 61-99 #a7a7a7,#3c3c3c, +|0: 0-75 #a7a7a7,#3c3c3c, 76-84 #d4d4d4,#264f78, 85-99 #d4d4d4,#3c3c3c, |1: 0-1 d,#458276, 2-2 d,#1e1e1e, 3-49 #ffffff,#1e1e1e, 50-51 #ffffff,#458276, 52-52 #ffffff,#3c3c3c, 53-99 #a7a7a7,#3c3c3c, |2: 0-1 d,#007fd4, 2-2 d,#1e1e1e, 3-29 #ffffff,#1e1e1e, 30-38 #cbe5fc,#1e1e1e, 39-49 #ffffff,#1e1e1e, 50-51 #ffffff,#1c608e, 52-52 #ffffff,#3c3c3c, 53-79 #a7a7a7,#3c3c3c, 80-88 #68aee9,#3c3c3c, 89-99 #a7a7a7,#3c3c3c, |3: 0-2 d,#1e1e1e, 3-49 #ffffff,#1e1e1e, 50-52 #ffffff,#3c3c3c, 53-99 #a7a7a7,#3c3c3c, @@ -621,7 +621,7 @@ |30: 0-0 d,#424242, 1-49 d,#1e1e1e, 50-50 d,#424242, 51-99 d,#1e1e1e, == snap solarized-dark grid=100x31 cursor=4,6 == style solarized-dark grid=100x31 -|0: 0-50 #01090b,#657b83, 51-59 #002b36,#586e75, 60-60 #002b36,#657b83, 61-99 #01090b,#657b83, +|0: 0-75 #01090b,#657b83, 76-84 #002b36,#586e75, 85-99 #002b36,#657b83, |1: 0-1 d,#758a41, 2-2 d,#93a1a1, 3-49 #073642,#93a1a1, 50-51 #073642,#758a41, 52-52 #073642,#657b83, 53-99 #01090b,#657b83, |2: 0-1 d,#2483c5, 2-2 d,#93a1a1, 3-29 #073642,#93a1a1, 30-38 #2d3502,#93a1a1, 39-49 #073642,#93a1a1, 50-51 #073642,#185986, 52-52 #073642,#657b83, 53-79 #01090b,#657b83, 80-88 #121600,#657b83, 89-99 #01090b,#657b83, |3: 0-2 d,#93a1a1, 3-49 #073642,#93a1a1, 50-52 #073642,#657b83, 53-99 #01090b,#657b83, diff --git a/test/snapshots/theme.snap b/test/snapshots/theme.snap index b770d7f3..4cb360d3 100644 --- a/test/snapshots/theme.snap +++ b/test/snapshots/theme.snap @@ -5,6 +5,14 @@ file t.txt x start 31 100 -n 3 wait 8000 t.txt stable 700 20000 +# NextColor is no default word of the workspace tag: typed onto its end +press left 99 1 +release left 99 1 +key space +text NextColor +key esc +settle 100 +stable 700 10000 snap orchard snapstyle orchard press middle @NextColor 1 diff --git a/test/snapshots/themesel.golden b/test/snapshots/themesel.golden index d9c4f4ba..a82d88f5 100644 --- a/test/snapshots/themesel.golden +++ b/test/snapshots/themesel.golden @@ -1,5 +1,5 @@ == snap boot grid=100x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/themesel/cwd/t.txt Save Tty Collapse Del | 1 line 1 diff --git a/test/snapshots/tinywin.golden b/test/snapshots/tinywin.golden index c847a2f1..f4d20a9a 100644 --- a/test/snapshots/tinywin.golden +++ b/test/snapshots/tinywin.golden @@ -1,5 +1,5 @@ == snap stacked grid=100x31 cursor=14,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/tinywin/cwd Tty+bash Save Mode Filter Collapse Del | $ :^[n^[n^[n @@ -23,12 +23,12 @@ | /tmp/pardes-snap/tinywin/cwd/+New Save Tty Collapse Del | 1 == snap shrunk grid=60x4 cursor=59,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Co | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/tinywin/cwd Tty+bash Save Mode Filter Co | /tmp/pardes-snap/tinywin/cwd/+New Save Tty Collapse Del == snap columns grid=100x31 cursor=23,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/tinywin/cwd Tty+bash Save Mode Filter Collapse Del | $ :^[n^[n^[n cn cn cn diff --git a/test/snapshots/topbarexec.golden b/test/snapshots/topbarexec.golden index 500f9f2a..3ede27e8 100644 --- a/test/snapshots/topbarexec.golden +++ b/test/snapshots/topbarexec.golden @@ -1,5 +1,5 @@ == snap selected grid=90x21 cursor=14,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/topbarexec/cwd Tty+bash S /tmp/pardes-snap/topbarexec/cwd Tty+bash S | ave Mode Filter Collapse Del ave Mode Filter Collapse Del diff --git a/test/snapshots/tty.golden b/test/snapshots/tty.golden index b876ace6..981a5c7f 100644 --- a/test/snapshots/tty.golden +++ b/test/snapshots/tty.golden @@ -1,5 +1,5 @@ == snap tty-on grid=100x31 cursor=4,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/tty/cwd Tty+bash Save Mode Fil /tmp/pardes-snap/tty/cwd Tty+bash Save Mode Fil | ter Collapse Del ter Collapse Del diff --git a/test/snapshots/ttyclick.golden b/test/snapshots/ttyclick.golden index a69d951f..5076e882 100644 --- a/test/snapshots/ttyclick.golden +++ b/test/snapshots/ttyclick.golden @@ -1,5 +1,5 @@ == snap tty-bodyclick grid=100x31 cursor=4,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/ttyclick/cwd Tty+bash Save Mod /tmp/pardes-snap/ttyclick/cwd Tty+bash Save Mod | e Filter Collapse Del e Filter Collapse Del diff --git a/test/snapshots/ttyedit.golden b/test/snapshots/ttyedit.golden index 4411962e..ab1b1b5b 100644 --- a/test/snapshots/ttyedit.golden +++ b/test/snapshots/ttyedit.golden @@ -1,5 +1,5 @@ == snap before grid=100x31 cursor=7,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/ttyedit/cwd Tty+bash Save Mode /tmp/pardes-snap/ttyedit/cwd Tty+bash Save Mode | Filter Collapse Del Filter Collapse Del diff --git a/test/snapshots/ttyfollow.golden b/test/snapshots/ttyfollow.golden index 1527ce86..3fb41e89 100644 --- a/test/snapshots/ttyfollow.golden +++ b/test/snapshots/ttyfollow.golden @@ -1,5 +1,5 @@ == snap held-pre grid=100x31 cursor=4,16 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/ttyfollow/cwd Tty+bash Save Mo /tmp/pardes-snap/ttyfollow/cwd Tty+bash Save Mo | de Filter Collapse Del de Filter Collapse Del diff --git a/test/snapshots/ttyhelp.golden b/test/snapshots/ttyhelp.golden index c252ff28..7d21bc00 100644 --- a/test/snapshots/ttyhelp.golden +++ b/test/snapshots/ttyhelp.golden @@ -1,5 +1,5 @@ == snap boot grid=100x31 cursor=4,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/ttyhelp/cwd Tty+bash Save Mode Filter Collapse Del | $ diff --git a/test/snapshots/ttylook.golden b/test/snapshots/ttylook.golden index a8ed1b95..b839a174 100644 --- a/test/snapshots/ttylook.golden +++ b/test/snapshots/ttylook.golden @@ -1,5 +1,5 @@ == snap tok1 grid=120x31 cursor=2,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/ttylook/cwd Tty+bash Save Mode Filter Co /tmp/pardes-snap/ttylook/cwd Tty+bash Save Mode Filter Co | llapse Del llapse Del diff --git a/test/snapshots/ttyonly.golden b/test/snapshots/ttyonly.golden index 24f54b29..208aa485 100644 --- a/test/snapshots/ttyonly.golden +++ b/test/snapshots/ttyonly.golden @@ -1,5 +1,5 @@ == snap ttyonly grid=100x31 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/ttyonly/cwd Tty+bash Save Mode Filter Collapse Del | $ echo TTY''ONLY diff --git a/test/snapshots/ttypaste.golden b/test/snapshots/ttypaste.golden index 40e0ae4c..ec98834e 100644 --- a/test/snapshots/ttypaste.golden +++ b/test/snapshots/ttypaste.golden @@ -1,5 +1,5 @@ == snap bracketed-paste-reached-the-shell grid=100x31 cursor=18,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/ttypaste/cwd Tty+bash Save Mod /tmp/pardes-snap/ttypaste/cwd Tty+bash Save Mod | e Filter Collapse Del e Filter Collapse Del diff --git a/test/snapshots/ttyprompt.golden b/test/snapshots/ttyprompt.golden index 0033c78f..eb99f417 100644 --- a/test/snapshots/ttyprompt.golden +++ b/test/snapshots/ttyprompt.golden @@ -1,5 +1,5 @@ == snap greeted grid=100x31 cursor=4,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/ttyprompt/cwd Tty+bash Save Mo /tmp/pardes-snap/ttyprompt/cwd Tty+bash Save Mo | de Filter Collapse Del de Filter Collapse Del diff --git a/test/snapshots/ttytaken.golden b/test/snapshots/ttytaken.golden index d0f2eee9..73a75088 100644 --- a/test/snapshots/ttytaken.golden +++ b/test/snapshots/ttytaken.golden @@ -1,5 +1,5 @@ == snap opened grid=210x31 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/ttytaken/cwd Tty+bash Save Mode Filter Collapse Del | ls diff --git a/test/snapshots/tutor.golden b/test/snapshots/tutor.golden index 9793ca34..1be72b87 100644 --- a/test/snapshots/tutor.golden +++ b/test/snapshots/tutor.golden @@ -1,5 +1,5 @@ == snap tutor grid=150x31 cursor=7,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/tutor/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/tutor/cwd Tty+bash Save Mode Filter Collapse Del | ls Tutor ls diff --git a/test/snapshots/wheeldrift.golden b/test/snapshots/wheeldrift.golden index 256c2999..b5c4d231 100644 --- a/test/snapshots/wheeldrift.golden +++ b/test/snapshots/wheeldrift.golden @@ -1,5 +1,5 @@ == snap home grid=70x17 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exi +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/wheeldrift/cwd/drift.txt Save Tty Collapse Del | 1 line 1_0123456789_abcdefghij_ZEND Wrap diff --git a/test/snapshots/winch.golden b/test/snapshots/winch.golden index a1e8afc4..c6972f79 100644 --- a/test/snapshots/winch.golden +++ b/test/snapshots/winch.golden @@ -1,5 +1,5 @@ == snap storm grid=100x31 cursor=4,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/winch/cwd Tty+bash Save Mode F /tmp/pardes-snap/winch/cwd Tty+bash Save Mode F | ilter Collapse Del ilter Collapse Del @@ -20,7 +20,7 @@ | ilter Collapse Del | ls == snap resized grid=106x35 cursor=4,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/winch/cwd Tty+bash Save Mode Filt /tmp/pardes-snap/winch/cwd Tty+bash Save Mode Filt | er Collapse Del er Collapse Del diff --git a/test/snapshots/windownav.golden b/test/snapshots/windownav.golden index 13fc7ae7..91e80e6d 100644 --- a/test/snapshots/windownav.golden +++ b/test/snapshots/windownav.golden @@ -1,5 +1,5 @@ == snap start grid=100x31 cursor=7,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/windownav/cwd/w.txt Save Tty C /tmp/pardes-snap/windownav/cwd Tty+bash Save Mo | ollapse Del de Filter Collapse Del diff --git a/test/snapshots/windowops.golden b/test/snapshots/windowops.golden index d729f179..6a48785e 100644 --- a/test/snapshots/windowops.golden +++ b/test/snapshots/windowops.golden @@ -1,5 +1,5 @@ == snap hover-v grid=100x31 cursor=4,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/windowops/cwd Tty+bash Save M╎ /tmp/pardes-snap/windowops/cwd Tty+bash Save Mo | de Filter Collapse Del ╎ de Filter Collapse Del @@ -153,7 +153,7 @@ |10: ╰────────────────────────────────────╯ |20: ls == style debug-on grid=100x31 -|0: 0-60 #b2c3b8,#1d2824, 61-65 #f5f7ee,#3c614a, 66-66 #f5f7ee,#1d2824, 67-99 #b2c3b8,#1d2824, +|0: 0-64 #b2c3b8,#1d2824, 65-69 #f5f7ee,#3c614a, 70-70 #f5f7ee,#1d2824, 71-99 #b2c3b8,#1d2824, |1: 0-1 d,#887455, 2-2 d,#1d2824, 3-39 #b2c3b8,#1d2824, 40-41 #b2c3b8,#887455, 42-42 #b2c3b8,#314738, 43-61 #becfc4,#314738, 62-99 d,d, |2: 0-1 d,#496656, 2-2 d,#1d2824, 3-33 #b2c3b8,#1d2824, 34-39 #d3b0d9,#1d2824, 40-41 #d3b0d9,#add38a, 42-42 #d3b0d9,#314738, 43-61 #becfc4,#314738, 62-62 d,d, 63-79 #b2c3b8,d, 80-98 #b2c3b8,#152019, 99-99 d,d, |3: 0-2 d,#1d2824, 3-5 #d3b0d9,#1d2824, 6-39 #b2c3b8,#1d2824, 40-42 #b2c3b8,#314738, 43-61 #becfc4,#314738, 62-62 d,d, 63-76 #b2c3b8,d, 77-98 #b2c3b8,#152019, 99-99 d,d, diff --git a/test/snapshots/wrap.golden b/test/snapshots/wrap.golden index cc834fc5..b620b2a9 100644 --- a/test/snapshots/wrap.golden +++ b/test/snapshots/wrap.golden @@ -35,7 +35,7 @@ |10: 3 third line |11: 4 == snap on-wide grid=128x15 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/wrap/cwd/long.txt Save Tty Collapse Del | 1 0---------1---------2---------3---------4---------5---------6---------7---------8---------9---------A---------B---------↩ diff --git a/test/snapshots/yankpaste.golden b/test/snapshots/yankpaste.golden index 22cc787f..e81587f8 100644 --- a/test/snapshots/yankpaste.golden +++ b/test/snapshots/yankpaste.golden @@ -1,5 +1,5 @@ == snap linewise-below grid=100x31 cursor=13,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Exit +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol | * /tmp/pardes-snap/yankpaste/cwd/f.txt Save Tty Collapse Del | 1 line 1 diff --git a/test/window_opacity.py b/test/window_opacity.py index a576b1bd..0253e15c 100644 --- a/test/window_opacity.py +++ b/test/window_opacity.py @@ -66,15 +66,15 @@ def run(args): help_text = output('Help') require('WindowOpacity' in help_text and 'FgOpacity' not in help_text, 'help did not replace FgOpacity with WindowOpacity') - settings = output('Config') + settings = output('DumpConfig') require('WindowOpacity: 100%\n' in settings and 'FgOpacity' not in settings, - 'initial Config opacity not applied: ' + settings) + 'initial DumpConfig opacity not applied: ' + settings) require('Wayland opacity: background-only transparent surface' in log.read_text(errors='replace'), 'background-only surface path not selected') report['renderer_path'] = 'background-only transparent surface' def wait_applied(percent): - require(wait_for(lambda: f'WindowOpacity: {percent}%\n' in output('Config')), + require(wait_for(lambda: f'WindowOpacity: {percent}%\n' in output('DumpConfig')), 'opacity did not apply: ' + str(percent)) geometry = None @@ -138,10 +138,10 @@ def run(args): wait_applied(70) require(samples() == baseline, 'opacity altered editor or terminal core RGB/text') capture(70) - settings = output('Config') + settings = output('DumpConfig') require('WindowOpacity: 70%\n' in settings, '70% opacity not applied: ' + settings) command(client, source, 'WindowOpacity 101') - require('WindowOpacity: 70%\n' in output('Config'), 'invalid opacity changed state') + require('WindowOpacity: 70%\n' in output('DumpConfig'), 'invalid opacity changed state') command(client, source, 'WindowOpacity 0') wait_applied(0) require(samples() == baseline, 'zero opacity altered editor or terminal core RGB/text') @@ -207,7 +207,7 @@ def run(args): log.read_text(errors='replace')) require(all(int(value) == 0xffffffff for value in multipliers), 'whole-window alpha modifier would fade foreground text') - require('WindowOpacity: 100%\n' in output('Config'), '100% opacity not restored') + require('WindowOpacity: 100%\n' in output('DumpConfig'), '100% opacity not restored') require(source_path.read_bytes() == original == client.read(f'/pane/{source}/body'), 'source contents changed') client.write(f'/pane/{terminal}/pty/data', b'exit\r') -- cgit v1.3 From 048e81e3471c73b9ac690901819976f689f6a4ce Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 10:50:18 -0300 Subject: An append to a body through 9P costs its own bytes, not five passes over the whole body: 60 KB appends go from 35.7 to 2.1 ms each Round 25 measured bulk body writes at about 8 ms a write. There is no frame wait in it: a profile of open, write, clunk in a loop found the flush of each close walking the whole body five times. dotOf, setDot and showOffset turned the cursor between offsets and rows by counting every newline from the top; setContent found the line index's changed span by comparing old and new byte for byte, and hashed the new text to see whether it was back to the saved one. The rows now come from the file's line index by binary search (checked against the counting at every offset), a splice tells setContent the span it changed, and the text is hashed only when its length is the saved text's. Measured over 9P on a Debug build: 60 KB appends 35.7 to 2.1 ms, 8 KB 5.3 to 0.8 ms, 1 KB 1.3 to 0.9 ms. What is left is two copies of the text an edit (the splice's and the undo snapshot's). The perf gate gains body-appends, 64 appends of 8 KB on the 50k-line file, and its three baselines are recorded again. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 46 ++++++++++++++----- src/ninep/ctl.zig | 1 + src/ninep/pane.zig | 80 ++++++++++++++++++++++++++++++--- test/perf-baseline-gui-Debug.json | 2 +- test/perf-baseline-tty-Debug.json | 2 +- test/perf-baseline-tty-ReleaseFast.json | 2 +- test/perf.zig | 21 +++++++++ 7 files changed, 135 insertions(+), 19 deletions(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index e8a9e2f8..43b921e3 100644 --- a/src/File.zig +++ b/src/File.zig @@ -57,6 +57,9 @@ pub const State = struct { /// replaces it: an edit that brings the text back to it is clean again, /// as an undo to the save point is in acme. saved_hash: ?u64 = null, + /// The length of the text `saved_hash` is of, when it is of one: an + /// edit to another length cannot be back to it, and is not hashed. + saved_len: ?usize = null, watch_after_save: bool = false, /// Save makes the file's directory, and any above it, first: `Config`'s /// pane for an init file that is not there yet, whose directory may not @@ -617,14 +620,22 @@ pub fn lineIndex(gpa: std.mem.Allocator, f: *State) ![]const usize { /// The line index of `new` from `old`'s: an edit replaces one span, so /// line starts before it stand, starts after it shift, and only the span /// is scanned. Rebuilding scanned the whole file on every keystroke. -fn editedLineStarts(gpa: std.mem.Allocator, starts: []const usize, old: []const u8, new: []const u8) ![]usize { +/// The bytes a splice left alone at either end, when its caller knows them. +pub const Span = struct { head: usize, tail: usize }; + +fn editedLineStarts(gpa: std.mem.Allocator, starts: []const usize, old: []const u8, new: []const u8, known: ?Span) ![]usize { const n = @min(old.len, new.len); var head: usize = 0; - while (head + 64 <= n and std.mem.eql(u8, old[head..][0..64], new[head..][0..64])) head += 64; - while (head < n and old[head] == new[head]) head += 1; var tail: usize = 0; - while (tail + 64 <= n - head and std.mem.eql(u8, old[old.len - tail - 64 ..][0..64], new[new.len - tail - 64 ..][0..64])) tail += 64; - while (tail < n - head and old[old.len - tail - 1] == new[new.len - tail - 1]) tail += 1; + if (known) |span| { + head = span.head; + tail = span.tail; + } else { + while (head + 64 <= n and std.mem.eql(u8, old[head..][0..64], new[head..][0..64])) head += 64; + while (head < n and old[head] == new[head]) head += 1; + while (tail + 64 <= n - head and std.mem.eql(u8, old[old.len - tail - 64 ..][0..64], new[new.len - tail - 64 ..][0..64])) tail += 64; + while (tail < n - head and old[old.len - tail - 1] == new[new.len - tail - 1]) tail += 1; + } // A start s follows the newline at s-1: kept while that newline is in // the common head, shifted while it is in the common tail. const kept = std.sort.upperBound(usize, starts, head, struct { @@ -677,7 +688,12 @@ test "edited line index equals a rebuilt one" { const old = try gpa.dupe(u8, text.items); defer gpa.free(old); try text.replaceRange(gpa, at, del, ins[0..ins_len]); - const edited = try editedLineStarts(gpa, starts, old, text.items); + // As a splice that says what it kept, and as one that does not. + const known: Span = .{ .head = at, .tail = old.len - at - del }; + const told = try editedLineStarts(gpa, starts, old, text.items, known); + defer gpa.free(told); + const edited = try editedLineStarts(gpa, starts, old, text.items, null); + try std.testing.expectEqualSlices(usize, edited, told); defer gpa.free(edited); var fresh_state: State = undefined; fresh_state.content = text.items; @@ -906,6 +922,12 @@ fn reportEdit(p: *Pardes, f: *State, new: []const u8) void { } pub fn setContent(p: *Pardes, f: *State, new: []u8) void { + setContentSpan(p, f, new, null); +} + +/// `setContent` for a splice that knows what it left alone at either end, +/// so the line index is not found again by comparing the whole text. +pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span: ?Span) void { locations.freeRows(p.gpa, f.location_rows); f.location_rows = &.{}; for (p.panes) |slot| if (slot) |pane| { @@ -919,13 +941,17 @@ pub fn setContent(p: *Pardes, f: *State, new: []u8) void { reportEdit(p, f, new); if (f.mini) |*mini| mini.deinit(p.gpa); f.mini = null; - const starts: []usize = if (f.line_starts.len > 0) editedLineStarts(p.gpa, f.line_starts, f.content, new) catch &.{} else &.{}; - // ponytail: a whole-text hash per edit; a rolling hash when files grow large. - if (f.revision == f.saved_revision or f.saved_hash == null) f.saved_hash = std.hash.Wyhash.hash(0, f.content); + const starts: []usize = if (f.line_starts.len > 0) editedLineStarts(p.gpa, f.line_starts, f.content, new, span) catch &.{} else &.{}; + // ponytail: a whole-text hash per edit that keeps the saved length; a + // rolling hash when that too matters. + if (f.revision == f.saved_revision or f.saved_hash == null) { + f.saved_hash = std.hash.Wyhash.hash(0, f.content); + f.saved_len = f.content.len; + } p.gpa.free(f.content); f.content = new; f.revision +%= 1; - if (f.saved_hash) |h| if (std.hash.Wyhash.hash(0, new) == h) { + if (f.saved_hash) |h| if ((f.saved_len orelse new.len) == new.len and std.hash.Wyhash.hash(0, new) == h) { f.saved_revision = f.revision; }; f.mtime = pardes.ctlfs.events.now(); diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 5ed03c58..05f93ac5 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -983,6 +983,7 @@ fn get(p: *Pardes, pane: *Pane, failed: *anyerror) u16 { panes.File.setContent(p, f, bytes); f.saved_revision = f.revision; f.saved_hash = std.hash.Wyhash.hash(0, f.content); + f.saved_len = f.content.len; f.disk_newer = null; f.disk_gone = false; if (discarded) { diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 3fad1fae..af8bb52c 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -149,12 +149,62 @@ pub fn clip(n: usize) u32 { return std.math.cast(u32, n) orelse std.math.maxInt(u32); } +/// The file's line index when it describes `text` (built by a render or a +/// look), else null: with it a row is a binary search, not a count of every +/// newline from the top, which a bulk write paid on each flush, twice over. +fn lineIndex(pane: *const Pane, text: []const u8) ?[]const usize { + const f = if (pane.file) |*file| file else return null; + if (f.line_starts.len == 0 or f.content.ptr != text.ptr or f.content.len != text.len) return null; + return f.line_starts; +} + +/// The line `off` is on: the last start at or before it. +fn rowAt(starts: []const usize, off: usize) usize { + const after = std.sort.upperBound(usize, starts, off, struct { + fn order(key: usize, item: usize) std.math.Order { + return std.math.order(key, item); + } + }.order); + return after -| 1; +} + +fn lineEnd(starts: []const usize, text: []const u8, row: usize) usize { + return if (row + 1 < starts.len) starts[row + 1] - 1 else text.len; +} + +/// `modal.runeOffsetAt`, through the line index when there is one. +fn runeOffsetAt(pane: *const Pane, text: []const u8, c: modal.Cursor) usize { + const starts = lineIndex(pane, text) orelse return modal.runeOffsetAt(text, c); + const row = @min(c.row, starts.len - 1); + const s = starts[row]; + const e = lineEnd(starts, text, row); + return s + modal.runeStart(text[s..e], @min(c.col, e - s)); +} + +/// `modal.runePositionAt`, through the line index when there is one. +fn runePositionAt(pane: *const Pane, text: []const u8, off: usize) modal.Cursor { + const starts = lineIndex(pane, text) orelse return modal.runePositionAt(text, off); + const bounded = modal.runeStart(text, off); + const row = rowAt(starts, bounded); + return .{ .row = row, .col = bounded - starts[row] }; +} + +/// `modal.positionAt`, through the line index when there is one. +fn positionAt(pane: *const Pane, text: []const u8, off: usize) modal.Cursor { + const starts = lineIndex(pane, text) orelse return modal.positionAt(text, off); + const bounded = @min(off, text.len); + const row = rowAt(starts, bounded); + const s = starts[row]; + const e = lineEnd(starts, text, row); + return .{ .row = row, .col = modal.graphemeStart(text[s..e], @min(bounded - s, e - s)) }; +} + pub fn dotOf(pane: *Pane) State.Range { const text = bodyOf(pane); // In runes, as every address is (modal.runeStart). - const head = modal.runeOffsetAt(text, .{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)) }); + const head = runeOffsetAt(pane, text, .{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)) }); if (!pane.body.vsel.active) return .{ .q0 = clip(head), .q1 = clip(head) }; - const anchor = modal.runeOffsetAt(text, .{ .row = @intCast(@max(0, pane.body.vsel.row)), .col = @intCast(@max(0, pane.body.vsel.col)) }); + const anchor = runeOffsetAt(pane, text, .{ .row = @intCast(@max(0, pane.body.vsel.row)), .col = @intCast(@max(0, pane.body.vsel.col)) }); var hi = @max(head, anchor); if (hi < text.len) hi = modal.nextRune(text, hi); return .{ .q0 = clip(@min(head, anchor)), .q1 = clip(hi) }; @@ -164,9 +214,9 @@ pub fn setDot(pane: *Pane, r: State.Range) void { const text = bodyOf(pane); const q0 = @min(@as(usize, r.q0), text.len); const q1 = @max(q0, @min(@as(usize, r.q1), text.len)); - const a = modal.runePositionAt(text, q0); + const a = runePositionAt(pane, text, q0); pane.body.vsel = .{ .active = q1 > q0, .row = @intCast(a.row), .col = @intCast(a.col), .explicit = true }; - const h = modal.runePositionAt(text, if (q1 > q0) modal.prevRune(text, q1) else q0); + const h = runePositionAt(pane, text, if (q1 > q0) modal.prevRune(text, q1) else q0); pane.body.cur_row = @intCast(h.row); pane.body.cur_col = @intCast(h.col); pane.body.cur_pinned = true; @@ -177,7 +227,7 @@ pub fn setDot(pane: *Pane, r: State.Range) void { pub fn showOffset(pane: *Pane, off: usize) void { const text = bodyOf(pane); - const c = modal.positionAt(text, @min(off, text.len)); + const c = positionAt(pane, text, @min(off, text.len)); pane.body.cur_row = @intCast(c.row); pane.body.cur_col = @intCast(c.col); pane.body.cur_pinned = true; @@ -229,10 +279,28 @@ pub fn spliceBody(p: *Pardes, pane: *Pane, q0: usize, q1: usize, bytes: []const const join = pane.fs.joined == f.revision; pane.fs.joined = null; if (!pane.fs.nomark and !join) panes.File.pushUndo(p, pane); - panes.File.setContent(p, f, new); + panes.File.setContentSpan(p, f, new, .{ .head = lo, .tail = f.content.len - hi }); return take; } +test "rows through the line index are the ones counting newlines gives, at every offset" { + const p = try withFile(testing.allocator, "héllo\nwo\u{301}rld\n\n last line é\ntail"); + defer p.deinit(); + const pane = p.panes[0].?; + const f = &pane.file.?; + _ = try panes.File.lineIndex(p.gpa, f); + const text = bodyOf(pane); + try testing.expect(lineIndex(pane, text) != null); + for (0..text.len + 2) |off| { + try testing.expectEqual(modal.positionAt(text, off), positionAt(pane, text, off)); + try testing.expectEqual(modal.runePositionAt(text, off), runePositionAt(pane, text, off)); + } + for (0..8) |row| for (0..16) |col| { + const c: modal.Cursor = .{ .row = row, .col = col }; + try testing.expectEqual(modal.runeOffsetAt(text, c), runeOffsetAt(pane, text, c)); + }; +} + test "a terminal's body stats as long as it reads" { const gpa = testing.allocator; const p = try pardes.Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); diff --git a/test/perf-baseline-gui-Debug.json b/test/perf-baseline-gui-Debug.json index 55bb2b70..8808dd55 100644 --- a/test/perf-baseline-gui-Debug.json +++ b/test/perf-baseline-gui-Debug.json @@ -1 +1 @@ -{"harness":"75a55b9f838d3f0","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1970,"med_us":2159,"p90_us":2428,"max_us":2940},{"op":"render","fixture":"medium","min_us":75,"med_us":76,"p90_us":78,"max_us":79},{"op":"key-down","fixture":"medium","min_us":77,"med_us":81,"p90_us":83,"max_us":95},{"op":"key-right","fixture":"medium","min_us":77,"med_us":78,"p90_us":95,"max_us":107},{"op":"page-down","fixture":"medium","min_us":75,"med_us":78,"p90_us":81,"max_us":92},{"op":"wheel","fixture":"medium","min_us":75,"med_us":79,"p90_us":82,"max_us":83},{"op":"edit-char","fixture":"medium","min_us":1056,"med_us":1524,"p90_us":1648,"max_us":1751},{"op":"body-2m","fixture":"medium","min_us":8421,"med_us":15590,"p90_us":19804,"max_us":21613}]} +{"harness":"f420fe5db60d6e97","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1740,"med_us":2009,"p90_us":2077,"max_us":2079},{"op":"render","fixture":"medium","min_us":76,"med_us":80,"p90_us":90,"max_us":101},{"op":"key-down","fixture":"medium","min_us":77,"med_us":81,"p90_us":94,"max_us":95},{"op":"key-right","fixture":"medium","min_us":77,"med_us":82,"p90_us":86,"max_us":89},{"op":"page-down","fixture":"medium","min_us":77,"med_us":78,"p90_us":86,"max_us":99},{"op":"wheel","fixture":"medium","min_us":76,"med_us":76,"p90_us":80,"max_us":89},{"op":"edit-char","fixture":"medium","min_us":924,"med_us":1330,"p90_us":1522,"max_us":1566},{"op":"body-2m","fixture":"medium","min_us":4888,"med_us":8435,"p90_us":10635,"max_us":11460},{"op":"body-appends","fixture":"medium","min_us":119102,"med_us":187377,"p90_us":230392,"max_us":245721}]} diff --git a/test/perf-baseline-tty-Debug.json b/test/perf-baseline-tty-Debug.json index c4361c57..ef42f0ad 100644 --- a/test/perf-baseline-tty-Debug.json +++ b/test/perf-baseline-tty-Debug.json @@ -1 +1 @@ -{"harness":"75a55b9f838d3f0","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1831,"med_us":2060,"p90_us":2194,"max_us":2252},{"op":"render","fixture":"medium","min_us":75,"med_us":79,"p90_us":79,"max_us":87},{"op":"key-down","fixture":"medium","min_us":77,"med_us":80,"p90_us":86,"max_us":91},{"op":"key-right","fixture":"medium","min_us":77,"med_us":81,"p90_us":89,"max_us":92},{"op":"page-down","fixture":"medium","min_us":77,"med_us":81,"p90_us":85,"max_us":86},{"op":"wheel","fixture":"medium","min_us":75,"med_us":77,"p90_us":83,"max_us":93},{"op":"edit-char","fixture":"medium","min_us":1071,"med_us":1446,"p90_us":1889,"max_us":2537},{"op":"body-2m","fixture":"medium","min_us":8740,"med_us":15875,"p90_us":19640,"max_us":21463}]} +{"harness":"f420fe5db60d6e97","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1743,"med_us":2011,"p90_us":2152,"max_us":2217},{"op":"render","fixture":"medium","min_us":76,"med_us":79,"p90_us":80,"max_us":84},{"op":"key-down","fixture":"medium","min_us":77,"med_us":78,"p90_us":85,"max_us":89},{"op":"key-right","fixture":"medium","min_us":77,"med_us":80,"p90_us":83,"max_us":95},{"op":"page-down","fixture":"medium","min_us":78,"med_us":78,"p90_us":87,"max_us":95},{"op":"wheel","fixture":"medium","min_us":76,"med_us":80,"p90_us":88,"max_us":90},{"op":"edit-char","fixture":"medium","min_us":1122,"med_us":1501,"p90_us":1812,"max_us":2440},{"op":"body-2m","fixture":"medium","min_us":4949,"med_us":8504,"p90_us":10909,"max_us":11452},{"op":"body-appends","fixture":"medium","min_us":115605,"med_us":190785,"p90_us":226244,"max_us":245258}]} diff --git a/test/perf-baseline-tty-ReleaseFast.json b/test/perf-baseline-tty-ReleaseFast.json index 96ea5801..66421ba3 100644 --- a/test/perf-baseline-tty-ReleaseFast.json +++ b/test/perf-baseline-tty-ReleaseFast.json @@ -1 +1 @@ -{"harness":"75a55b9f838d3f0","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1760,"med_us":2041,"p90_us":2185,"max_us":2206},{"op":"render","fixture":"medium","min_us":76,"med_us":85,"p90_us":100,"max_us":102},{"op":"key-down","fixture":"medium","min_us":77,"med_us":78,"p90_us":85,"max_us":97},{"op":"key-right","fixture":"medium","min_us":76,"med_us":77,"p90_us":90,"max_us":92},{"op":"page-down","fixture":"medium","min_us":77,"med_us":80,"p90_us":85,"max_us":87},{"op":"wheel","fixture":"medium","min_us":75,"med_us":80,"p90_us":89,"max_us":97},{"op":"edit-char","fixture":"medium","min_us":1146,"med_us":1473,"p90_us":1659,"max_us":1796},{"op":"body-2m","fixture":"medium","min_us":8487,"med_us":15600,"p90_us":20312,"max_us":21859}]} +{"harness":"f420fe5db60d6e97","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1751,"med_us":2134,"p90_us":2183,"max_us":2415},{"op":"render","fixture":"medium","min_us":76,"med_us":77,"p90_us":91,"max_us":92},{"op":"key-down","fixture":"medium","min_us":77,"med_us":78,"p90_us":82,"max_us":83},{"op":"key-right","fixture":"medium","min_us":79,"med_us":85,"p90_us":100,"max_us":102},{"op":"page-down","fixture":"medium","min_us":78,"med_us":82,"p90_us":86,"max_us":95},{"op":"wheel","fixture":"medium","min_us":76,"med_us":79,"p90_us":83,"max_us":87},{"op":"edit-char","fixture":"medium","min_us":1063,"med_us":1290,"p90_us":1527,"max_us":1564},{"op":"body-2m","fixture":"medium","min_us":4950,"med_us":9414,"p90_us":10945,"max_us":13152},{"op":"body-appends","fixture":"medium","min_us":117839,"med_us":189253,"p90_us":232943,"max_us":247720}]} diff --git a/test/perf.zig b/test/perf.zig index fca4a3b0..95b55748 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -49,6 +49,10 @@ const Op = enum { /// 2 MB appended to the file through 9P, on one open, in 256 KB /// writes: linear, not a copy of the whole buffer per write. body_write, + /// 64 appends to the file through 9P, each its own open, 8 KB write and + /// close, as a shell's `>>` loop makes: each costs its own bytes, not a + /// pass over the whole body for its cursor, line index and saved hash. + body_appends, fn label(o: Op) []const u8 { return switch (o) { @@ -60,6 +64,7 @@ const Op = enum { .wheel => "wheel", .edit_char => "edit-char", .body_write => "body-2m", + .body_appends => "body-appends", }; } }; @@ -78,6 +83,20 @@ fn bodyWrite(core: *pardes.Pardes, serial: u32) void { _ = core.serveFs(.{ .tag = 4, .op = .release, .node = body, .handle = h, .opened = true }); } +const append_chunk_len = 8 * 1024; +const append_count = 64; + +fn bodyAppends(core: *pardes.Pardes, serial: u32) void { + const Node = pardes.ctlfs.Node; + const body = Node.of(serial, .body); + for (body_chunk[0..append_chunk_len], 0..) |*c, i| c.* = if (i % 64 == 63) '\n' else 'y'; + for (0..append_count) |_| { + const h = core.serveFs(.{ .tag = 1, .op = .open, .node = body, .omode = 1 }).handle; + _ = core.serveFs(.{ .tag = 2, .op = .write, .node = body, .handle = h, .data = body_chunk[0..append_chunk_len] }); + _ = core.serveFs(.{ .tag = 4, .op = .release, .node = body, .handle = h, .opened = true }); + } +} + const TermFixture = struct { name: []const u8, kb: usize, @@ -533,6 +552,7 @@ fn measure(op: Op, fx: Fixture, path: []const u8, expected_bytes: usize, reps: u .wheel => core.update(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = wheel_col, .row = wheel_row } }), .edit_char => core.update(.{ .key = .{ .cp = 'x', .text = "x" } }), .body_write => bodyWrite(core, pane.serial), + .body_appends => bodyAppends(core, pane.serial), } pump(core); _ = try frame(core); @@ -540,6 +560,7 @@ fn measure(op: Op, fx: Fixture, path: []const u8, expected_bytes: usize, reps: u switch (op) { .open => unreachable, .body_write => if (pane.file.?.content.len != before.len + 8 * body_chunk.len) return error.BodyWriteWasNotAppended, + .body_appends => if (pane.file.?.content.len != before.len + append_count * append_chunk_len) return error.BodyAppendsWereNotAppended, .render => if (pane.body.cur_row != before.row or pane.body.cur_col != before.col or pane.file.?.content.len != before.len) return error.RenderChangedDocument, .key_down => if (pane.body.cur_row != before.row + 1) return error.DownDidNotMove, -- cgit v1.3 From b43866d6ab784e518df8dbef374147367358ada9 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 14:02:59 -0300 Subject: Save makes the directories its file goes in, always: for the pane's own name and Save path alike Whether a Save made missing directories depended on how the name had come about. Config's pane did, a name written into a missing directory did (since kkrqxtsp), and `Save path` and every other name did not, failing ENOENT instead. There is now one rule: a Save makes the parent directories of the file it writes, a pane's own or a terminal's scrollback included, and the make_dirs flag is gone. A directory it cannot make still fails the write with why, as fs.py's /nonexistent-pardes-dir case shows. fs.py now also saves into missing directories by Save path and by a written name. Co-Authored-By: Claude Opus 5.5 --- docs/fs.md | 6 +++--- src/File.zig | 4 ---- src/builtins.zig | 3 +-- src/ninep/pane.zig | 18 ------------------ src/pardes.zig | 14 ++++++++++++-- test/fs.py | 14 ++++++++++++-- 6 files changed, 28 insertions(+), 31 deletions(-) (limited to 'src/File.zig') diff --git a/docs/fs.md b/docs/fs.md index 334b6783..49b10a7b 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -364,8 +364,7 @@ are ENOSPC, for this open and for a look, exec, `New` or `Tty` alike. **`name`** reads the file name (a terminal's directory); a write renames the buffer (relative to the pane's directory) and marks nothing dirty; `Save` -then writes under the new name, making its directories first when the name -went into one not there. A name is one line; refused (EINVAL) are a +then writes under the new name. A name is one line; refused (EINVAL) are a second line, a blank at either end, control bytes and non-UTF-8 (`bad character in file name: a blank at its start`, ...). Up to 255 bytes a component. @@ -391,7 +390,8 @@ redo available, then `current`/`notcurrent` and a REPL's id if bound. It takes: - the pane builtins: `Del` (`Del k`/`Del j`, or `DelAbove`/`DelBelow`, give - its rows to the pane above or below), `Save [path]`, `Collapse` (fold), + its rows to the pane above or below), `Save [path]` (making the + directories the file goes in first, whichever name it writes), `Collapse` (fold), `Undo`/`Redo` (256 steps each), `Find pat`, `Edit ...`, `Tty [shell]` (a new terminal pane in its directory), and the column words acting on its column: `Delcol`, `Left`/`Right`/`Up`/`Down`. diff --git a/src/File.zig b/src/File.zig index 43b921e3..84cec879 100644 --- a/src/File.zig +++ b/src/File.zig @@ -61,10 +61,6 @@ pub const State = struct { /// edit to another length cannot be back to it, and is not hashed. saved_len: ?usize = null, watch_after_save: bool = false, - /// Save makes the file's directory, and any above it, first: `Config`'s - /// pane for an init file that is not there yet, whose directory may not - /// be either. - make_dirs: bool = false, /// The file changed on disk under unsaved edits, which were kept (see /// `changed`): its hash, so the same change is said once, until a Save /// or get settles it. A Save warns once before overwriting it, as acme's diff --git a/src/builtins.zig b/src/builtins.zig index 8fe49649..5a2037cf 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1304,9 +1304,8 @@ pub const Config = struct { // Not there yet: a pane named for it, which Save makes. const free = c.p.freeSlot() orelse return c.p.reportError(c.id, "Config", error.NoPaneSlots); c.p.newScratchFor(c.id, .scratch); - const pane = c.p.panes[free] orelse return; + if (c.p.panes[free] == null) return; @import("ninep/pane.zig").nameBuffer(c.p, free, path, false) catch |err| return c.p.reportError(c.id, "Config", err); - pane.file.?.make_dirs = true; c.p.active = free; } }; diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 6a0fbba5..de7f7cd4 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -867,11 +867,6 @@ fn writeName(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { error.OutOfMemory => E.NOMEM, else => E.INVAL, }); - // A name into a directory not there yet asks for it, as Config's pane - // does: its Save makes the directories (`pardes new/dir/f` forwarded). - if (comptime pardes.hosted) if (fs.localPath(std.fs.path.dirname(full) orelse "/")) |local| { - if (!exec.isDirectory(local)) fileOf(pane).?.make_dirs = true; - }; return .{ .tag = req.tag, .written = @intCast(req.data.len) }; } @@ -1392,19 +1387,6 @@ test "a name with a component over 255 bytes is refused, and a long path's faile try testing.expect(std.mem.endsWith(u8, late, "/f.txt: no such directory")); } -test "a name into a directory not there has Save make it; one into a directory there does not" { - if (comptime !pardes.hosted) return error.SkipZigTest; - const p = try withFile(testing.allocator, "x\n"); - defer p.deinit(); - const serial = serialOf(p); - const f = fileOf(p.panes[p.paneBySerial(serial).?].?).?; - try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/pardes-no-such-dir-mk/sub/f.txt\n").reply.status); - try testing.expect(f.make_dirs); - f.make_dirs = false; - try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .name), "/tmp/f.txt\n").reply.status); - try testing.expect(!f.make_dirs); -} - test "a name cut across writes is one name, applied once at its newline or its close" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); diff --git a/src/pardes.zig b/src/pardes.zig index d8124588..841faf7a 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -5401,6 +5401,15 @@ pub const Pardes = struct { p.noteLateFailure(id); } + /// A Save makes the directories its file goes in, and any above them, + /// first: one rule, for the pane's own name and `Save path` alike. A + /// directory it cannot make leaves the write to fail and say why. + fn makeParents(path: []const u8) void { + if (comptime !hosted) return; + const local = filesystem.localPath(path) orelse return; + filesystem.makeDirs(std.fs.path.dirname(local) orelse "/"); + } + pub fn saveFailed(p: *Pardes, id: u8, path: []const u8, err: anyerror) void { if (p.panes[id]) |pane| if (pane.file) |*f| { // The `-%` spelling fs.zig already uses for "make this dirty". @@ -5490,8 +5499,7 @@ pub const Pardes = struct { const was = f.saved_revision; const failures = p.fs.failures; f.saved_revision = f.revision; - if (f.make_dirs) if (filesystem.localPath(f.path)) |local| - filesystem.makeDirs(std.fs.path.dirname(local) orelse "/"); + makeParents(f.path); p.hostWriteFile(sf.pane, f.path, f.content); const saved_pane = p.panes[sf.pane] orelse return; if (saved_pane.serial != serial) return; @@ -5520,6 +5528,7 @@ pub const Pardes = struct { if (pane.file) |*f| { const was = f.saved_revision; const failures = p.fs.failures; + makeParents(st.path.slice()); p.hostWriteFile(st.pane, st.path.slice(), f.content); const after = p.panes[st.pane] orelse return; if (after.serial != st.serial) return; @@ -5535,6 +5544,7 @@ pub const Pardes = struct { if (!pane.isTerminal()) return; const text = panes.terminal.screenTextAlloc(pane, p.gpa) catch return; defer p.gpa.free(text); + makeParents(st.path.slice()); p.hostWriteFile(st.pane, st.path.slice(), text); }, .write_dump => { diff --git a/test/fs.py b/test/fs.py index a1e2ae79..b02b9e45 100644 --- a/test/fs.py +++ b/test/fs.py @@ -381,8 +381,18 @@ def discovery(binary, embedded=False): # Through a mount both read as EINVAL; the log says which and why. assert f'err {scratch} addr: no match for regexp\n'.encode() in client.read('/log') client.remove(f'/pane/{scratch}') - # A save the host cannot do fails the write that asked for it, - # and the log's err record names the path and why. + # A Save makes the directories its file goes in, whatever names + # it: the pane's own name or Save's path. + made_dirs = new_pane(client, b'deep\n') + client.write(f'/pane/{made_dirs}/ctl', f'Save {root}/save-made/a/b/x.txt\n'.encode()) + assert (root / 'save-made/a/b/x.txt').read_bytes() == b'deep\n' + client.write(f'/pane/{made_dirs}/name', f'{root}/save-named/c/y.txt\n'.encode()) + client.write(f'/pane/{made_dirs}/ctl', b'Save\n') + assert (root / 'save-named/c/y.txt').read_bytes() == b'deep\n' + client.remove(f'/pane/{made_dirs}') + # A save the host cannot do (a directory it may not make) fails + # the write that asked for it, and the log's err record names + # the path and why. unsaved = new_pane(client, b'unsaved\n') try: client.write(f'/pane/{unsaved}/ctl', b'Save /nonexistent-pardes-dir/x.txt\n') -- cgit v1.3 From c04df904f2fa686cbe5ce0c078a96260af7b08bd Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 15:39:20 -0300 Subject: A diff reads as the code it changes: hunks in their file's language, added and removed rows tinted A .diff or .patch pane, and a command pane whose output is a diff (`git diff`, `git show`, `diff -u`; told by a `diff --git` line, or `---`/`+++` with a `@@` under them, in its first rows), colour each hunk's code in the language of the file its section names (`+++ b/`, `--- a/` for a deleted file), with tree-sitter, as highlightLocations does for results. src/diff.zig walks a unified diff by its `@@` counts, so a removed line that reads `--- x` is no header. Each side of a hunk is parsed as one text (context and removed lines the old side, context and added lines the new), so a string or comment across lines colours as it does in the file; a side no line takes its colours from is not parsed. A section's hunks share a parse, in pieces of about 40 lines (a hunk past 80 is cut), only those in view, and each piece's colours are kept by its bytes, so scrolling back and a terminal's every repaint parse nothing again. Added and removed lines carry a flag in their style byte; the painter tints their rows to the pane's edge, a little way from the page toward the theme's ANSI green or red, and draws the prefix in that hue pushed to read on it. A file in no known language keeps the old line colours. A command pane is read once its command has finished: its rows are copied once (File.DiffOutput, dropped when the pane runs again), so no frame dumps the scrollback, and painted over what git printed. A running command is shown as it prints. Co-Authored-By: Claude Opus 5.5 --- docs/tags.md | 14 ++ src/CHANGELOG.md | 8 + src/File.zig | 232 ++++++++++++++++++- src/body_layer.zig | 1 + src/diff.zig | 337 ++++++++++++++++++++++++++++ src/exec.zig | 1 + src/pardes.zig | 4 + src/syntax.zig | 499 ++++++++++++++++++++++++++++++++++++++--- test/snapshots/diffview.golden | 119 ++++++++++ test/snapshots/diffview.snap | 27 +++ 10 files changed, 1204 insertions(+), 38 deletions(-) create mode 100644 src/diff.zig create mode 100644 test/snapshots/diffview.golden create mode 100644 test/snapshots/diffview.snap (limited to 'src/File.zig') diff --git a/docs/tags.md b/docs/tags.md index 93c8a6fa..4d4e9178 100644 --- a/docs/tags.md +++ b/docs/tags.md @@ -64,6 +64,20 @@ Unsaved text shows on the pane's grip, as acme's modbutton, not in the tag. In a terminal the grip is two cells: the pane's mode (blank normal, `^` insert, `$` tty mode), then `*` while unsaved. +## Reviewing diffs + +Open a `.diff` or `.patch` file, or run `git diff` (or `git show`, `diff -u +old new`) as a command from any tag: once the command has finished, output +that starts as a diff does (a `diff --git` line, or a `--- ` line with `+++ +` and `@@` under it) is shown as one. Each hunk's code is coloured in the language of the file its +section names (`+++ b/`, or `--- a/` for a deleted file), its +old side (context and removed lines) and new side (context and added lines) +each parsed as one text, so a string or comment across lines colours as it +does in the file. Added and removed rows are tinted to the pane's edge, +their `+`/`-` in the tint's hue (the theme's ANSI green and red where it +has them); a file in no language pardes knows keeps the plain line colours. +Only the hunks in view are parsed, a few dozen lines at a time, each once. + ## Editing tags A tag is text like a body, with the body's normal and insert modes and undo. diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index 25740d16..5f53ff8a 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## Unreleased + +- A diff reads as the code it changes: a `.diff` or `.patch` file, and a + command's output that is a diff (`git diff`), colour each hunk in its + file's language, its old and new side each parsed whole, and tint added + and removed rows to the pane's edge with their `+`/`-` in the tint's hue. + Only the hunks in view are parsed, once each. + ## 0.0.8 - `~` and `~/` mean the home directory wherever a path is taken: look diff --git a/src/File.zig b/src/File.zig index 84cec879..2046a7cd 100644 --- a/src/File.zig +++ b/src/File.zig @@ -10,10 +10,12 @@ const Surface = pardes.Surface; const modal = @import("modal.zig"); const filesystem = @import("fs.zig"); const syntax = @import("syntax.zig"); +const diff = @import("diff.zig"); const tracy = @import("tracy.zig"); const dump = @import("dump.zig"); const limits = @import("memory.zig").limits; const locations = @import("locations.zig"); +const Colors = @import("colors.zig"); const Pane = panes.Pane; const Output = panes.Output; const Mini = panes.mini; @@ -1301,6 +1303,59 @@ pub fn drawGutter(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, const SynStyle = struct { fg: [3]u8, bold: bool }; +/// How added and removed diff lines are told apart in every theme: a row +/// ground a little way from the page toward green or red (the theme's own +/// ANSI green and red where it has a palette), and the prefix column in +/// that hue, pushed toward the ink until it reads on that ground. The +/// syntax colours are drawn over the ground unchanged. +pub const DiffTints = struct { + added_bg: [3]u8, + removed_bg: [3]u8, + added_fg: [3]u8, + removed_fg: [3]u8, + + pub fn of(p: *Pardes) DiffTints { + const th = p.theme(); + const page = th.bg orelse th.tag_bg; + const ink = th.fg orelse th.tag_fg; + const green: [3]u8 = if (th.palette) |pal| pal[2] else .{ 0x2e, 0xa0, 0x43 }; + const red: [3]u8 = if (th.palette) |pal| pal[1] else .{ 0xcf, 0x22, 0x2e }; + const added_bg = Colors.mixOklab(page, green, 0.18); + const removed_bg = Colors.mixOklab(page, red, 0.18); + return .{ + .added_bg = added_bg, + .removed_bg = removed_bg, + .added_fg = legible(green, ink, added_bg), + .removed_fg = legible(red, ink, removed_bg), + }; + } + + fn legible(hue: [3]u8, ink: [3]u8, ground: [3]u8) [3]u8 { + var fg = hue; + var step: usize = 0; + while (step < 4 and Colors.contrast(fg, ground) < 3) : (step += 1) fg = Colors.mixOklab(fg, ink, 0.4); + return fg; + } + + /// The row ground and prefix ink for a line's style byte, if it is an + /// added or removed line. + pub fn forStyle(t: *const DiffTints, style: u8) ?struct { bg: [3]u8, fg: [3]u8 } { + if (style & syntax.diff_added != 0) return .{ .bg = t.added_bg, .fg = t.added_fg }; + if (style & syntax.diff_removed != 0) return .{ .bg = t.removed_bg, .fg = t.removed_fg }; + return null; + } +}; + +/// A diff row's tint: its ground from `x` to the pane's edge. +fn tintRow(s: *Surface, x: u16, y: u16, end: u16, bg: [3]u8) void { + var col = x; + while (col < end) : (col += 1) { + const cell = s.at(col, y); + cell.default = false; + cell.style.bg = .{ .rgb = bg }; + } +} + fn synStyle(p: *Pardes, sy: syntax.Syn) ?SynStyle { return switch (sy) { .none => null, @@ -1320,6 +1375,7 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. const prefix_width = gutterWidth(pane); const tz_recolor = tracy.zone(@src(), "synRecolor"); defer tz_recolor.end(); + const tints: ?DiffTints = if (pane.colorAlgo() == .diff and highlights.len > 0) DiffTints.of(p) else null; // indexed start, same as bodyText — an empty tail simply paints nothing var flines = std.mem.splitScalar(u8, f.content[lineStart(p.gpa, f, f.scroll)..], '\n'); const total = nlines(p.gpa, f); @@ -1352,6 +1408,12 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. const metadata: ?locations.Row = if (row_index < f.location_rows.len) f.location_rows[row_index] else null; const decoration = Output.decorateRow(f.output, line, metadata); const chrome: ?*const pardes.ChromeTheme = if (decoration.plain()) null else p.bodyChrome(); + // An added or removed line's row, every wrapped row of it, is tinted. + const tint = if (tints) |*t| if (base >= highlight_start and base - highlight_start < highlights.len) + t.forStyle(highlights[base - highlight_start]) + else + null else null; + if (tint) |t| if (prefix_width < tw) tintRow(s, tx + @as(u16, @intCast(prefix_width)), body_y + vr, tx + tw, t.bg); var c: usize = 0; var screen_c: usize = 0; while (hs + c < limit and prefix_width + screen_c < tw) { @@ -1361,7 +1423,11 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. if (idx >= highlight_start) { const hidx = idx - highlight_start; if (hidx < highlights.len) { - if (synStyle(p, @enumFromInt(highlights[hidx]))) |ss| { + if (if (tint != null and hs + c == 0) + SynStyle{ .fg = tint.?.fg, .bold = true } + else + synStyle(p, @enumFromInt(highlights[hidx] & syntax.syn_bits))) |ss| + { var fill: usize = 0; while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) { const cell = s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr); @@ -1390,6 +1456,170 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. } } +/// What finished command panes printed, kept while it cannot change: a +/// copy of the terminal's rows, and whether they are a diff. Taken once +/// when a finished pane is first drawn, so neither a frame nor a look dumps +/// the whole scrollback again; a still running command is shown as it +/// printed. Keyed by the pane and its width (a resize rewraps every row); +/// a rerun in the pane drops it (exec.runCommand). +pub const DiffOutput = struct { + const Entry = struct { + serial: u32, + cols: u16, + is_diff: bool, + /// The rows joined by '\n'; `rows` are slices of it. + text: []u8, + rows: [][]const u8, + used: u64, + }; + slots: [4]?Entry = @splat(null), + clock: u64 = 0, + + pub fn reset(o: *DiffOutput, gpa: std.mem.Allocator) void { + for (&o.slots) |*slot| { + if (slot.*) |e| { + gpa.free(e.text); + gpa.free(e.rows); + } + slot.* = null; + } + } + + /// A pane's command runs again: what it printed before is gone. + pub fn drop(o: *DiffOutput, gpa: std.mem.Allocator, serial: u32) void { + for (&o.slots) |*slot| if (slot.*) |e| if (e.serial == serial) { + gpa.free(e.text); + gpa.free(e.rows); + slot.* = null; + }; + } + + /// A finished command pane's rows when they are a diff, else null. + pub fn lines(o: *DiffOutput, p: *Pardes, pane: *Pane) ?[]const []const u8 { + if (pane.command == null or !pane.command_done or pane.command_pty or pane.terminal == null) return null; + o.clock += 1; + for (&o.slots) |*slot| if (slot.*) |*e| if (e.serial == pane.serial and e.cols == pane.cols) { + e.used = o.clock; + return if (e.is_diff) e.rows else null; + }; + const shown = terminal.shellRows(p, pane) catch return null; + const is_diff = diff.looksLikeDiff(shown); + var total: usize = 0; + if (is_diff) for (shown) |row| { + total += row.len + 1; + }; + const text = p.gpa.alloc(u8, total) catch return null; + const rows = p.gpa.alloc([]const u8, if (is_diff) shown.len else 0) catch { + p.gpa.free(text); + return null; + }; + var at: usize = 0; + for (rows, 0..) |*row, i| { + @memcpy(text[at..][0..shown[i].len], shown[i]); + row.* = text[at..][0..shown[i].len]; + at += shown[i].len; + text[at] = '\n'; + at += 1; + } + var oldest: usize = 0; + for (&o.slots, 0..) |*slot, i| { + const e = slot.* orelse { + oldest = i; + break; + }; + if (o.slots[oldest]) |old| if (e.used < old.used) { + oldest = i; + }; + } + if (o.slots[oldest]) |old| { + p.gpa.free(old.text); + p.gpa.free(old.rows); + } + o.slots[oldest] = .{ .serial = pane.serial, .cols = pane.cols, .is_diff = is_diff, .text = text, .rows = rows, .used = o.clock }; + return if (is_diff) rows else null; + } +}; + +/// A command pane whose output is a diff (`git diff`, `diff -u`): its +/// rows coloured as a .diff file's are, over what the program printed. +/// The rows are the terminal's own, so a line it wrapped goes on in the +/// row below (syntax.highlightDiffRows). +pub fn recolorDiffOutput(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16, body: []const u8) void { + if (pane.command == null or !p.settings.colors) return; + const tz = tracy.zone(@src(), "diffRecolor"); + defer tz.end(); + const rows = p.diff_output.lines(p, pane) orelse return; + // The copy's rows are one text, joined as a file's lines are. + const flat_start = @intFromPtr(rows[0].ptr); + const last = rows[rows.len - 1]; + const flat = rows[0].ptr[0 .. @intFromPtr(last.ptr) + last.len - flat_start]; + const raw = pane.body.mode == .tty; + const View = struct { row: usize, at: usize }; + const arena = p.scratch.allocator(); + const views = arena.alloc(?View, body_h) catch return; + var lo: usize = std.math.maxInt(usize); + var hi: usize = 0; + var shown = std.mem.splitScalar(u8, body, '\n'); + for (views, 0..) |*view, vi| { + view.* = null; + const line = shown.next() orelse continue; + const vr: i32 = @intCast(vi); + const w = pane.wrapAt(vr); + const row_i: i32 = if (raw) terminal.gridOffset(pane) + vr else w.line; + if (row_i < 0 or row_i >= @as(i64, @intCast(rows.len))) continue; + const row: usize = @intCast(row_i); + const from: usize = if (raw) 0 else @intCast(@max(0, w.at)); + if (from > rows[row].len or !std.mem.startsWith(u8, rows[row][from..], line)) continue; + view.* = .{ .row = row, .at = from }; + const start = @intFromPtr(rows[row].ptr) - flat_start; + lo = @min(lo, start); + hi = @max(hi, start + rows[row].len); + } + if (lo > hi) return; + const styles = syntax.highlightDiffRows(arena, flat, lo, hi, true) catch return; + const tints = DiffTints.of(p); + const ink = p.theme().fg orelse p.theme().tag_fg; + const body_y = p.bodyTop(pane, r); + shown = std.mem.splitScalar(u8, body, '\n'); + for (views, 0..) |maybe, vr| { + const line = shown.next() orelse break; + const view = maybe orelse continue; + const base = @intFromPtr(rows[view.row].ptr) - flat_start - lo; + const tint = if (base < styles.len) tints.forStyle(styles[base]) else null; + if (tint) |t| tintRow(s, tx, body_y + @as(u16, @intCast(vr)), tx + tw, t.bg); + var c: usize = 0; + var screen_c: usize = 0; + while (c < line.len and screen_c < tw) { + const grapheme_end = modal.nextGrapheme(line, c); + if (grapheme_end <= c) break; + const cells = graphemeDisplayWidth(line[c..grapheme_end]); + const style = styles[base + view.at + c]; + const prefix = view.at + c == 0 and (line[0] == '+' or line[0] == '-'); + // On an added or removed line, what the program coloured red or + // green is the tint's to say now: its code takes the page's ink. + const paint: ?SynStyle = if (tint != null and prefix) + .{ .fg = tint.?.fg, .bold = true } + else if (synStyle(p, @enumFromInt(style & syntax.syn_bits))) |ss| + ss + else if (tint != null) + .{ .fg = ink, .bold = false } + else + null; + if (paint) |ss| { + var fill: usize = 0; + while (fill < cells and screen_c + fill < tw) : (fill += 1) { + const cell = s.at(tx + @as(u16, @intCast(screen_c + fill)), body_y + @as(u16, @intCast(vr))); + if (cell.default) continue; + cell.style.fg = .{ .rgb = ss.fg }; + cell.style.bold = ss.bold; + } + } + screen_c += cells; + c = grapheme_end; + } + } +} + pub fn drawWrapMarkers( p: *Pardes, s: *Surface, diff --git a/src/body_layer.zig b/src/body_layer.zig index cb26c1f2..8e7cd030 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -292,6 +292,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane panes.File.drawWrapMarkers(p, s, pane, r, tx, tw, body_h, pane_bg); } else if (pane.isTerminal() and p.settings.colors) { panes.terminal.recolorAnsi(p, s, pane, r, tx, tw, body_h, body); + panes.File.recolorDiffOutput(p, s, pane, r, tx, tw, body_h, body); } tz_color.end(); diff --git a/src/diff.zig b/src/diff.zig new file mode 100644 index 00000000..98942469 --- /dev/null +++ b/src/diff.zig @@ -0,0 +1,337 @@ +//! A unified diff (`git diff`, `diff -u`), read a line at a time: which +//! file each section is about, what each line is, and where a hunk line +//! stands in the old and the new file. The syntax painter (syntax.zig +//! highlightDiff) walks it. +//! +//! A hunk's extent comes from the counts in its `@@` header, as patch +//! reads it, so a removed line that itself starts `--` (`--- x`) is not +//! taken for a file header. +const std = @import("std"); + +pub const Kind = enum { + /// Anything outside a file header and a hunk: a commit message, + /// `Only in ...`, a mail's headers. + other, + /// `diff ...`, `index ...`, `new file mode ...`, `rename from ...`, + /// `Binary files ... differ`: said of the section, naming no line. + meta, + /// `--- ` + old_path, + /// `+++ ` + new_path, + /// `@@ -a,b +c,d @@` + hunk, + context, + added, + removed, + /// `\ No newline at end of file` + no_newline, +}; + +/// One line, walked. +pub const Line = struct { + kind: Kind, + /// Where it is in the old and the new file, from 1. A hunk header has + /// its first lines; a removed line the new line now standing where it + /// was (the one after it); an added line the old line after it. + old: usize = 0, + new: usize = 0, +}; + +pub const Walk = struct { + /// The section's paths, as written, borrowed from the lines walked: + /// `a/` and `b/` kept, timestamps cut. + old_path: []const u8 = "", + new_path: []const u8 = "", + /// `diff --git a/x b/y`'s b side, for a section with no `+++` yet + /// (a mode change, a rename, a binary file). + git_path: []const u8 = "", + old_left: usize = 0, + new_left: usize = 0, + old_at: usize = 0, + new_at: usize = 0, + /// The hunk's header numbers, which a look past its end clamps to. + new_start: usize = 0, + new_count: usize = 0, + /// Rows a terminal wrapped: inside a hunk, a row that starts with no + /// prefix at all continues the line above instead of ending the hunk. + continued_rows: bool = false, + last: Kind = .other, + + pub fn inHunk(w: *const Walk) bool { + return w.old_left > 0 or w.new_left > 0; + } + + /// The file the section is about: the new one, else (deleted) the old + /// one, else what its `diff --git` line names. + pub fn path(w: *const Walk) []const u8 { + if (w.new_path.len > 0 and !isDevNull(w.new_path)) return w.new_path; + if (w.old_path.len > 0 and !isDevNull(w.old_path)) return w.old_path; + return w.git_path; + } + + /// Whether the section deletes its file (`+++ /dev/null`). + pub fn deleted(w: *const Walk) bool { + return isDevNull(w.new_path); + } + + pub fn step(w: *Walk, line_raw: []const u8) Line { + const line = std.mem.trimEnd(u8, line_raw, "\r"); + const got = w.stepInner(line); + w.last = got.kind; + return got; + } + + fn stepInner(w: *Walk, line: []const u8) Line { + if (w.inHunk()) { + // A blank context line, its space stripped by a mailer or an + // editor, is still context. + const c: u8 = if (line.len == 0) ' ' else line[0]; + switch (c) { + ' ' => if (w.old_left > 0 and w.new_left > 0) { + const at: Line = .{ .kind = .context, .old = w.old_at, .new = w.new_at }; + w.old_left -= 1; + w.new_left -= 1; + w.old_at += 1; + w.new_at += 1; + return at; + }, + '-' => if (w.old_left > 0) { + const at: Line = .{ .kind = .removed, .old = w.old_at, .new = w.new_at }; + w.old_left -= 1; + w.old_at += 1; + return at; + }, + '+' => if (w.new_left > 0) { + const at: Line = .{ .kind = .added, .old = w.old_at, .new = w.new_at }; + w.new_left -= 1; + w.new_at += 1; + return at; + }, + '\\' => return .{ .kind = .no_newline, .old = w.old_at, .new = w.new_at }, + else => if (w.continued_rows and w.last != .hunk and w.last != .other) + return .{ .kind = w.last, .old = w.old_at, .new = w.new_at }, + } + // Counts run out, or a line no hunk has: the hunk was cut short. + w.old_left = 0; + w.new_left = 0; + } + if (line.len > 0 and line[0] == '\\' and w.last != .other and w.last != .meta) + return .{ .kind = .no_newline, .old = w.old_at, .new = w.new_at }; + if (std.mem.startsWith(u8, line, "diff ")) { + w.* = .{ .continued_rows = w.continued_rows }; + w.git_path = gitPath(line); + return .{ .kind = .meta }; + } + if (std.mem.startsWith(u8, line, "--- ")) { + // A second `---` with no `+++` between starts another section + // (plain `diff -u` output has no `diff` line of its own). + w.* = .{ .continued_rows = w.continued_rows, .git_path = w.git_path }; + w.old_path = cutPath(line[4..]); + return .{ .kind = .old_path }; + } + if (std.mem.startsWith(u8, line, "+++ ")) { + w.new_path = cutPath(line[4..]); + return .{ .kind = .new_path }; + } + if (parseHunk(line)) |h| { + w.old_left = h.old_count; + w.new_left = h.new_count; + w.old_at = h.old_start; + w.new_at = h.new_start; + w.new_start = h.new_start; + w.new_count = h.new_count; + return .{ .kind = .hunk, .old = h.old_start, .new = h.new_start }; + } + for (meta_words) |word| if (std.mem.startsWith(u8, line, word)) return .{ .kind = .meta }; + return .{ .kind = .other }; + } +}; + +const meta_words = [_][]const u8{ + "index ", "new file mode ", "deleted file mode ", "old mode ", "new mode ", + "similarity index ", "rename from ", "rename to ", "copy from ", "copy to ", + "Binary files ", "dissimilarity ", +}; + +fn isDevNull(path: []const u8) bool { + return std.mem.eql(u8, path, "/dev/null"); +} + +/// A `---`/`+++` path with what follows it cut: `diff -u`'s tab and +/// timestamp, and git's quotes round a name it had to escape. +fn cutPath(rest: []const u8) []const u8 { + var name = rest[0 .. std.mem.indexOfScalar(u8, rest, '\t') orelse rest.len]; + name = std.mem.trimEnd(u8, name, " \r"); + if (name.len >= 2 and name[0] == '"' and name[name.len - 1] == '"') name = name[1 .. name.len - 1]; + return name; +} + +/// `diff --git a/x b/y`: the b side. A name with a space in it is split at +/// the last ` b/`, which is right unless the old name has one too. +fn gitPath(line: []const u8) []const u8 { + if (!std.mem.startsWith(u8, line, "diff --git ")) return ""; + const rest = line["diff --git ".len..]; + const at = std.mem.lastIndexOf(u8, rest, " b/") orelse return ""; + return std.mem.trimEnd(u8, rest[at + 1 ..], " \r"); +} + +pub const HunkHeader = struct { old_start: usize, old_count: usize, new_start: usize, new_count: usize }; + +/// `@@ -a[,b] +c[,d] @@ ...`, a count left out meaning one. +pub fn parseHunk(line: []const u8) ?HunkHeader { + if (!std.mem.startsWith(u8, line, "@@ -")) return null; + var at: usize = "@@ -".len; + const old = range(line, &at) orelse return null; + if (at + 1 >= line.len or line[at] != ' ' or line[at + 1] != '+') return null; + at += 2; + const new = range(line, &at) orelse return null; + if (!std.mem.startsWith(u8, line[at..], " @@")) return null; + return .{ .old_start = old[0], .old_count = old[1], .new_start = new[0], .new_count = new[1] }; +} + +fn range(line: []const u8, at: *usize) ?[2]usize { + const start = number(line, at) orelse return null; + if (at.* < line.len and line[at.*] == ',') { + at.* += 1; + return .{ start, number(line, at) orelse return null }; + } + return .{ start, 1 }; +} + +fn number(line: []const u8, at: *usize) ?usize { + const from = at.*; + var n: usize = 0; + while (at.* < line.len and std.ascii.isDigit(line[at.*])) : (at.* += 1) + n = std.math.add(usize, std.math.mul(usize, n, 10) catch return null, line[at.*] - '0') catch return null; + return if (at.* > from) n else null; +} + +/// Where a walk that ends up at byte `pos` of `content` may safely start: +/// the start of the nearest `diff ` line before it (no hunk line starts +/// with a `d`), else the top. +pub fn anchorBefore(content: []const u8, pos: usize) usize { + var end = @min(pos, content.len); + while (end > 0) { + const nl = std.mem.lastIndexOfScalar(u8, content[0..end], '\n') orelse break; + if (std.mem.startsWith(u8, content[nl + 1 ..], "diff ") and nl + 1 <= pos) return nl + 1; + end = nl; + } + return 0; +} + +/// The same for a list of lines: the nearest `diff ` line at or above `row`. +pub fn anchorRow(lines: []const []const u8, row: usize) usize { + var r = @min(row, lines.len); + while (r > 0) { + r -= 1; + if (std.mem.startsWith(u8, lines[r], "diff ")) return r; + } + return 0; +} + +/// Whether text a command printed is a diff: a `diff --git` line, or a +/// `--- ` line with a `+++ ` line under it, in its first rows (after +/// `git show`'s commit header, say). +pub fn looksLikeDiff(lines: []const []const u8) bool { + const n = @min(lines.len, 200); + for (lines[0..n], 0..) |line, i| { + if (std.mem.startsWith(u8, line, "diff --git ")) return true; + if (std.mem.startsWith(u8, line, "--- ") and i + 1 < lines.len and std.mem.startsWith(u8, lines[i + 1], "+++ ") and + i + 2 < lines.len and parseHunk(lines[i + 2]) != null) return true; + } + return false; +} + +// ---- tests ---- + +const testing = std.testing; + +fn splitLines(comptime text: []const u8) [std.mem.count(u8, text, "\n")][]const u8 { + @setEvalBranchQuota(100_000); + var out: [std.mem.count(u8, text, "\n")][]const u8 = undefined; + var it = std.mem.splitScalar(u8, text, '\n'); + for (&out) |*line| line.* = it.next().?; + return out; +} + +const git_diff = + \\diff --git a/src/a.zig b/src/a.zig + \\index 1111111..2222222 100644 + \\--- a/src/a.zig + \\+++ b/src/a.zig + \\@@ -10,4 +10,4 @@ pub fn main() void { + \\ const a = 1; + \\-const b = 2; + \\+const b = 3; + \\+const c = 4; + \\ const d = 5; + \\--- x + \\@@ -40,2 +41,2 @@ + \\ keep(); + \\-gone(); + \\+added(); + \\diff --git a/old.py b/old.py + \\deleted file mode 100644 + \\--- a/old.py + \\+++ /dev/null + \\@@ -1,2 +0,0 @@ + \\-def f(): + \\- return 1 + \\ +; + +test "diff a walk follows the hunk counts, so a removed `--` line is no header" { + const lines = splitLines(git_diff); + var w: Walk = .{}; + var kinds: [lines.len]Kind = undefined; + for (lines, 0..) |line, i| kinds[i] = w.step(line).kind; + try testing.expectEqualSlices(Kind, &.{ + .meta, .meta, .old_path, .new_path, .hunk, + .context, .removed, .added, .added, .context, + .removed, .hunk, .context, .removed, .added, + .meta, .meta, .old_path, .new_path, .hunk, + .removed, .removed, + }, &kinds); +} + +test "diff plain diff -u output: no a/ b/, timestamps after the names" { + const lines = splitLines("--- old/x.zig\t2026-09-30 10:00:00.000000000 +0000\n" ++ + "+++ new/x.zig\t2026-09-30 11:00:00.000000000 +0000\n" ++ + "@@ -3 +3,2 @@\n" ++ + "-const a = 1;\n" ++ + "+const a = 2;\n" ++ + "+const b = 3;\n"); + try testing.expect(looksLikeDiff(&lines)); + var w: Walk = .{}; + for (lines) |line| _ = w.step(line); + try testing.expectEqualStrings("new/x.zig", w.path()); + try testing.expectEqualStrings("old/x.zig", w.old_path); +} + +test "diff output is told from other text by its first rows" { + const git = [_][]const u8{ "$ git diff", "diff --git a/x b/x", "index 1..2" }; + try testing.expect(looksLikeDiff(&git)); + const show = [_][]const u8{ "commit abc", "Author: a", "", " msg", "", "diff --git a/x b/x" }; + try testing.expect(looksLikeDiff(&show)); + const prose = [_][]const u8{ "--- a heading", "+++ not a path", "text" }; + try testing.expect(!looksLikeDiff(&prose)); + const nothing = [_][]const u8{ "ls", "a.zig b.zig" }; + try testing.expect(!looksLikeDiff(¬hing)); +} + +test "diff hunk headers: counts left out are one, a broken one is none" { + try testing.expectEqual(HunkHeader{ .old_start = 3, .old_count = 1, .new_start = 4, .new_count = 1 }, parseHunk("@@ -3 +4 @@").?); + try testing.expectEqual(HunkHeader{ .old_start = 1, .old_count = 0, .new_start = 0, .new_count = 0 }, parseHunk("@@ -1,0 +0,0 @@ fn x").?); + try testing.expect(parseHunk("@@ -a +1 @@") == null); + try testing.expect(parseHunk("@@ -1 +1") == null); + try testing.expect(parseHunk("@@@ -1 -1 +1 @@@") == null); +} + +test "diff a terminal's wrapped row stays in its line" { + const lines = [_][]const u8{ "--- a/x.c", "+++ b/x.c", "@@ -1,2 +1,2 @@", "+int a = 1; /* a long", "comment */", " int b;", "-int c;" }; + var w: Walk = .{ .continued_rows = true }; + var kinds: [lines.len]Kind = undefined; + for (lines, 0..) |line, k| kinds[k] = w.step(line).kind; + try testing.expectEqualSlices(Kind, &.{ .old_path, .new_path, .hunk, .added, .added, .context, .removed }, &kinds); +} diff --git a/src/exec.zig b/src/exec.zig index d114dbf8..5e223f04 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -738,6 +738,7 @@ fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { }; p.gpa.free(pane.command.?); pane.command = owned; + p.diff_output.drop(p.gpa, pane.serial); pane.command_done = false; pane.command_status = null; pane.command_pty = true; diff --git a/src/pardes.zig b/src/pardes.zig index b16d39b7..9fe6a1fb 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -4502,6 +4502,9 @@ pub const Pardes = struct { /// the terminal motion surface, memoized against the pane it was built /// for — see panes.terminal.RowsCache for the lifetime rule shell_rows: panes.terminal.RowsCache = .{}, + /// Finished command panes' output, and whether it is a diff + /// (File.DiffOutput). + diff_output: panes.File.DiffOutput = .{}, /// The message row's entry points, called from everywhere as /// `p.setMessage(...)`; they live with the rest of it in Messages.zig. @@ -4752,6 +4755,7 @@ pub const Pardes = struct { p.locations_cache.deinit(p.tree_sitter_gpa); p.fs.deinit(gpa); p.shell_rows.reset(gpa); + p.diff_output.reset(gpa); p.scratch.deinit(); p.frame_arena.deinit(); gpa.free(p.surface.cells); diff --git a/src/syntax.zig b/src/syntax.zig index 8ed00bfa..b7406b04 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -5,6 +5,11 @@ const grammar_manifest = @import("grammar_manifest.zig"); const look = @import("look.zig"); const regexp = @import("regexp.zig"); const c_heap = @import("c_heap"); +const diff = @import("diff.zig"); + +test { + _ = diff; +} pub const enabled = config.syntax_highlighting; const zig_grammar = config.syntax_zig_grammar; @@ -183,6 +188,7 @@ pub fn stop() void { spec.objects = null; spec.objects_failed = false; } + dropDiffPieces(); ts_set_allocator(null, null, null, null); syntax_started = false; syntax_allocator = undefined; @@ -1029,35 +1035,269 @@ fn childOfKind(node: ts.Node, kind: []const u8) ?ts.Node { return null; } -pub fn highlightDiff(gpa: std.mem.Allocator, content: []const u8, start_byte_raw: usize, end_byte_raw: usize) ![]u8 { - const start_byte = @min(start_byte_raw, content.len); - const end_byte = @max(start_byte, @min(end_byte_raw, content.len)); - const source = content[start_byte..end_byte]; - const styles = try gpa.alloc(u8, source.len); +/// A diff line's style byte carries whether the line was added or removed +/// over its syntax style (the low bits), so the painter can tint its row +/// and mark its prefix. +pub const diff_added: u8 = 0x80; +pub const diff_removed: u8 = 0x40; +pub const syn_bits: u8 = 0x3f; + +/// A file section's hunks are parsed together, each side as one text, in +/// pieces: a piece takes whole hunks until it holds `diff_piece_lines` +/// lines, and a hunk longer than `diff_piece_cut` is cut there, counted +/// from the section's first hunk. So a view parses about what a file's +/// view does (its rows and a margin), however many small hunks it shows, +/// and a 20k-line new file is parsed where it is shown, not whole. A string +/// or comment across a cut colours as a fragment would. +const diff_piece_lines = 40; +const diff_piece_cut = 80; + +/// Painted hunk pieces, keyed by their bytes and language: scrolling back +/// over a hunk, or a terminal repainting the same output every frame, +/// parses nothing again. Freed by `stop`. +const DiffPiece = struct { hash: u64, styles: []u8, used: u64 }; +var diff_pieces: [96]?DiffPiece = @splat(null); +var diff_clock: u64 = 0; + +fn dropDiffPieces() void { + for (&diff_pieces) |*slot| { + if (slot.*) |piece| syntax_allocator.free(piece.styles); + slot.* = null; + } + diff_clock = 0; +} + +/// The styles of `content[start..end)` read as a unified diff: headers +/// muted, `@@` lines as keywords, and each hunk's code in the language of +/// the file its section names. A hunk's old side (context and removed +/// lines) and new side (context and added lines) are each parsed whole, so +/// a string or comment that spans lines colours as it does in the file. +/// Added and removed lines carry `diff_added`/`diff_removed`. A file in no +/// language pardes knows keeps the plain colours: added lines as strings, +/// removed ones as numbers. +pub fn highlightDiff(gpa: std.mem.Allocator, content: []const u8, start_raw: usize, end_raw: usize) ![]u8 { + return highlightDiffRows(gpa, content, start_raw, end_raw, false); +} + +/// The same for a terminal's rows, where a row the terminal wrapped +/// continues the diff line above it. +pub fn highlightDiffRows(gpa: std.mem.Allocator, content: []const u8, start_raw: usize, end_raw: usize, continued_rows: bool) ![]u8 { + const tz = tracy.zone(@src(), "highlightDiff"); + defer tz.end(); + const start_byte = @min(start_raw, content.len); + const end_byte = @max(start_byte, @min(end_raw, content.len)); + const styles = try gpa.alloc(u8, end_byte - start_byte); errdefer gpa.free(styles); @memset(styles, 0); + const Window = struct { + styles: []u8, + start: usize, + fn put(w: @This(), at: usize, bytes: []const u8) void { + const lo = @max(at, w.start); + const hi = @min(at + bytes.len, w.start + w.styles.len); + if (lo < hi) @memcpy(w.styles[lo - w.start .. hi - w.start], bytes[lo - at .. hi - at]); + } + fn fill(w: @This(), at: usize, len: usize, style: u8) void { + const lo = @max(at, w.start); + const hi = @min(at + len, w.start + w.styles.len); + if (lo < hi) @memset(w.styles[lo - w.start .. hi - w.start], style); + } + }; + const window: Window = .{ .styles = styles, .start = start_byte }; + + var walk: diff.Walk = .{ .continued_rows = continued_rows }; + // The run of hunk lines not painted yet, with each line's kind. + var piece_start: ?usize = null; + var piece_end: usize = 0; + var piece_path: []const u8 = ""; + var kinds: [diff_piece_cut]diff.Kind = undefined; + var nkinds: usize = 0; + var at = diff.anchorBefore(content, start_byte); + while (true) { + const nl = std.mem.indexOfScalarPos(u8, content, at, '\n') orelse content.len; + const got = walk.step(content[at..nl]); + const body = switch (got.kind) { + .context, .added, .removed, .no_newline => true, + // The next hunk of the section goes on in the same piece. + .hunk => piece_start != null and nkinds < diff_piece_lines, + else => false, + }; + if (piece_start) |ps| if (!body or nkinds == diff_piece_cut) { + if (piece_end >= start_byte) try paintDiffPiece(gpa, window, content[ps..piece_end], ps, kinds[0..nkinds], piece_path); + piece_start = null; + nkinds = 0; + }; + if (at >= end_byte and piece_start == null) break; + if (body and (piece_start != null or got.kind != .hunk)) { + if (piece_start == null) { + piece_start = at; + piece_path = walk.path(); + } + kinds[nkinds] = got.kind; + nkinds += 1; + piece_end = nl; + } else if (nl >= start_byte) { + const style: Syn = switch (got.kind) { + .hunk => .keyword, + .meta, .old_path, .new_path => .comment, + else => .none, + }; + if (style != .none) window.fill(at, nl - at, @intFromEnum(style)); + } + if (nl >= content.len) break; + at = nl + 1; + } + if (piece_start) |ps| if (piece_end >= start_byte) + try paintDiffPiece(gpa, window, content[ps..piece_end], ps, kinds[0..nkinds], piece_path); + return styles; +} +fn paintDiffPiece(gpa: std.mem.Allocator, window: anytype, bytes: []const u8, at: usize, kinds: []const diff.Kind, path: []const u8) !void { + const selected: ?Selected = if (enabled and syntax_started) (forExt(std.fs.path.extension(path)) catch null) else null; + if (selected) |sel| { + const hash = std.hash.Wyhash.hash(std.hash.Wyhash.hash(0, sel.name), bytes); + diff_clock += 1; + for (&diff_pieces) |*slot| if (slot.*) |*piece| if (piece.hash == hash and piece.styles.len == bytes.len) { + piece.used = diff_clock; + return window.put(at, piece.styles); + }; + const colored = try syntax_allocator.alloc(u8, bytes.len); + errdefer syntax_allocator.free(colored); + try paintHunk(gpa, colored, bytes, kinds, sel); + window.put(at, colored); + var oldest: usize = 0; + for (&diff_pieces, 0..) |*slot, i| { + const piece = slot.* orelse { + oldest = i; + break; + }; + if (diff_pieces[oldest]) |o| if (piece.used < o.used) { + oldest = i; + }; + } + if (diff_pieces[oldest]) |old| syntax_allocator.free(old.styles); + diff_pieces[oldest] = .{ .hash = hash, .styles = colored, .used = diff_clock }; + return; + } + // No language: each line in one colour, as diffs were always shown. + var lines = std.mem.splitScalar(u8, bytes, '\n'); var offset: usize = 0; - var lines = std.mem.splitScalar(u8, source, '\n'); - while (lines.next()) |line| { - const syn = diffLineSyn(line); - if (syn != .none) @memset(styles[offset .. offset + line.len], @intFromEnum(syn)); + for (kinds) |kind| { + const line = lines.next() orelse break; + const style: u8 = switch (kind) { + .added => @intFromEnum(Syn.string) | diff_added, + .removed => @intFromEnum(Syn.number) | diff_removed, + .no_newline => @intFromEnum(Syn.comment), + .hunk => @intFromEnum(Syn.keyword), + else => 0, + }; + if (style != 0) window.fill(at + offset, line.len, style); offset += line.len + 1; } - return styles; } -fn diffLineSyn(line: []const u8) Syn { - if (std.mem.startsWith(u8, line, "@@")) return .keyword; - if (std.mem.startsWith(u8, line, "+++") or - std.mem.startsWith(u8, line, "---") or - std.mem.startsWith(u8, line, "diff ") or - std.mem.startsWith(u8, line, "index ") or - std.mem.startsWith(u8, line, "\\ No newline")) return .comment; - if (line.len == 0) return .none; - if (line[0] == '+') return .string; - if (line[0] == '-') return .number; - return .none; +/// One piece's styles: its old side and its new side each parsed as one +/// text, and every line's code coloured from its side, behind its +/// one-character prefix. A `@@` line between its hunks is in neither. +fn paintHunk(gpa: std.mem.Allocator, out: []u8, bytes: []const u8, kinds: []const diff.Kind, sel: Selected) !void { + @memset(out, 0); + const old_src = try gpa.alloc(u8, bytes.len); + defer gpa.free(old_src); + const new_src = try gpa.alloc(u8, bytes.len); + defer gpa.free(new_src); + var old_len: usize = 0; + var new_len: usize = 0; + var lines = std.mem.splitScalar(u8, bytes, '\n'); + for (kinds) |kind| { + const line = lines.next() orelse break; + const code = line[codeStart(line, kind)..]; + // A row a terminal wrapped goes on the line above, as it was printed. + const joined = continuesRow(line, kind); + if (kind == .context or kind == .removed) { + if (joined and old_len > 0) old_len -= 1; + @memcpy(old_src[old_len..][0..code.len], code); + old_len += code.len; + old_src[old_len] = '\n'; + old_len += 1; + } + if (kind == .context or kind == .added) { + if (joined and new_len > 0) new_len -= 1; + @memcpy(new_src[new_len..][0..code.len], code); + new_len += code.len; + new_src[new_len] = '\n'; + new_len += 1; + } + } + // A side is parsed only when a line takes its colours from it: the old + // side for removed lines, the new side for added lines, and context + // from the new side, else from the old. A piece that only adds or only + // removes is one parse. + var removes = false; + var adds = false; + for (kinds) |kind| { + removes = removes or kind == .removed; + adds = adds or kind == .added; + } + const context_new = adds or !removes; + const old_colors = try gpa.alloc(u8, old_len); + defer gpa.free(old_colors); + @memset(old_colors, 0); + if (!context_new or removes) paint(old_colors, old_src[0..old_len], sel); + const new_colors = try gpa.alloc(u8, new_len); + defer gpa.free(new_colors); + @memset(new_colors, 0); + if (context_new) paint(new_colors, new_src[0..new_len], sel); + + lines = std.mem.splitScalar(u8, bytes, '\n'); + var offset: usize = 0; + var old_at: usize = 0; + var new_at: usize = 0; + for (kinds) |kind| { + const line = lines.next() orelse break; + defer offset += line.len + 1; + const skip = codeStart(line, kind); + const code_len = line.len - skip; + const dst = out[offset + skip ..][0..code_len]; + if (continuesRow(line, kind)) { + if ((kind == .context or kind == .removed) and old_at > 0) old_at -= 1; + if ((kind == .context or kind == .added) and new_at > 0) new_at -= 1; + } + switch (kind) { + .removed => @memcpy(dst, old_colors[old_at..][0..code_len]), + .added => @memcpy(dst, new_colors[new_at..][0..code_len]), + .context => @memcpy(dst, if (context_new) new_colors[new_at..][0..code_len] else old_colors[old_at..][0..code_len]), + .no_newline => @memset(out[offset..][0..line.len], @intFromEnum(Syn.comment)), + .hunk => @memset(out[offset..][0..line.len], @intFromEnum(Syn.keyword)), + else => {}, + } + if (kind == .context or kind == .removed) old_at += code_len + 1; + if (kind == .context or kind == .added) new_at += code_len + 1; + const flag: u8 = switch (kind) { + .added => diff_added, + .removed => diff_removed, + else => 0, + }; + if (flag != 0) for (out[offset..][0..line.len]) |*b| { + b.* |= flag; + }; + } +} + +fn continuesRow(line: []const u8, kind: diff.Kind) bool { + return line.len > 0 and codeStart(line, kind) == 0 and + (kind == .context or kind == .added or kind == .removed); +} + +/// Where a hunk line's code starts: past its prefix, which a blank context +/// line (its space stripped) and a terminal's wrapped row have none of. +fn codeStart(line: []const u8, kind: diff.Kind) usize { + if (line.len == 0) return 0; + return switch (kind) { + .context => @intFromBool(line[0] == ' '), + .added => @intFromBool(line[0] == '+'), + .removed => @intFromBool(line[0] == '-'), + else => 0, + }; } test "syntax a results row is coloured by the file its location names" { @@ -1268,31 +1508,215 @@ test "syntax plain Markdown keeps block styles without starting the inline parse } test "syntax highlightDiff colors unified diff lines by prefix" { - const diff = + const diff_text = "diff --git a/x b/x\n" ++ "--- a/x\n" ++ "+++ b/x\n" ++ - "@@ -1,3 +1,3 @@\n" ++ + "@@ -1,2 +1,2 @@\n" ++ " context\n" ++ "-old line\n" ++ "+new line\n"; - const styles = try highlightDiff(std.testing.allocator, diff, 0, diff.len); + const styles = try highlightDiff(std.testing.allocator, diff_text, 0, diff_text.len); defer std.testing.allocator.free(styles); + try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "diff --git", 0)); + try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "--- a/x", 0)); + try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "+++ b/x", 0)); + try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "@@ -1,2", 0)); + try std.testing.expectEqual(Syn.none, diffSynAt(styles, diff_text, " context", 0)); + // A file in no known language: each line in one colour, and tinted. + try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "-old line", 0)); + try std.testing.expectEqual(Syn.string, diffSynAt(styles, diff_text, "+new line", 0)); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "-old line").?] & diff_removed != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "+new line").? + 4] & diff_added != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, " context").?] & (diff_added | diff_removed) == 0); +} - const byteSyn = struct { - fn at(s: []const u8, src: []const u8, needle: []const u8) Syn { - const i = std.mem.indexOf(u8, src, needle).?; - return @enumFromInt(s[i]); - } - }.at; +fn diffSynAt(styles: []const u8, text: []const u8, needle: []const u8, offset: usize) Syn { + return @enumFromInt(styles[std.mem.indexOf(u8, text, needle).? + offset] & syn_bits); +} + +test "syntax a Zig hunk is coloured as Zig, each side parsed whole" { + if (!enabled) return; + start(std.testing.allocator); + defer stop(); + const diff_text = + "diff --git a/src/shape.zig b/src/shape.zig\n" ++ + "index 1111111..2222222 100644\n" ++ + "--- a/src/shape.zig\n" ++ + "+++ b/src/shape.zig\n" ++ + "@@ -1,6 +1,6 @@\n" ++ + " const Shape = struct {\n" ++ + "- side: u8 = 7,\n" ++ + "+ side: u16 = 42,\n" ++ + " const note =\n" ++ + "- \\\\old words defer\n" ++ + "+ \\\\new words defer\n" ++ + " ;\n" ++ + " };\n"; + const styles = try highlightDiff(std.testing.allocator, diff_text, 0, diff_text.len); + defer std.testing.allocator.free(styles); + try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "struct", 0)); + try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "7,", 0)); + try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "42", 0)); + // A multiline string, told apart only by parsing the side it is on: + // `defer` inside it is no keyword. + try std.testing.expectEqual(Syn.string, diffSynAt(styles, diff_text, "old words defer", 10)); + try std.testing.expectEqual(Syn.string, diffSynAt(styles, diff_text, "new words defer", 10)); + // The prefix is no code: it carries the tint alone. + const added = std.mem.indexOf(u8, diff_text, "+ side").?; + try std.testing.expectEqual(diff_added, styles[added]); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "42").?] & diff_added != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "7,").?] & diff_removed != 0); + try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "index 111", 0)); + + // A window in the middle is coloured as the whole is. + const from = std.mem.indexOf(u8, diff_text, " const note").?; + const part = try highlightDiff(std.testing.allocator, diff_text, from, diff_text.len); + defer std.testing.allocator.free(part); + try std.testing.expectEqualSlices(u8, styles[from..], part); +} + +test "syntax a Python hunk is coloured as Python" { + if (!enabled or !full_grammars) return; + start(std.testing.allocator); + defer stop(); + const diff_text = + "--- a/tool.py\n" ++ + "+++ b/tool.py\n" ++ + "@@ -1,3 +1,4 @@\n" ++ + " def run(n):\n" ++ + "- return n\n" ++ + "+ # doubled now\n" ++ + "+ return n * 2\n" ++ + " \n"; + const styles = try highlightDiff(std.testing.allocator, diff_text, 0, diff_text.len); + defer std.testing.allocator.free(styles); + try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "def", 0)); + try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "return n\n", 0)); + try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "# doubled", 2)); + try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "2\n", 0)); +} + +test "syntax a deleted file's lines are coloured in its language" { + if (!enabled) return; + start(std.testing.allocator); + defer stop(); + const diff_text = + "diff --git a/gone.zig b/gone.zig\n" ++ + "deleted file mode 100644\n" ++ + "--- a/gone.zig\n" ++ + "+++ /dev/null\n" ++ + "@@ -1,2 +0,0 @@\n" ++ + "-const Gone = enum { a };\n" ++ + "-// the end\n"; + const styles = try highlightDiff(std.testing.allocator, diff_text, 0, diff_text.len); + defer std.testing.allocator.free(styles); + try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "enum", 0)); + try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "// the end", 3)); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "enum").?] & diff_removed != 0); + try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "deleted file", 0)); +} + +test "syntax a hunk in no known language keeps the line colours" { + if (!enabled) return; + start(std.testing.allocator); + defer stop(); + const diff_text = + "--- a/notes.unknownext\n" ++ + "+++ b/notes.unknownext\n" ++ + "@@ -1 +1 @@\n" ++ + "-const struct 1\n" ++ + "+const struct 2\n"; + const styles = try highlightDiff(std.testing.allocator, diff_text, 0, diff_text.len); + defer std.testing.allocator.free(styles); + try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "struct 1", 0)); + try std.testing.expectEqual(Syn.string, diffSynAt(styles, diff_text, "struct 2", 0)); + try std.testing.expectEqual(Syn.string, diffSynAt(styles, diff_text, "+const struct 2", 0)); +} - try std.testing.expectEqual(Syn.comment, byteSyn(styles, diff, "diff --git")); - try std.testing.expectEqual(Syn.comment, byteSyn(styles, diff, "--- a/x")); - try std.testing.expectEqual(Syn.comment, byteSyn(styles, diff, "+++ b/x")); - try std.testing.expectEqual(Syn.keyword, byteSyn(styles, diff, "@@ -1,3")); - try std.testing.expectEqual(Syn.none, byteSyn(styles, diff, " context")); - try std.testing.expectEqual(Syn.number, byteSyn(styles, diff, "-old line")); - try std.testing.expectEqual(Syn.string, byteSyn(styles, diff, "+new line")); +test "syntax git diff output in a command pane is told and coloured by its rows" { + if (!enabled) return; + start(std.testing.allocator); + defer stop(); + // A command pane's rows: its command line, then git's output, with one + // long added line the terminal wrapped onto a second row. + const rows = [_][]const u8{ + "git diff", + "diff --git a/main.zig b/main.zig", + "--- a/main.zig", + "+++ b/main.zig", + "@@ -1,2 +1,2 @@", + " pub fn main() void {", + "+ const answer: u32 = 42; // the ", + "wrapped rest", + "- return;", + "", + }; + try std.testing.expect(diff.looksLikeDiff(&rows)); + try std.testing.expect(!diff.looksLikeDiff(rows[5..])); + const text = try std.mem.join(std.testing.allocator, "\n", &rows); + defer std.testing.allocator.free(text); + const styles = try highlightDiffRows(std.testing.allocator, text, 0, text.len, true); + defer std.testing.allocator.free(styles); + try std.testing.expectEqual(Syn.none, diffSynAt(styles, text, "git diff", 0)); + try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, text, "fn main", 0)); + try std.testing.expectEqual(Syn.number, diffSynAt(styles, text, "42", 0)); + // The wrapped row stays an added line, and inside the comment. + try std.testing.expect(styles[std.mem.indexOf(u8, text, "wrapped rest").?] & diff_added != 0); + try std.testing.expectEqual(Syn.comment, diffSynAt(styles, text, "wrapped rest", 0)); + try std.testing.expect(styles[std.mem.indexOf(u8, text, "return").?] & diff_removed != 0); +} + +test "syntax a section's small hunks share one parse" { + if (!enabled) return; + const gpa = std.testing.allocator; + start(gpa); + defer stop(); + const diff_text = + "--- a/x.zig\n+++ b/x.zig\n" ++ + "@@ -1 +1 @@\n-const a = 1;\n+const a = 2;\n" ++ + "@@ -10 +10 @@\n-const b = 1;\n+const b = 2;\n" ++ + "@@ -20 +20 @@\n-const c = 1;\n+const c = 2;\n" ++ + "--- a/y.zig\n+++ b/y.zig\n" ++ + "@@ -1 +1 @@\n-const d = 1;\n+const d = 2;\n"; + const styles = try highlightDiff(gpa, diff_text, 0, diff_text.len); + defer gpa.free(styles); + var cached: usize = 0; + for (diff_pieces) |slot| cached += @intFromBool(slot != null); + try std.testing.expectEqual(@as(usize, 2), cached); // x.zig's three hunks, and y.zig's + try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "@@ -10", 0)); + try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "2;\n@@ -20", 0)); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "@@ -10").?] & (diff_added | diff_removed) == 0); +} + +test "syntax a hunk painted once is kept, and a long one is parsed in pieces" { + if (!enabled) return; + const gpa = std.testing.allocator; + start(gpa); + defer stop(); + var text: std.Io.Writer.Allocating = .init(gpa); + defer text.deinit(); + const n = diff_piece_cut * 20 + 10; + try text.writer.print("--- /dev/null\n+++ b/big.zig\n@@ -0,0 +1,{d} @@\n", .{n}); + for (0..n) |i| try text.writer.print("+const v{d} = {d};\n", .{ i, i }); + const content = text.written(); + const at = std.mem.indexOf(u8, content, "+const v1000 ").?; + const window = try highlightDiff(gpa, content, at, at + 200); + defer gpa.free(window); + try std.testing.expectEqual(Syn.number, @as(Syn, @enumFromInt(window["+const v1000 = ".len] & syn_bits))); + var cached: usize = 0; + for (diff_pieces) |slot| if (slot) |piece| { + cached += 1; + // One piece of many, not the whole hunk. + try std.testing.expect(piece.styles.len < content.len / 4); + }; + try std.testing.expectEqual(@as(usize, 1), cached); + const again = try highlightDiff(gpa, content, at, at + 200); + defer gpa.free(again); + try std.testing.expectEqualSlices(u8, window, again); + cached = 0; + for (diff_pieces) |slot| cached += @intFromBool(slot != null); + try std.testing.expectEqual(@as(usize, 1), cached); } test "syntax result fragments preserve source indentation and inline markup" { @@ -1526,3 +1950,4 @@ test "syntax source analysis preserves declarations and injected colors" { try std.testing.expectEqual(@as(usize, 0), unsupported.declarations.len); try std.testing.expectEqual(@as(usize, 0), unsupported.colors.len); } + diff --git a/test/snapshots/diffview.golden b/test/snapshots/diffview.golden new file mode 100644 index 00000000..2da9f6e3 --- /dev/null +++ b/test/snapshots/diffview.golden @@ -0,0 +1,119 @@ +== snap diff-pane grid=100x31 cursor=7,3 +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/diffview/cwd/change.diff Save Tty Collapse Del +| 1 diff --git a/src/shape.zig b/src/shape.zig +| 2 index 1111111..2222222 100644 +| 3 --- a/src/shape.zig +| 4 +++ b/src/shape.zig +| 5 @@ -1,10 +1,12 @@ +| 6 const std = @import("std"); +| 7 +| 8 pub const Shape = union(enum) { +| 9 circle: f32, +| 10 - square: u8 = 7, +| 11 + square: f32, +| 12 + triangle: struct { base: f32, height: f32 }, +| 13 +| 14 const note = +| 15 - \\areas +| 16 + \\areas, defer +| 17 + \\summed +| 18 ; +| 19 }; +| 20 +== style diff-colours grid=100x31 +|0: 0-99 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-2 d,#314738, 3-99 #becfc4,#314738, +|2: 0-1 d,#add38a, 2-2 d,#314738, 3-32 #becfc4,#314738, 33-44 #dfbce5,#314738, 45-99 #becfc4,#314738, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-99 #b9f480,#0d1410, +|4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #b9f480,#0d1410, +|5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #b9f480,#0d1410, +|6: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #b9f480,#0d1410, +|7: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #c9a7ed,#0d1410, +|8: 0-0 d,#608269, 1-4 d,#0d1410, 5-7 #59675c,#0d1410, 8-19 #e5eee5,#0d1410, 20-26 #c9a7ed,#0d1410, 27-27 #e5eee5,#0d1410, 28-32 #b8d88a,#0d1410, 33-99 #e5eee5,#0d1410, +|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, +|10: 0-0 d,#608269, 1-4 d,#0d1410, 5-7 #59675c,#0d1410, 8-25 #e5eee5,#0d1410, 26-30 #c9a7ed,#0d1410, 31-31 #e5eee5,#0d1410, 32-35 #c9a7ed,#0d1410, 36-99 #e5eee5,#0d1410, +|11: 0-0 d,#608269, 1-4 d,#0d1410, 5-11 #59675c,#0d1410, 12-99 #e5eee5,#0d1410, +|12: 0-0 d,#608269, 1-3 d,#0d1410, 4-6 #59675c,#0d1410, 7-7 #f1a39b,#302b25,b 8-11 #f1a39b,#302b25, 12-24 #e5eee5,#302b25, 25-25 #f8c082,#302b25, 26-99 #e5eee5,#302b25, +|13: 0-0 d,#608269, 1-3 d,#0d1410, 4-6 #59675c,#0d1410, 7-7 #b6ce94,#263025,b 8-11 #b6ce94,#263025, 12-99 #e5eee5,#263025, +|14: 0-0 d,#608269, 1-3 d,#0d1410, 4-6 #59675c,#0d1410, 7-7 #b6ce94,#263025,b 8-11 #b6ce94,#263025, 12-21 #e5eee5,#263025, 22-28 #c9a7ed,#263025, 29-99 #e5eee5,#263025, +|15: 0-0 d,#608269, 1-3 d,#0d1410, 4-99 #59675c,#0d1410, +|16: 0-0 d,#608269, 1-3 d,#0d1410, 4-11 #59675c,#0d1410, 12-99 #e5eee5,#0d1410, +|17: 0-0 d,#608269, 1-3 d,#0d1410, 4-6 #59675c,#0d1410, 7-7 #f1a39b,#302b25,b 8-15 #f1a39b,#302b25, 16-99 #b8d88a,#302b25, +|18: 0-0 d,#608269, 1-3 d,#0d1410, 4-6 #59675c,#0d1410, 7-7 #b6ce94,#263025,b 8-15 #b6ce94,#263025, 16-99 #b8d88a,#263025, +|19: 0-0 d,#608269, 1-3 d,#0d1410, 4-6 #59675c,#0d1410, 7-7 #b6ce94,#263025,b 8-15 #b6ce94,#263025, 16-99 #b8d88a,#263025, +|20: 0-0 d,#608269, 1-3 d,#0d1410, 4-11 #59675c,#0d1410, 12-99 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-3 d,#0d1410, 4-7 #59675c,#0d1410, 8-99 #e5eee5,#0d1410, +|22: 0-0 d,#608269, 1-3 d,#0d1410, 4-99 #59675c,#0d1410, +|23: 0-0 d,#608269, 1-99 d,#0d1410, +|24: 0-0 d,#608269, 1-99 d,#0d1410, +|25: 0-0 d,#608269, 1-99 d,#0d1410, +|26: 0-0 d,#608269, 1-99 d,#0d1410, +|27: 0-0 d,#608269, 1-99 d,#0d1410, +|28: 0-0 d,#608269, 1-99 d,#0d1410, +|29: 0-0 d,#608269, 1-99 d,#0d1410, +|30: 0-0 d,#608269, 1-99 d,#0d1410, +== snap command-pane grid=100x31 cursor=7,3 +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/diffview/cwd/cmds.txt Save Tty Collapse Del +| 1 cat change.diff Exec +| 2 +| +| +| +| +| +| +| +| +| +| +| +| +| /tmp/pardes-snap/diffview/cwd (cat change.diff) exit 0 Kill Save Collapse Del +| circle: f32, +| - square: u8 = 7, +| + square: f32, +| + triangle: struct { base: f32, height: f32 }, +| +| const note = +| - \\areas +| + \\areas, defer +| + \\summed +| ; +| }; +| exit 0 +== style command-colours grid=100x31 +|0: 0-99 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-2 d,#314738, 3-99 #becfc4,#314738, +|2: 0-1 d,#add38a, 2-2 d,#314738, 3-32 #becfc4,#314738, 33-41 #dfbce5,#314738, 42-99 #becfc4,#314738, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-93 #e5eee5,#0d1410, 94-94 #e5eee5,#1d2824, 95-99 #b2c3b8,#1d2824, +|4: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, +|5: 0-0 d,#608269, 1-99 d,#0d1410, +|6: 0-0 d,#608269, 1-99 d,#0d1410, +|7: 0-0 d,#608269, 1-99 d,#0d1410, +|8: 0-0 d,#608269, 1-99 d,#0d1410, +|9: 0-0 d,#608269, 1-99 d,#0d1410, +|10: 0-0 d,#608269, 1-99 d,#0d1410, +|11: 0-0 d,#608269, 1-99 d,#0d1410, +|12: 0-0 d,#608269, 1-99 d,#0d1410, +|13: 0-0 d,#608269, 1-99 d,#0d1410, +|14: 0-0 d,#608269, 1-99 d,#0d1410, +|15: 0-0 d,#608269, 1-99 d,#0d1410, +|16: 0-0 d,#608269, 1-99 d,#0d1410, +|17: 0-1 d,#496656, 2-2 d,#1d2824, 3-99 #b2c3b8,#1d2824, +|18: 0-0 d,#152019, 1-6 d,#0d1410, 7-99 #e5eee5,#0d1410, +|19: 0-0 d,#152019, 1-1 d,#0d1410, 2-2 #f1a39b,#302b25,b 3-6 #f1a39b,#302b25, 7-19 #e5eee5,#302b25, 20-20 #f8c082,#302b25, 21-99 #e5eee5,#302b25, +|20: 0-0 d,#152019, 1-1 d,#0d1410, 2-2 #b6ce94,#263025,b 3-6 #b6ce94,#263025, 7-99 #e5eee5,#263025, +|21: 0-0 d,#152019, 1-1 d,#0d1410, 2-2 #b6ce94,#263025,b 3-6 #b6ce94,#263025, 7-16 #e5eee5,#263025, 17-23 #c9a7ed,#263025, 24-99 #e5eee5,#263025, +|22: 0-0 d,#152019, 1-99 d,#0d1410, +|23: 0-0 d,#608269, 1-6 d,#0d1410, 7-99 #e5eee5,#0d1410, +|24: 0-0 d,#608269, 1-1 d,#0d1410, 2-2 #f1a39b,#302b25,b 3-10 #f1a39b,#302b25, 11-99 #b8d88a,#302b25, +|25: 0-0 d,#608269, 1-1 d,#0d1410, 2-2 #b6ce94,#263025,b 3-10 #b6ce94,#263025, 11-99 #b8d88a,#263025, +|26: 0-0 d,#608269, 1-1 d,#0d1410, 2-2 #b6ce94,#263025,b 3-10 #b6ce94,#263025, 11-99 #b8d88a,#263025, +|27: 0-0 d,#608269, 1-6 d,#0d1410, 7-99 #e5eee5,#0d1410, +|28: 0-0 d,#608269, 1-2 d,#0d1410, 3-99 #e5eee5,#0d1410, +|29: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|30: 0-0 d,#152019, 1-99 d,#0d1410, diff --git a/test/snapshots/diffview.snap b/test/snapshots/diffview.snap new file mode 100644 index 00000000..b5900db9 --- /dev/null +++ b/test/snapshots/diffview.snap @@ -0,0 +1,27 @@ +# A diff pane, for reviewing a change: each hunk's code coloured as Zig (a +# multi-line string over three lines, `defer` inside it no keyword), added and +# removed rows tinted to the pane's edge with their prefix in the tint's hue, +# headers muted. +dirmk .git +dirmk src +file src/shape.zig const std = @import("std");\n\npub const Shape = union(enum) {\n circle: f32,\n square: f32,\n triangle: struct { base: f32, height: f32 },\n\n const note =\n \\\\areas, defer\n \\\\summed\n ;\n};\n +file change.diff diff --git a/src/shape.zig b/src/shape.zig\nindex 1111111..2222222 100644\n--- a/src/shape.zig\n+++ b/src/shape.zig\n@@ -1,10 +1,12 @@\n const std = @import("std");\n \n pub const Shape = union(enum) {\n circle: f32,\n- square: u8 = 7,\n+ square: f32,\n+ triangle: struct { base: f32, height: f32 },\n \n const note =\n- \\\\areas\n+ \\\\areas, defer\n+ \\\\summed\n ;\n };\n +start 31 100 change.diff +wait 8000 Newcol Joincol +stable 700 20000 +snap diff-pane +snapstyle diff-colours +# The same diff printed by a command (`git diff`, here `cat`) into a command +# pane: its output is told for a diff and coloured the same, over the colours +# the program printed. +file cmds.txt cat change.diff\n +start 31 100 cmds.txt +wait 8000 cmds.txt +stable 700 20000 +press middle 7 4 +drag middle 22 4 +release middle 22 4 +wait 10000 exit 0 +stable 700 15000 +snap command-pane +snapstyle command-colours -- cgit v1.3 From a15eabc3b9d98ef5f659ca82a2b0f2afb7451a39 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 16:47:19 -0300 Subject: A restored pane whose file is gone from disk comes back dirty, and Del asks before throwing its text away A dump keeps a pane's text. Restored after its file was deleted, the pane came back clean: the watch's baseline read of the missing file failed quietly, and Del closed it without a word. Its text was then nowhere at all. Restore now checks the file: a local path with nothing on disk comes back as one deleted on disk, as the watch would have said. It says so once, logs `changed N deleted`, and is dirty, so Del, Exit and Restore ask first. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 5 +++++ src/ninep/ctl.zig | 15 +++++++++++++++ 2 files changed, 20 insertions(+) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index 2046a7cd..78c84287 100644 --- a/src/File.zig +++ b/src/File.zig @@ -888,6 +888,11 @@ pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { pane.cols = @max(1, src.cols); pane.rows = @max(1, src.rows); if (output == null and filesystem.localPath(path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true, .mode = .baseline_disk } }); + // Its file gone from disk since the dump: its text is nowhere else now, + // so it comes back as one deleted on disk, dirty, and Del, Exit and + // Restore ask before throwing it away. + if (comptime pardes.hosted) if (output == null) if (filesystem.localPath(path)) |local| + if (@import("exec.zig").kindOf(local) == null) deleted(p, @intCast(id)); return pane; } diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 9a95a10f..549aa265 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -2525,6 +2525,21 @@ test "Kill with a name and nothing running says so and does not fail, as bare Ki try testing.expect(th.logHas(p, "Kill: nothing running")); } +test "a restored pane whose file is gone from disk comes back dirty, and Del asks first" { + if (comptime !pardes.hosted) return error.SkipZigTest; + const p = try withFile(testing.allocator, "kept text\n"); + defer p.deinit(); + try pane_files.nameBuffer(p, 0, "/tmp/pardes-restore-gone-xyz/f.txt", false); + try pardes.dump.dumpState(p); + const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); + defer restored.deinit(); + const again = restored.panes[restored.paneBySerial(restored.panes[0].?.serial).?].?; + try testing.expect(again.file.?.disk_gone); + const r = wr(restored, Node.of(again.serial, .ctl), "Del\n"); + try testing.expectEqual(Status.err, r.reply.status); + try testing.expect(std.mem.indexOf(u8, r.reply.ename, "Modified") != null); +} + test "a line starting with # runs as nothing at an exec or a ctl, silently" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); -- cgit v1.3 From 9a256d34ebca317e3007adf71c2b94016059d4a3 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 18:40:41 -0300 Subject: A selection deep in a long line costs a render what one at its start does: 5 MB in, /screen goes from 14.7 s to 5 ms Every render measured a selection's and the cursor's columns from the start of their line (lineDisplayOffset walked the whole prefix twice), so a selection near the end of a 5 MB line stalled each frame, 3 s at 1 MB in and 14.7 s at 5 MB. The cost grew with the offset, with Wrap on or off. Three changes make it independent of where the selection is: - display width adds (a tab is tab_width wherever it stands), so the offset between two columns is the width of the text between them, never the prefix; - the selection's rows are clamped to what is shown: a row wholly before the selection is skipped, a start before the row's first column starts there, and an end past its last column ends there; - a head or cursor whose column lies past its visible row (the last visible row of a line owns every column after its start) is not measured, since it is not drawn. Measured on a Debug build, 5 MB line: offset 10, 1 MB and 5 MB now take 11, 6 and 5 ms per /screen. A new perf gate case, deep-sel, renders with the selection 2 MB into a line: 83 us on Debug. The baselines were re-recorded for the new harness. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 15 ++++++++++---- src/body_layer.zig | 35 +++++++++++++++++++++++++++++++-- test/perf-baseline-gui-Debug.json | 2 +- test/perf-baseline-tty-Debug.json | 2 +- test/perf-baseline-tty-ReleaseFast.json | 2 +- test/perf.zig | 28 +++++++++++++++++++++++--- 6 files changed, 72 insertions(+), 12 deletions(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index 78c84287..a89db613 100644 --- a/src/File.zig +++ b/src/File.zig @@ -352,11 +352,18 @@ pub fn byteAtDisplayFrom(line_text: []const u8, from_raw: usize, display_col: us return from +| rawAtDisplay(line_text[from..], display_col); } +/// The display columns from `from_raw` to `to_raw` on a line. Widths add +/// (a tab is `tab_width` wherever it stands), so only the text between +/// the two is measured, never the line from its start: a selection a +/// million bytes into a line draws as fast as one at its start. pub fn lineDisplayOffset(line_text: []const u8, from_raw: usize, to_raw: usize) i32 { - const from_display = rawDisplayCol(line_text, from_raw); - const to_display = rawDisplayCol(line_text, to_raw); - if (to_display >= from_display) return @intCast(to_display - from_display); - return -@as(i32, @intCast(from_display - to_display)); + const lo = @min(from_raw, to_raw); + const hi = @max(from_raw, to_raw); + const a = modal.graphemeStart(line_text, @min(lo, line_text.len)); + const b = modal.graphemeStart(line_text, @min(hi, line_text.len)); + const past = (hi -| line_text.len) - (lo -| line_text.len); + const width: usize = displayWidth(line_text[a..b]) +| past; + return if (to_raw >= from_raw) @intCast(width) else -@as(i32, @intCast(width)); } pub fn lineDisplayEndOffset(line_text: []const u8, from_raw: usize, at_raw: usize) i32 { diff --git a/src/body_layer.zig b/src/body_layer.zig index 8e7cd030..914694e7 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -83,6 +83,17 @@ fn paintTerminalSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: [ } } +/// Whether `col` lies past the last column its visible row shows: the last +/// visible row of a line owns every column after its start (wrapRow), so a +/// head millions of bytes along a long line is on that row, off the view. +fn pastView(pane: *Pane, body: []const u8, line: i32, row: i32, at: i32, col: i32, tw: u16) bool { + const text = if (pane.file != null) panes.File.sourceLine(pane, line) else modal.lineSlice(body, @intCast(@max(0, row))); + const from: usize = @intCast(@max(0, at)); + const to: usize = @intCast(@max(0, col)); + if (from >= text.len) return to >= from +| tw; + return to >= from + panes.File.byteAtDisplay(text[from..], tw) and to < text.len; +} + fn paintSourceSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: []const Pane.PointerRow, bg: [3]u8, fg: ?[3]u8) void { if (pane.isTerminal()) return paintTerminalSelection(p, s, pane, r, rows, bg, fg); const terminal_lines = if (pane.file == null) panes.terminal.cursorLines(p, pane) catch return else &.{}; @@ -371,14 +382,26 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane const w = pane.wrapAt(vr); if (w.line < bnd.lo_row or w.line > bnd.hi_row) continue; const visible_line = modal.lineSlice(body, @intCast(vr)); - const cstart: i32 = if (w.line == bnd.lo_row) + // Only the visible columns are measured: a selection that + // starts before this row's first column starts at it, and + // one that ends past its last ends there. + const row_text = if (pane.file != null) panes.File.sourceLine(pane, w.line) else visible_line; + const row_at: usize = @intCast(@max(0, w.at)); + // The byte past the row's last column, walked from its first: + // bounded by the view, not the line. + // A line that ends inside the view has no column past it. + const shown_to = if (row_at >= row_text.len) row_text.len else row_at + panes.File.byteAtDisplay(row_text[row_at..], tw); + const past_view = if (shown_to >= row_text.len) std.math.maxInt(usize) else shown_to; + // A row that ends before the selection starts has none of it. + if (w.line == bnd.lo_row and @as(usize, @intCast(@max(0, bnd.lo_col))) >= past_view) continue; + const cstart: i32 = if (w.line == bnd.lo_row and bnd.lo_col > w.at) (if (pane.file != null) panes.File.displayOffset(pane, w.line, w.at, bnd.lo_col) else panes.File.lineDisplayOffset(visible_line, @intCast(@max(0, w.at)), @intCast(@max(0, bnd.lo_col)))) + vpfx else vpfx; - const cend: i32 = if (w.line == bnd.hi_row) + const cend: i32 = if (w.line == bnd.hi_row and @as(usize, @intCast(@max(0, bnd.hi_col))) < past_view) (if (pane.file != null) panes.File.displayEndOffset(pane, w.line, w.at, bnd.hi_col) else @@ -396,6 +419,10 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane if (primary and !preview and !hover_only) continue; // the hardware cursor IS the primary's if (hover_only) continue; // quiet preview preserves the source ink const cw = pane.wrapRow(sr.row, sr.col); + // A head off the view is measured not at all: its row is not + // drawn, and its column may be millions of bytes along. + if (cw.row < 0 or cw.row + @as(i32, pane.tag_rows) >= @as(i32, body_bottom)) continue; + if (pastView(pane, body, sr.row, cw.row, cw.at, sr.col, tw)) continue; const crow = cw.row + @as(i32, pane.tag_rows); const ccol = (if (pane.file != null) panes.File.displayOffset(pane, sr.row, cw.at, sr.col) @@ -447,6 +474,9 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane const ccol = if (pane.body.cur_pinned) pane.body.cur_col else @as(i32, @intCast(cur.x)); const cwp = pane.wrapRow(crow, ccol); const prow = cwp.row + @as(i32, pane.tag_rows); + // Off the view, the cursor is not measured (its column may be + // millions of bytes along a line whose start is shown). + if (cwp.row >= 0 and prow < body_bottom and !pastView(pane, body, crow, cwp.row, cwp.at, ccol, tw)) { // Files store source-byte columns; the Surface stores display // cells, so account for every expanded tab before the cursor. const cx = if (pane.file != null) @@ -461,6 +491,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane ccol; if (prow >= pane.tag_rows and cx >= 0 and prow < body_bottom and cx < tw) s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = body_y + @as(u16, @intCast(prow - pane.tag_rows)), .bar = pane.body.mode == .insert }; + } } else if (panes.terminal.visibleCursor(pane)) |cur| { if (cur.y + pane.tag_rows < body_bottom and cur.x < tw) s.cursor = .{ .x = tx + cur.x, .y = body_y + cur.y }; diff --git a/test/perf-baseline-gui-Debug.json b/test/perf-baseline-gui-Debug.json index 8808dd55..ace9a967 100644 --- a/test/perf-baseline-gui-Debug.json +++ b/test/perf-baseline-gui-Debug.json @@ -1 +1 @@ -{"harness":"f420fe5db60d6e97","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1740,"med_us":2009,"p90_us":2077,"max_us":2079},{"op":"render","fixture":"medium","min_us":76,"med_us":80,"p90_us":90,"max_us":101},{"op":"key-down","fixture":"medium","min_us":77,"med_us":81,"p90_us":94,"max_us":95},{"op":"key-right","fixture":"medium","min_us":77,"med_us":82,"p90_us":86,"max_us":89},{"op":"page-down","fixture":"medium","min_us":77,"med_us":78,"p90_us":86,"max_us":99},{"op":"wheel","fixture":"medium","min_us":76,"med_us":76,"p90_us":80,"max_us":89},{"op":"edit-char","fixture":"medium","min_us":924,"med_us":1330,"p90_us":1522,"max_us":1566},{"op":"body-2m","fixture":"medium","min_us":4888,"med_us":8435,"p90_us":10635,"max_us":11460},{"op":"body-appends","fixture":"medium","min_us":119102,"med_us":187377,"p90_us":230392,"max_us":245721}]} +{"harness":"e63a8b27a0bcb261","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2100,"med_us":2437,"p90_us":2875,"max_us":3207},{"op":"render","fixture":"medium","min_us":82,"med_us":84,"p90_us":88,"max_us":89},{"op":"key-down","fixture":"medium","min_us":88,"med_us":95,"p90_us":102,"max_us":114},{"op":"key-right","fixture":"medium","min_us":84,"med_us":88,"p90_us":94,"max_us":105},{"op":"page-down","fixture":"medium","min_us":83,"med_us":86,"p90_us":88,"max_us":89},{"op":"wheel","fixture":"medium","min_us":82,"med_us":85,"p90_us":90,"max_us":99},{"op":"edit-char","fixture":"medium","min_us":1276,"med_us":1769,"p90_us":2239,"max_us":2754},{"op":"body-2m","fixture":"medium","min_us":5333,"med_us":9734,"p90_us":12257,"max_us":14666},{"op":"body-appends","fixture":"medium","min_us":135052,"med_us":262059,"p90_us":295829,"max_us":304576},{"op":"deep-sel","fixture":"medium","min_us":77,"med_us":79,"p90_us":83,"max_us":118}]} diff --git a/test/perf-baseline-tty-Debug.json b/test/perf-baseline-tty-Debug.json index ef42f0ad..6b5c0bd5 100644 --- a/test/perf-baseline-tty-Debug.json +++ b/test/perf-baseline-tty-Debug.json @@ -1 +1 @@ -{"harness":"f420fe5db60d6e97","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1743,"med_us":2011,"p90_us":2152,"max_us":2217},{"op":"render","fixture":"medium","min_us":76,"med_us":79,"p90_us":80,"max_us":84},{"op":"key-down","fixture":"medium","min_us":77,"med_us":78,"p90_us":85,"max_us":89},{"op":"key-right","fixture":"medium","min_us":77,"med_us":80,"p90_us":83,"max_us":95},{"op":"page-down","fixture":"medium","min_us":78,"med_us":78,"p90_us":87,"max_us":95},{"op":"wheel","fixture":"medium","min_us":76,"med_us":80,"p90_us":88,"max_us":90},{"op":"edit-char","fixture":"medium","min_us":1122,"med_us":1501,"p90_us":1812,"max_us":2440},{"op":"body-2m","fixture":"medium","min_us":4949,"med_us":8504,"p90_us":10909,"max_us":11452},{"op":"body-appends","fixture":"medium","min_us":115605,"med_us":190785,"p90_us":226244,"max_us":245258}]} +{"harness":"e63a8b27a0bcb261","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1830,"med_us":2222,"p90_us":2264,"max_us":2287},{"op":"render","fixture":"medium","min_us":78,"med_us":83,"p90_us":86,"max_us":94},{"op":"key-down","fixture":"medium","min_us":80,"med_us":84,"p90_us":89,"max_us":98},{"op":"key-right","fixture":"medium","min_us":78,"med_us":81,"p90_us":88,"max_us":96},{"op":"page-down","fixture":"medium","min_us":78,"med_us":82,"p90_us":89,"max_us":95},{"op":"wheel","fixture":"medium","min_us":77,"med_us":85,"p90_us":96,"max_us":109},{"op":"edit-char","fixture":"medium","min_us":1125,"med_us":1307,"p90_us":1558,"max_us":1584},{"op":"body-2m","fixture":"medium","min_us":5189,"med_us":9224,"p90_us":10859,"max_us":14741},{"op":"body-appends","fixture":"medium","min_us":108477,"med_us":198709,"p90_us":227756,"max_us":252672},{"op":"deep-sel","fixture":"medium","min_us":73,"med_us":77,"p90_us":80,"max_us":91}]} diff --git a/test/perf-baseline-tty-ReleaseFast.json b/test/perf-baseline-tty-ReleaseFast.json index 66421ba3..87a31754 100644 --- a/test/perf-baseline-tty-ReleaseFast.json +++ b/test/perf-baseline-tty-ReleaseFast.json @@ -1 +1 @@ -{"harness":"f420fe5db60d6e97","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1751,"med_us":2134,"p90_us":2183,"max_us":2415},{"op":"render","fixture":"medium","min_us":76,"med_us":77,"p90_us":91,"max_us":92},{"op":"key-down","fixture":"medium","min_us":77,"med_us":78,"p90_us":82,"max_us":83},{"op":"key-right","fixture":"medium","min_us":79,"med_us":85,"p90_us":100,"max_us":102},{"op":"page-down","fixture":"medium","min_us":78,"med_us":82,"p90_us":86,"max_us":95},{"op":"wheel","fixture":"medium","min_us":76,"med_us":79,"p90_us":83,"max_us":87},{"op":"edit-char","fixture":"medium","min_us":1063,"med_us":1290,"p90_us":1527,"max_us":1564},{"op":"body-2m","fixture":"medium","min_us":4950,"med_us":9414,"p90_us":10945,"max_us":13152},{"op":"body-appends","fixture":"medium","min_us":117839,"med_us":189253,"p90_us":232943,"max_us":247720}]} +{"harness":"e63a8b27a0bcb261","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2042,"med_us":2280,"p90_us":2451,"max_us":2478},{"op":"render","fixture":"medium","min_us":82,"med_us":84,"p90_us":87,"max_us":104},{"op":"key-down","fixture":"medium","min_us":83,"med_us":86,"p90_us":90,"max_us":93},{"op":"key-right","fixture":"medium","min_us":84,"med_us":87,"p90_us":91,"max_us":104},{"op":"page-down","fixture":"medium","min_us":84,"med_us":87,"p90_us":93,"max_us":96},{"op":"wheel","fixture":"medium","min_us":81,"med_us":85,"p90_us":89,"max_us":89},{"op":"edit-char","fixture":"medium","min_us":1309,"med_us":1613,"p90_us":1840,"max_us":2128},{"op":"body-2m","fixture":"medium","min_us":5386,"med_us":11064,"p90_us":11706,"max_us":12374},{"op":"body-appends","fixture":"medium","min_us":144772,"med_us":232307,"p90_us":273586,"max_us":281169},{"op":"deep-sel","fixture":"medium","min_us":79,"med_us":83,"p90_us":87,"max_us":130}]} diff --git a/test/perf.zig b/test/perf.zig index 95b55748..94076a25 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -53,6 +53,10 @@ const Op = enum { /// close, as a shell's `>>` loop makes: each costs its own bytes, not a /// pass over the whole body for its cursor, line index and saved hash. body_appends, + /// A render with the selection 2 MB into one line: only the columns + /// shown are measured, so it costs what a selection at the line's + /// start does (4.5 s a frame at 5 MB before). + deep_selection, fn label(o: Op) []const u8 { return switch (o) { @@ -65,6 +69,7 @@ const Op = enum { .edit_char => "edit-char", .body_write => "body-2m", .body_appends => "body-appends", + .deep_selection => "deep-sel", }; } }; @@ -83,6 +88,16 @@ fn bodyWrite(core: *pardes.Pardes, serial: u32) void { _ = core.serveFs(.{ .tag = 4, .op = .release, .node = body, .handle = h, .opened = true }); } +/// One line of 2 MB appended to the file, no newline in it. +fn longLine(core: *pardes.Pardes, serial: u32) void { + const Node = pardes.ctlfs.Node; + const body = Node.of(serial, .body); + @memset(&body_chunk, 'z'); + const h = core.serveFs(.{ .tag = 1, .op = .open, .node = body, .omode = 1 }).handle; + for (0..8) |_| _ = core.serveFs(.{ .tag = 2, .op = .write, .node = body, .handle = h, .data = &body_chunk }); + _ = core.serveFs(.{ .tag = 4, .op = .release, .node = body, .handle = h, .opened = true }); +} + const append_chunk_len = 8 * 1024; const append_count = 64; @@ -534,9 +549,16 @@ fn measure(op: Op, fx: Fixture, path: []const u8, expected_bytes: usize, reps: u core.update(.{ .key = .{ .cp = 'i', .text = "i" } }); pump(core); } + if (op == .deep_selection) { + longLine(core, pane.serial); + pump(core); + const len: u32 = @intCast(pane.file.?.content.len); + pardes.ctlfs.pane.setDot(pane, .{ .q0 = len - 10, .q1 = len - 5 }); + pump(core); + } for (0..warmup + reps) |n| { - seek(pane, fx, n); + if (op != .deep_selection) seek(pane, fx, n); _ = try frame(core); // settle the view at the new spot, untimed const before = .{ .row = pane.body.cur_row, .col = pane.body.cur_col, .scroll = pane.scroll(), .len = pane.file.?.content.len }; const rect = core.rects[id]; @@ -545,7 +567,7 @@ fn measure(op: Op, fx: Fixture, path: []const u8, expected_bytes: usize, reps: u const t0 = nowNs(); switch (op) { .open => unreachable, - .render => {}, + .render, .deep_selection => {}, .key_down => core.update(.{ .key = .{ .cp = 'j', .text = "j" } }), .key_right => core.update(.{ .key = .{ .cp = 'l', .text = "l" } }), .page_down => core.update(.{ .key = .{ .cp = pardes.Key.page_down } }), @@ -561,7 +583,7 @@ fn measure(op: Op, fx: Fixture, path: []const u8, expected_bytes: usize, reps: u .open => unreachable, .body_write => if (pane.file.?.content.len != before.len + 8 * body_chunk.len) return error.BodyWriteWasNotAppended, .body_appends => if (pane.file.?.content.len != before.len + append_count * append_chunk_len) return error.BodyAppendsWereNotAppended, - .render => if (pane.body.cur_row != before.row or pane.body.cur_col != before.col or pane.file.?.content.len != before.len) + .render, .deep_selection => if (pane.body.cur_row != before.row or pane.body.cur_col != before.col or pane.file.?.content.len != before.len) return error.RenderChangedDocument, .key_down => if (pane.body.cur_row != before.row + 1) return error.DownDidNotMove, .key_right => if (pane.body.cur_row != before.row or pane.body.cur_col != before.col + 1) return error.RightDidNotMove, -- cgit v1.3 From f02c10bfa6d02d305ddb6d7a28b12c40035274c7 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Wed, 30 Sep 2026 21:16:32 -0300 Subject: A Restore brings back clean a pane whose file was never on disk, such as Config's new init; only a file that existed when dumped is said deleted A restored pane whose path was not on disk was marked deleted on disk, so Config's not-yet-written init came back dirty and asked before Del, Exit or Restore. The dump now records whether the file was on disk (older dumps read as yes), and only one that was and is gone is said deleted. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 31 +++++++++++++++++++++++++++++-- src/dump.zig | 4 ++++ src/ninep/ctl.zig | 10 +++++++++- 3 files changed, 42 insertions(+), 3 deletions(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index a89db613..d16d4fc0 100644 --- a/src/File.zig +++ b/src/File.zig @@ -127,6 +127,7 @@ pub fn dumpPane( .content = file.content, .content_b64 = try dump.encodeBytes(arena, file.content), .dirty = file.revision != file.saved_revision, + .on_disk = onDisk(file.path), .origin = origin, .origin_arg = origin_arg, .mini_source = if (file.mini) |mini| mini.source else "", @@ -220,6 +221,24 @@ fn restoreLocationRows(gpa: std.mem.Allocator, content: []const u8, saved: []con return rows; } +test "a clean pane whose file was never on disk comes back clean from a Restore; one whose file has gone is said deleted" { + if (comptime !pardes.hosted) return; + for ([_]bool{ false, true }) |was_on_disk| { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const id = p.freeSlot().?; + const pane = try restore(p, id, .{ + .kind = .file, + .tag = "", + .body = "", + .file = .{ .path = "/tmp/pardes-never-written/init", .content = "", .on_disk = was_on_disk }, + }); + try std.testing.expectEqual(was_on_disk, pane.file.?.disk_gone); + try std.testing.expectEqual(pane.file.?.saved_revision, pane.file.?.revision); + } +} + test "location metadata restore rejects offsets and invalid syntax bytes" { const gpa = std.testing.allocator; var row: dump.LocationRow = .{ @@ -898,11 +917,19 @@ pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { // Its file gone from disk since the dump: its text is nowhere else now, // so it comes back as one deleted on disk, dirty, and Del, Exit and // Restore ask before throwing it away. - if (comptime pardes.hosted) if (output == null) if (filesystem.localPath(path)) |local| - if (@import("exec.zig").kindOf(local) == null) deleted(p, @intCast(id)); + // One never on disk (Config's new file, a name not yet saved) is + // restored as it was: clean, and nothing deleted. + if (output == null and saved.on_disk and !onDisk(path)) deleted(p, @intCast(id)); return pane; } +/// Whether `path` names a file on this host's disk now. +fn onDisk(path: []const u8) bool { + if (comptime !pardes.hosted) return false; + const local = filesystem.localPath(path) orelse return false; + return @import("exec.zig").kindOf(local) != null; +} + pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { if (file.output == null) for (p.panes, 0..) |slot, id| { if (slot == pane) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); diff --git a/src/dump.zig b/src/dump.zig index 4194f628..983d5894 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -209,6 +209,10 @@ pub const File = struct { content: []const u8 = "", content_b64: []const u8 = "", dirty: bool = false, + /// Its file was on disk when dumped: one gone by the Restore is said + /// deleted, one never written (Config's new file) is not. True in + /// older dumps. + on_disk: bool = true, tree_context: bool = false, location_rows: []const LocationRow = &.{}, // Builtin names remain stable when enum ordinals change. diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index a14b1efb..63f89cdf 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -2691,8 +2691,16 @@ test "a restored pane whose file is gone from disk comes back dirty, and Del ask if (comptime !pardes.hosted) return error.SkipZigTest; const p = try withFile(testing.allocator, "kept text\n"); defer p.deinit(); - try pane_files.nameBuffer(p, 0, "/tmp/pardes-restore-gone-xyz/f.txt", false); + // On disk when dumped, gone by the Restore. + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "f.txt", .data = "kept text\n" }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; + var path_buf: [4200]u8 = undefined; + try pane_files.nameBuffer(p, 0, try std.fmt.bufPrint(&path_buf, "{s}/f.txt", .{dir}), false); try pardes.dump.dumpState(p); + try tmp.dir.deleteFile(testing.io, "f.txt"); const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); defer restored.deinit(); const again = restored.panes[restored.paneBySerial(restored.panes[0].?.serial).?].?; -- cgit v1.3 From e6ff64843b4a8986e9740c576f346690217cf5a7 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 01:14:37 -0300 Subject: A +Pager pane whose text is a diff is drawn and looked at as a diff, as a diff command pane is: git diff, show and log -p page into review With git paging into +Pager, a diff arrived as plain text: no colour for its sides and a right click on a hunk line searched the word. A +Pager pane now notes, as its text is set, whether its first 64 KiB holds a diff header or a unified hunk, and such a pane takes the diff highlighting and the diff look every diff pane has. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 33 +++++++++++++++++++++++++++++++++ src/panes.zig | 2 +- src/pardes.zig | 1 + 3 files changed, 35 insertions(+), 1 deletion(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index d16d4fc0..c738ee58 100644 --- a/src/File.zig +++ b/src/File.zig @@ -72,6 +72,9 @@ pub const State = struct { /// Its file was deleted on disk: said once (`deleted`) until it is /// written or found again. disk_gone: bool = false, + /// A +Pager pane (`pardes -`) whose text is a diff (`git diff`, `show`, + /// `log -p`): drawn and looked at as a diff (Pane.colorAlgo). + pager_diff: bool = false, /// Seconds of the last content change, for the filesystem's stat; zero until edited. mtime: u32 = 0, /// Non-null for a generated output buffer rather than an on-disk file. @@ -998,6 +1001,36 @@ pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span: ?Span) void { f.highlights = &.{}; f.highlight_start = 0; f.syntax_dirty = true; + if (std.mem.endsWith(u8, f.path, "/+Pager")) f.pager_diff = looksLikeDiff(new[0..@min(new.len, 64 * 1024)]); +} + +/// Whether `head`, a text's first bytes, holds a diff: a `diff` header, or +/// a unified hunk's `---`, `+++` and `@@` lines. +pub fn looksLikeDiff(head: []const u8) bool { + if (std.mem.startsWith(u8, head, "diff ") or std.mem.indexOf(u8, head, "\ndiff ") != null) return true; + const minus = std.mem.indexOf(u8, head, "--- ") orelse return false; + const plus = std.mem.indexOfPos(u8, head, minus, "\n+++ ") orelse return false; + return std.mem.indexOfPos(u8, head, plus, "\n@@ ") != null; +} + +test "a +Pager pane holding a diff is drawn and looked at as one; holding other text, as text" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile(""); + const f = &pane.file.?; + p.gpa.free(f.path); + f.path = try p.gpa.dupe(u8, "/tmp/+Pager"); + setContent(p, f, try p.gpa.dupe(u8, "commit abc\n\ndiff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b\n")); + try std.testing.expect(pane.colorAlgo() == .diff); + try std.testing.expect(pardes.look.diffLines(p, pane) != null); + setContent(p, f, try p.gpa.dupe(u8, "commit abc\n\n a plain log\n")); + try std.testing.expect(pane.colorAlgo() != .diff); +} + +test "a pager's text is a diff when it holds a diff header or a unified hunk" { + try std.testing.expect(looksLikeDiff("commit abc\nAuthor: x\n\n msg\n\ndiff --git a/f b/f\n")); + try std.testing.expect(looksLikeDiff("--- a/f\n+++ b/f\n@@ -1 +1 @@\n-a\n+b\n")); + try std.testing.expect(!looksLikeDiff("commit abc\nAuthor: x\n\n plain log\n")); } pub fn restoreSnap(pane: *Pane, f: *State, snap: Snapshot) void { diff --git a/src/panes.zig b/src/panes.zig index a395d6ed..9d1b7571 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -448,7 +448,7 @@ pub const Pane = struct { if (pane.isTerminal()) return .tty; if (pane.file) |f| { if (f.mini != null) return .source; - if (std.mem.endsWith(u8, f.path, ".diff") or std.mem.endsWith(u8, f.path, ".patch")) return .diff; + if (std.mem.endsWith(u8, f.path, ".diff") or std.mem.endsWith(u8, f.path, ".patch") or f.pager_diff) return .diff; if (f.output != null) { const tr = Output.fileTraits(f.output); if (tr.locations) return .locations; diff --git a/src/pardes.zig b/src/pardes.zig index 84b891e5..5d0ab7e8 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -4640,6 +4640,7 @@ pub const Pardes = struct { const named = try std.fs.path.join(gpa, &.{ dir, "+Pager" }); gpa.free(shown.file.?.path); shown.file.?.path = named; + shown.file.?.pager_diff = panes.File.looksLikeDiff(content[0..@min(content.len, 64 * 1024)]); p.oneColumn(); }, .embedded => { -- cgit v1.3 From 6c82d06cd2a15d724b8e82e1128fa15dc9e35d05 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 07:56:48 -0300 Subject: Restore reads a clean file from disk, and an unsaved one whose file changed since the Dump is said changed, its first Save asking before overwriting it A Restore put back the dump's copy of every file pane and armed the watch with the disk as it now was, so a file changed on disk after the Dump came back as its old text, marked clean, and the next Save wrote the old text over the new without a word. A clean file pane's text is now not in the dump: Restore reads its file (an older dump's copy is read past too, and used only when the file is gone). An unsaved pane keeps its text once, base64, the plain copy beside it dropped, with the hash of the file it was read against (`disk_hash`); a Restore that finds another there says the file changed on disk, and Save asks once before overwriting it, as for a change seen while it was open. file_watch.zig's own tests were never collected (no test root imported it): main.zig's test block does now, and the restored watch test says what a clean restore now reads. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 40 +++++++++++++++++++++++++++++++++++----- src/dump.zig | 8 ++++++++ src/file_watch.zig | 11 +++++++---- src/main.zig | 2 ++ src/ninep/ctl.zig | 40 ++++++++++++++++++++++++++++++++++++++++ test/fs_namespace.zig | 3 ++- 6 files changed, 94 insertions(+), 10 deletions(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index c738ee58..d41007c3 100644 --- a/src/File.zig +++ b/src/File.zig @@ -105,6 +105,7 @@ pub const State = struct { pub const NodeStep = struct { ranges: []modal.Selection, primary: usize }; pub fn dumpPane( + p: *Pardes, arena: std.mem.Allocator, pane: *const Pane, file: *const State, @@ -114,6 +115,18 @@ pub fn dumpPane( origin: []const u8, origin_arg: []const u8, ) !dump.Pane { + const dirty = file.revision != file.saved_revision; + const on_disk = onDisk(file.path); + // A clean file's text is its file's: read from disk when restored, so + // a change made there since is what comes back. Any other is kept, once. + const from_disk = file.output == null and !dirty and on_disk; + // What an unsaved pane's text was read against: the disk as it is, or, + // when a change there was seen already, something it is not. + const disk_hash: ?u64 = if (file.output != null or !dirty or !on_disk) null else if (file.disk_newer) |newer| newer +% 1 else blk: { + const bytes = filesystem.read(p, file.path) catch break :blk null; + defer p.gpa.free(bytes); + break :blk std.hash.Wyhash.hash(0, bytes); + }; return .{ .kind = .file, .tag = tag, @@ -127,10 +140,10 @@ pub fn dumpPane( .tree_context = file.tree_context, .location_rows = try dumpLocationRows(arena, file.location_rows), .path = file.path, - .content = file.content, - .content_b64 = try dump.encodeBytes(arena, file.content), - .dirty = file.revision != file.saved_revision, - .on_disk = onDisk(file.path), + .content_b64 = if (from_disk) "" else try dump.encodeBytes(arena, file.content), + .dirty = dirty, + .disk_hash = disk_hash, + .on_disk = on_disk, .origin = origin, .origin_arg = origin_arg, .mini_source = if (file.mini) |mini| mini.source else "", @@ -855,7 +868,16 @@ pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { saved.content_b64.len > encoded_limit or saved.mini_colors_b64.len > encoded_limit) return error.InvalidMini; } - const content: []u8 = if (saved.content_b64.len > 0) + // A clean file's text is read from its file: one changed on disk since + // the dump comes back changed, never as the old text marked clean (and + // a dump from before, which kept it, is read so too). Gone from disk, the + // dump's text if it kept one. + const from_disk: ?[]u8 = if (Output.fromWord(saved.origin) == null and !saved.dirty and saved.on_disk and + saved.mini_source.len == 0 and filesystem.localPath(saved.path) != null) + filesystem.read(p, saved.path) catch null + else + null; + const content: []u8 = if (from_disk) |bytes| bytes else if (saved.content_b64.len > 0) try dump.decodeBytes(p.gpa, saved.content_b64) else try p.gpa.dupe(u8, saved.content); @@ -923,6 +945,14 @@ pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { // One never on disk (Config's new file, a name not yet saved) is // restored as it was: clean, and nothing deleted. if (output == null and saved.on_disk and !onDisk(path)) deleted(p, @intCast(id)); + // Unsaved, and its file changed on disk since the text was read: said, + // and its first Save asks before overwriting the newer file. + if (saved.disk_hash) |read_against| if (output == null and onDisk(path)) { + if (filesystem.read(p, path)) |bytes| { + defer p.gpa.free(bytes); + if (std.hash.Wyhash.hash(0, bytes) != read_against) changed(p, @intCast(id), bytes); + } else |_| {} + }; return pane; } diff --git a/src/dump.zig b/src/dump.zig index ca3751f2..1420ea8f 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -208,9 +208,16 @@ pub const LocationRow = struct { pub const File = struct { path: []const u8 = "", + /// The text, in older dumps plain and base64 both; now base64 alone, + /// and only for a pane whose text is not its file's on disk (unsaved, + /// an output, a file never written): a clean file's is read from disk. content: []const u8 = "", content_b64: []const u8 = "", dirty: bool = false, + /// An unsaved pane's: the hash of the file on disk its text was read + /// against. A Restore that finds another there says it changed, and + /// Save asks before overwriting it. + disk_hash: ?u64 = null, /// Its file was on disk when dumped: one gone by the Restore is said /// deleted, one never written (Config's new file) is not. True in /// older dumps. @@ -728,6 +735,7 @@ pub fn dumpState(p: *Pardes) !void { const body = try body_layer.bodyText(p, arena, pane); const scroll: usize = @intCast(@max(0, pane.scroll())); var dp: Pane = if (pane.file) |*f| try pardes.panes.File.dumpPane( + p, arena, pane, f, diff --git a/src/file_watch.zig b/src/file_watch.zig index 6c746e74..46764a73 100644 --- a/src/file_watch.zig +++ b/src/file_watch.zig @@ -687,11 +687,14 @@ test "restored file watches preserve snapshots and accept later disk changes" { else => {}, }; try std.testing.expect(armed and watches[id] != null); - try std.testing.expectEqualStrings("restored snapshot\n", pane.file.?.content); + // A clean pane's text is its file's, read at the Restore: a dump + // that kept other text (an older dump) is not what comes back. + const restored: []const u8 = if (case.dirty) "restored snapshot\n" else "disk baseline\n"; + try std.testing.expectEqualStrings(restored, pane.file.?.content); try std.testing.expectEqual(@as(usize, 0), pane.file.?.history.undo_len); try std.testing.expectEqual(case.dirty, pane.file.?.revision != pane.file.?.saved_revision); _ = reloadChanged(core, io, gpa, &watches); - try std.testing.expectEqualStrings("restored snapshot\n", pane.file.?.content); + try std.testing.expectEqualStrings(restored, pane.file.?.content); try tmp.dir.writeFile(io, .{ .sub_path = "watched", .data = "later disk save\n" }); _ = reloadChanged(core, io, gpa, &watches); @@ -704,9 +707,9 @@ test "restored file watches preserve snapshots and accept later disk changes" { } try std.testing.expectEqualStrings("later disk save\n", pane.file.?.content); pardes.panes.File.undo(core, pane); - try std.testing.expectEqualStrings("restored snapshot\n", pane.file.?.content); + try std.testing.expectEqualStrings(restored, pane.file.?.content); _ = reloadChanged(core, io, gpa, &watches); - try std.testing.expectEqualStrings("restored snapshot\n", pane.file.?.content); + try std.testing.expectEqualStrings(restored, pane.file.?.content); } } diff --git a/src/main.zig b/src/main.zig index 08ead756..5dd6a8e6 100644 --- a/src/main.zig +++ b/src/main.zig @@ -822,6 +822,8 @@ test { _ = @import("host_io.zig"); _ = @import("host_io.zig").Shell; _ = @import("host_io.zig").Lsp; + // Its tests too: imported by the hosts only, it was never collected. + _ = @import("file_watch.zig"); _ = @import("lsp/lsp_client.zig"); _ = @import("lsp/lsp.zig"); if (comptime pardes.platform == .tty) { diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index f4aff960..1a2dbdbc 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -4213,3 +4213,43 @@ test "Petscii, Palette and Ascii take the state their tag word names, set rather _ = wr(p, ctl_node, "Petscii maybe\n"); try testing.expect(th.logHas(p, "Petscii takes on or off")); } + +test "a Restore reads a clean file from disk; an unsaved one whose file changed since is said so, and its first Save asks" { + if (comptime !pardes.hosted) return; + const gpa = testing.allocator; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.txt", .data = "one\n" }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; + var path_buf: [4200]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "{s}/a.txt", .{dir}); + const p = try Pardes.init(gpa, .{ .file = path, .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + // Clean: the dump keeps no text, and the newer disk is what comes back. + try pardes.dump.dumpState(p); + try testing.expect(std.mem.indexOf(u8, p.dump_out.?, "b25lCg==") == null); // "one\n" in base64 + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.txt", .data = "two\n" }); + { + const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); + defer restored.deinit(); + const f = pane_files.fileOf(restored.panes[0].?).?; + try testing.expectEqualStrings("two\n", f.content); + try testing.expectEqual(f.saved_revision, f.revision); + } + // Unsaved: its text comes back, the disk changed under it is said, and + // Save asks once before overwriting it. + const f = pane_files.fileOf(p.panes[0].?).?; + const edited = try gpa.dupe(u8, "edited\n"); + pardes.panes.File.setContent(p, f, edited); + try testing.expect(f.revision != f.saved_revision); + try pardes.dump.dumpState(p); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.txt", .data = "three\n" }); + const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); + defer restored.deinit(); + const rf = pane_files.fileOf(restored.panes[0].?).?; + try testing.expectEqualStrings("edited\n", rf.content); + try testing.expect(rf.disk_newer != null); + pardes.exec.saveFile(restored, 0); + try testing.expect(th.logHas(restored, "modified on disk since read (Save again to overwrite)")); +} diff --git a/test/fs_namespace.zig b/test/fs_namespace.zig index bd620c2d..5bce9eda 100644 --- a/test/fs_namespace.zig +++ b/test/fs_namespace.zig @@ -206,7 +206,8 @@ test "explicit OS file opens and restores keep their names and request watches" .kind = .file, .tag = path, .body = "", - .file = .{ .path = path, .content = "const unsaved = 2;\n" }, + // Unsaved text: kept (a clean pane's is read from disk). + .file = .{ .path = path, .content = "const unsaved = 2;\n", .dirty = true }, }); try std.testing.expectEqualStrings(path, copy.file.?.path); try std.testing.expectEqualStrings("const unsaved = 2;\n", copy.file.?.content); -- cgit v1.3 From 9b641cbe3dc6c226be158e5051afafb9eb86c122 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 10:02:59 -0300 Subject: An unsaved pane restored from a dump that says nothing of its disk (no disk_hash, an older dump) asks at its first Save, as for a file changed on disk What its text was read against is unknown, so a Save could write over a newer file without a word; it now asks once first. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 10 ++++++++++ src/ninep/ctl.zig | 19 +++++++++++++++++++ 2 files changed, 29 insertions(+) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index d41007c3..4fac0073 100644 --- a/src/File.zig +++ b/src/File.zig @@ -953,6 +953,16 @@ pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { if (std.hash.Wyhash.hash(0, bytes) != read_against) changed(p, @intCast(id), bytes); } else |_| {} }; + // An older dump says nothing of what the text was read against: its + // first Save asks, as for a file changed on disk, rather than guess. + if (saved.dirty and saved.disk_hash == null and output == null and onDisk(path)) { + if (filesystem.read(p, path)) |bytes| { + defer p.gpa.free(bytes); + const f = &pane.file.?; + f.disk_newer = std.hash.Wyhash.hash(0, bytes); + f.disk_newer_warned = false; + } else |_| {} + } return pane; } diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 16fbabb4..554333bb 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -4409,3 +4409,22 @@ test "a command or a terminal refused for room is refused before anything is log p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); } } + +test "an unsaved pane from a dump that says nothing of its disk asks at its first Save" { + if (comptime !pardes.hosted) return; + const gpa = testing.allocator; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "old.txt", .data = "disk\n" }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; + var path_buf: [4200]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "{s}/old.txt", .{dir}); + const p = try withFile(gpa, "x\n"); + defer p.deinit(); + const id = p.freeSlot().?; + const pane = try pardes.panes.File.restore(p, id, .{ .kind = .file, .tag = "", .body = "", .file = .{ .path = path, .content = "unsaved\n", .dirty = true } }); + try testing.expect(pane.file.?.disk_newer != null); + pardes.exec.saveFile(p, id); + try testing.expect(th.logHas(p, "modified on disk since read (Save again to overwrite)")); +} -- cgit v1.3 From edad6d960dc0fc1165cbb3b801e0538045b2247f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 10:09:54 -0300 Subject: A +Pager keeps its program's colours: the session parses what /pager is written after its directory with ghostty-vt, SGR becomes spans drawn over the plain text, every other escape is dropped, and PagerColor off pages it plain --- src/9p_io.zig | 28 ++- src/File.zig | 40 ++++- src/config.zig | 8 +- src/fs.zig | 7 + src/main.zig | 129 +++----------- src/ninep/ctl.zig | 103 +++++++++-- src/ninep/tree.zig | 58 +++++- src/pager.zig | 373 +++++++++++++++++++++++++++++++++++++++ src/pardes.zig | 12 +- test/fs.py | 20 +++ test/selfmount.py | 14 ++ test/snapshots/pagercolor.golden | 120 +++++++++++++ test/snapshots/pagercolor.snap | 24 +++ 13 files changed, 806 insertions(+), 130 deletions(-) create mode 100644 src/pager.zig create mode 100644 test/snapshots/pagercolor.golden create mode 100644 test/snapshots/pagercolor.snap (limited to 'src/File.zig') diff --git a/src/9p_io.zig b/src/9p_io.zig index 9a38b438..57df0c5f 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -266,6 +266,7 @@ pub const Listener = struct { const restores = pardes.turn.restores; // Asked first: a release that runs a held line has none after. const changes = pardes.ctlfs.changesPane(core, req); + const fills = pardes.ctlfs.holdsPage(core, req); const reply = core.serveFs(req); if (req.op == .release and quiet) l.collectOs(); // A read with nothing yet stays parked in the engine, and the core @@ -299,6 +300,13 @@ pub const Listener = struct { // file written. A change carries no payload, so the reply is still // whole after the wait. l.kick(); + // A read that put a /pager open's text in (ctl.fillPager), or a + // close that handed it to the editor's step, waits on nothing the + // editor performs: its answer goes now, while the turn still keeps + // a read's payload whole. Waiting would hang a close through a + // mount: 9ns answers nothing else on it while a clunk is out, and + // the editor's step may be out opening a file through that mount. + if (fills) return conn.reply(&reply, core.fsPayload(reply)); // A refusal answers at once: its text may be in the core's one // buffer for it, which a request run while this one waited would // write over. @@ -2341,10 +2349,12 @@ pub const Client = struct { gpa.destroy(s); } - /// Writes `request` to `path` and reads the answer on the same open, - /// as /pane/new answers its own open: a session's last answer, from - /// another client, can never be what comes back. `exec 3<>file`. - pub fn ask(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, request: []const u8) ![]u8 { + /// Writes `request`, then `more`, to `path` and reads the answer on the + /// same open, as /pane/new answers its own open: a session's last + /// answer, from another client, can never be what comes back. `exec + /// 3<>file`. `more` (`pardes -`'s text after its /pager line) goes in + /// Twrites at rising offsets, each answer giving the next its budget. + pub fn ask(gpa: std.mem.Allocator, dial: []const u8, path: []const u8, request: []const u8, more: []const u8) ![]u8 { if (comptime !supported) return error.Unsupported; var names: [max_depth][]const u8 = undefined; const n = try elements(path, &names); @@ -2356,7 +2366,15 @@ pub const Client = struct { defer endSession(gpa, s); const fid = (try walkTo(s, names[0..n], &remote)).fid; _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); - _ = try s.ask(.{ .write = .{ .fid = fid, .offset = 0, .data = request } }, &remote); + var written: usize = 0; + while (written < request.len + more.len) { + const from = if (written < request.len) request[written..] else more[written - request.len ..]; + const chunk = from[0..@min(from.len, s.cl.maxWrite())]; + const count = (try s.ask(.{ .write = .{ .fid = fid, .offset = written, .data = chunk } }, &remote)).write; + if (count == 0 or count > chunk.len) return Error.Botch; + written += count; + s.deadline = nowMs() +| write_budget_ms; + } var out: std.ArrayList(u8) = .empty; errdefer out.deinit(gpa); while (true) { diff --git a/src/File.zig b/src/File.zig index 4fac0073..b3c28290 100644 --- a/src/File.zig +++ b/src/File.zig @@ -75,6 +75,11 @@ pub const State = struct { /// A +Pager pane (`pardes -`) whose text is a diff (`git diff`, `show`, /// `log -p`): drawn and looked at as a diff (Pane.colorAlgo). pager_diff: bool = false, + /// A +Pager's colours, as its program printed them (pager.zig): drawn + /// over its text by recolorSyntax, never read over 9P. ponytail: any + /// edit drops them (setContentSpan); shifting them through the splice, + /// as pane.zig's shiftOne moves dot, would keep them. + pager_spans: []pardes.pager.Span = &.{}, /// Seconds of the last content change, for the filesystem's stat; zero until edited. mtime: u32 = 0, /// Non-null for a generated output buffer rather than an on-disk file. @@ -982,6 +987,7 @@ pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { if (file.mini) |*mini| mini.deinit(p.gpa); if (file.line_starts.len > 0) p.gpa.free(file.line_starts); if (file.highlights.len > 0) p.tree_sitter_gpa.free(file.highlights); + p.gpa.free(file.pager_spans); locations.freeRows(p.gpa, file.location_rows); if (file.context_declarations.len > 0) p.tree_sitter_gpa.free(file.context_declarations); if (file.node_tree) |tree| syntax.freeTree(tree); @@ -1010,6 +1016,8 @@ pub fn setContent(p: *Pardes, f: *State, new: []u8) void { pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span: ?Span) void { locations.freeRows(p.gpa, f.location_rows); f.location_rows = &.{}; + p.gpa.free(f.pager_spans); + f.pager_spans = &.{}; for (p.panes) |slot| if (slot) |pane| { if (pane.file) |*file| if (file == f) { for (0..pane.sel.len) |button| { @@ -1483,7 +1491,8 @@ fn synStyle(p: *Pardes, sy: syntax.Syn) ?SynStyle { pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void { const highlights = if (f.mini) |mini| mini.colors else f.highlights; const highlight_start = if (f.mini != null) 0 else f.highlight_start; - if (highlights.len == 0 and f.output == null) return; + const spans = f.pager_spans; + if (highlights.len == 0 and f.output == null and spans.len == 0) return; const prefix_width = gutterWidth(pane); const tz_recolor = tracy.zone(@src(), "synRecolor"); defer tz_recolor.end(); @@ -1526,6 +1535,14 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. else null else null; if (tint) |t| if (prefix_width < tw) tintRow(s, tx + @as(u16, @intCast(prefix_width)), body_y + vr, tx + tw, t.bg); + // A +Pager's own colours (pager.zig) on every row but one the diff + // look tints: an added or removed line is drawn as pardes draws a + // diff, and git's red and green on it would only fight the tint. + var span_at = if (tint != null) spans.len else std.sort.partitionPoint(pardes.pager.Span, spans, base + hs, struct { + fn before(at: usize, span: pardes.pager.Span) bool { + return span.end <= at; + } + }.before); var c: usize = 0; var screen_c: usize = 0; while (hs + c < limit and prefix_width + screen_c < tw) { @@ -1562,6 +1579,27 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. if (style.bg != .default) cell.style.bg = style.bg; } } + while (span_at < spans.len and spans[span_at].end <= idx) span_at += 1; + if (span_at < spans.len and spans[span_at].start <= idx) { + const st = spans[span_at].style; + var fill: usize = 0; + while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) { + const cell = s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr); + if (cell.default) continue; + // A palette colour through the theme's sixteen, as a + // terminal pane's cell; truecolor as it is. + if (st.fg != .default) cell.style.fg = if (st.fg == .index) terminal.palColor(p, st.fg.index) else st.fg; + if (st.bg != .default) cell.style.bg = if (st.bg == .index) terminal.palColor(p, st.bg.index) else st.bg; + cell.style.bold = cell.style.bold or st.bold; + cell.style.dim = st.dim; + cell.style.italic = st.italic; + cell.style.blink = st.blink; + cell.style.reverse = st.reverse; + cell.style.invisible = st.invisible; + cell.style.strikethrough = st.strikethrough; + if (st.ul != .off) cell.style.ul = st.ul; + } + } screen_c += cells; c = grapheme_end - hs; } diff --git a/src/config.zig b/src/config.zig index 7559d481..86baa9fe 100644 --- a/src/config.zig +++ b/src/config.zig @@ -82,6 +82,7 @@ pub const leader_path = paths: { .BootShell = null, .LookWord = null, .Pager = null, + .PagerColor = null, .TermImages = null, .Debug = "td", .Msg = null, @@ -762,6 +763,9 @@ pub const Runtime = struct { /// PAGER and GIT_PAGER set to `pardes -`, a +Pager pane, where the /// user's environment set neither; `off`, the environment as it is. pager: Pager = .pardes, + /// A +Pager keeps its program's colours (SGR, as spans over the text, + /// pager.zig), or is plain; for the next text paged. + pager_color: bool = true, /// How a new terminal pane draws the kitty graphics its program sends /// (yazi's previews): `real`, as pixels where the shell can, or /// `petscii`, as glyph art. The Petscii builtin flips one pane. @@ -939,7 +943,7 @@ pub const Runtime = struct { /// The message timings a setting word sets, each in milliseconds. pub const MessageTime = enum { linger, fall, dissolve }; - pub const Toggle = enum { colors, wrap, tree_context_tag_style, tag_bottom, debug, focus_tint, syntax_bold, verbose, message_animation, ligatures, cursor_blink, selection_glow, hover_glow, occlusion, parallax, jump_trail, chip_shadow, thumb_flash }; + pub const Toggle = enum { colors, wrap, tree_context_tag_style, tag_bottom, debug, focus_tint, syntax_bold, pager_color, verbose, message_animation, ligatures, cursor_blink, selection_glow, hover_glow, occlusion, parallax, jump_trail, chip_shadow, thumb_flash }; /// A bundled post pass, a Shadertoy file in shaders/post/: the CRT, and /// G4's bloom, vignette and grain (docs/effects.md). pub const Scene = enum { crt, bloom, vignette, grain }; @@ -1040,6 +1044,7 @@ pub const Runtime = struct { .{ .word = "BootShell", .action = .{ .choice = .boot_shell }, .doc = "A document dropped where a lone untouched shell stands: keep the shell, or replace it." }, .{ .word = "LookWord", .action = .{ .choice = .look_word }, .doc = "A plain word looked at: search selects its next place in the pane, list lists every place in a +Search." }, .{ .word = "Pager", .action = .{ .choice = .pager }, .doc = "What a terminal's commands page through: pardes, a +Pager pane (pardes -), or off, the environment's own; for terminals started after it." }, + .{ .word = "PagerColor", .action = .{ .toggle = .pager_color }, .doc = "A +Pager keeps its program's colours, on or off; for the next text paged." }, .{ .word = "TermImages", .action = .{ .choice = .term_images }, .doc = "How a new terminal draws its program's kitty graphics: real, as pixels where it can, or petscii, as glyph art." }, }; @@ -1748,6 +1753,7 @@ pub const Runtime = struct { .debug => "Debug on\n", .focus_tint => "FocusTint off\n", .syntax_bold => "SyntaxBold on\n", + .pager_color => "PagerColor off\n", .verbose => "Verbose off\n", .message_animation => "MessageAnimation off\n", .ligatures => "Ligatures off\n", diff --git a/src/fs.zig b/src/fs.zig index 9eb3fd0f..4a243b10 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1631,6 +1631,11 @@ pub const Namespace = struct { /// append to `body`, an insert at `data`'s address), held and put in /// as one edit when anything else comes (ninep/pane.zig flushBatch): a /// 10 MB write in 8 KB pieces is one copy and one undo step, not 1280. + /// The text of /pager opens closed before a read put it in, each with + /// its +Pager's serial, for the editor's step to put in (ctl.fillPager): + /// a close through a mount may not wait for the editor to be quiet, + /// as 9ns answers nothing else on that mount while a clunk is out. + pages: std.ArrayList(struct { serial: u32, bytes: std.ArrayList(u8) }) = .empty, batch: struct { serial: u32 = 0, node: u64 = 0, @@ -1678,6 +1683,8 @@ pub const Namespace = struct { for (st.os_paths.items) |entry| gpa.free(entry.path); st.os_paths.deinit(gpa); for (&st.opens) |*o| o.deinit(gpa); + for (st.pages.items) |*page| page.bytes.deinit(gpa); + st.pages.deinit(gpa); st.log.deinit(gpa); st.out.deinit(gpa); } diff --git a/src/main.zig b/src/main.zig index e998accc..6d895307 100644 --- a/src/main.zig +++ b/src/main.zig @@ -50,9 +50,10 @@ const help_text = \\ \\With no arguments the shell pane starts in tty mode. A FILE argument \\(optionally file:LINE) opens it alone, filling the window; a DIRECTORY - \\argument becomes the cwd shells spawn in. `-` reads stdin, its terminal - \\escapes stripped, into a +Pager pane: inside a pardes pane the outer - \\session's, returning at once (a terminal's PAGER), else a new editor's. + \\argument becomes the cwd shells spawn in. `-` reads stdin into a +Pager + \\pane, its colours kept (PagerColor) and every other escape dropped: + \\inside a pardes pane the outer session's, returning at once (a + \\terminal's PAGER), else a new editor's. \\ \\Options: \\ --tty start as one shell pane already in tty mode @@ -100,11 +101,12 @@ const help_text = \\ ; -/// `pardes -` inside a session: `text` into the directory's one +Pager -/// (/pager, refilled when it is there), written into its -/// body through one open, as one undo step, and left clean. A text -/// the session would not take is never lost: it goes to stderr, with why, -/// and the exit is 1. +/// `pardes -` inside a session: `text`, stdin as it came, escapes and all, +/// into the directory's one +Pager (/pager, refilled when it is there): +/// written after the directory on that one open, the session parses it +/// (pager.zig) and puts it in as one undo step, left clean. A text the +/// session would not take is never lost: it goes to stderr, a terminal, +/// with why, and the exit is 1. fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const u8) void { const Fail = struct { fn with(o: std.Io, t: []const u8, what: []const u8, err: anyerror) noreturn { @@ -128,22 +130,16 @@ fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const } else !pardes.filesystem.deniedAbove(cwd); var line_buf: [4200]u8 = undefined; const dir_line = std.fmt.bufPrint(&line_buf, "{s}\n", .{if (plain) cwd else ""}) catch "\n"; - // Its serial read back on the open that asked: another client's exec - // meanwhile can never send this text into that client's pane. - const answer = ninep_io.Client.ask(gpa, dial, "/pager", dir_line) catch |err| Fail.with(io, text, "no +Pager pane", err); - const serial = std.fmt.parseInt(u32, std.mem.trim(u8, answer, " \n"), 10) catch |err| Fail.with(io, text, "no +Pager pane", err); - // The whole text through one open of the body (truncated once, then - // written at rising offsets): one undo step, and every byte of it. - var body_buf: [64]u8 = undefined; - const body = std.fmt.bufPrint(&body_buf, "/pane/{d}/body", .{serial}) catch unreachable; - ninep_io.Client.write(gpa, dial, body, text) catch |err| Fail.with(io, text, "the +Pager pane would not take it", err); - var ctl_buf: [64]u8 = undefined; - ninep_io.Client.write(gpa, dial, std.fmt.bufPrint(&ctl_buf, "/pane/{d}/ctl", .{serial}) catch unreachable, "clean\n") catch {}; + // Its serial read back on the open that asked, once the text is in: + // another client's exec meanwhile can never send it into that + // client's pane. + const answer = ninep_io.Client.ask(gpa, dial, "/pager", dir_line, text) catch |err| Fail.with(io, text, "no +Pager pane", err); + _ = std.fmt.parseInt(u32, std.mem.trim(u8, answer, " \n"), 10) catch |err| Fail.with(io, text, "no +Pager pane", err); } -/// Stdin to its end, its terminal escapes stripped (a pager's input is -/// coloured for a terminal; a text pane shows text), at most a file's -/// limit, a longer one cut there and said so at its end. +/// Stdin to its end, as it came (its escapes are the session's to parse, +/// pager.zig), at most a file's limit, a longer one cut there and said so +/// at its end. fn readStdinText(gpa: std.mem.Allocator) ![]u8 { const limit = pardes.memory.limits.max_file_bytes; var raw: std.ArrayList(u8) = .empty; @@ -164,90 +160,13 @@ fn readStdinText(gpa: std.mem.Allocator) ![]u8 { } try raw.appendSlice(gpa, chunk[0..got]); } - var text = try stripEscapes(gpa, raw.items); if (cut) { - const said = "\n[pardes: the rest of stdin is cut: a pane holds at most a file's limit]\n"; - text = try std.mem.concat(gpa, u8, &.{ text, said }); - } - return text; -} - -/// `bytes` without terminal escapes: CSI (`ESC [` ... a final byte, SGR -/// colour among them), OSC (`ESC ]` ... BEL or `ESC \`), any other -/// two-byte `ESC x`, and a man page's overstrike (`x BS x`, `_ BS x`). -pub fn stripEscapes(gpa: std.mem.Allocator, bytes: []const u8) ![]u8 { - var out = try std.ArrayList(u8).initCapacity(gpa, bytes.len); - var i: usize = 0; - while (i < bytes.len) { - const c = bytes[i]; - if (c == 0x1b and i + 1 < bytes.len) { - const kind = bytes[i + 1]; - i += 2; - if (kind == '[') { - while (i < bytes.len and !(bytes[i] >= 0x40 and bytes[i] <= 0x7e)) i += 1; - i += 1; - } else if (std.mem.indexOfScalar(u8, "()*+", kind) != null) { - i += 1; // a charset's name after it - } else if (kind == ']') { - while (i < bytes.len) : (i += 1) { - if (bytes[i] == 0x07) { - i += 1; - break; - } - if (bytes[i] == 0x1b and i + 1 < bytes.len and bytes[i + 1] == '\\') { - i += 2; - break; - } - } - } - continue; - } - // Overstrike: the byte before a backspace is struck over. - if (c == 0x08) { - if (out.items.len > 0) _ = out.pop(); - i += 1; - continue; - } - // A carriage return: CRLF is a newline; alone, the line starts - // over, as on a terminal, so a progress line keeps its last state. - if (c == '\r') { - if (i + 1 < bytes.len and bytes[i + 1] == '\n') { - i += 1; - continue; - } - const line_start = if (std.mem.lastIndexOfScalar(u8, out.items, '\n')) |nl| nl + 1 else 0; - out.shrinkRetainingCapacity(line_start); - i += 1; - continue; - } - // Bytes a terminal acts on and never shows: NUL, BEL, SO, SI. - if (c == 0 or c == 0x07 or c == 0x0e or c == 0x0f) { - i += 1; - continue; - } - out.appendAssumeCapacity(c); - i += 1; - } - return out.toOwnedSlice(gpa); -} - -test "stripEscapes takes out colour, other escapes and overstrike, and keeps the text" { - const gpa = std.testing.allocator; - const cases = [_][2][]const u8{ - .{ "\x1b[33mcommit abc\x1b[m\n", "commit abc\n" }, - .{ "a\x1b]8;;http://x\x1b\\link\x1b]8;;\x07b", "alinkb" }, - .{ "N\x08NA\x08AM\x08ME\x08E _\x08u", "NAME u" }, - .{ "plain\ttext\n", "plain\ttext\n" }, - .{ "\x1b(Bdone", "done" }, - .{ "a\r\nb\r\n", "a\nb\n" }, - .{ "10%\r50%\r100%\ndone\n", "100%\ndone\n" }, - .{ "x\x00y\x07z\x0e\x0f\n", "xyz\n" }, - }; - for (cases) |c| { - const got = try stripEscapes(gpa, c[0]); - defer gpa.free(got); - try std.testing.expectEqualStrings(c[1], got); + // CAN ends an escape the cut left half sent, and SGR 0 its colour, + // so the note is never swallowed or tinted. + const said = "\x18\x1b[m\n[pardes: the rest of stdin is cut: a pane holds at most a file's limit]\n"; + try raw.appendSlice(gpa, said); } + return raw.toOwnedSlice(gpa); } /// A forwarding failure in words, never an error's name: the ones this @@ -693,7 +612,7 @@ fn nativeMain(init: std.process.Init) !void { const command = std.fmt.bufPrint(&command_buf, "{s}{s}\n", .{ path, word[target.path.len..] }) catch |err| Refuse.with(init.io, word, err); // The pane it went to, read on the open that asked (another // client's look meanwhile is not this one's): what --wait waits on. - const went = ninep_io.Client.ask(arena, parent.dial, look, command) catch |err| Refuse.with(init.io, word, err); + const went = ninep_io.Client.ask(arena, parent.dial, look, command, "") catch |err| Refuse.with(init.io, word, err); var rows = std.mem.tokenizeAny(u8, went, " \n"); if (rows.next()) |row| made_serial = std.fmt.parseInt(u32, row, 10) catch null; } else { diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index cd8bc6c9..d4751191 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -650,7 +650,8 @@ pub fn readRoot(p: *Pardes, req: Req) Reply { /// /pager, `pardes -`'s: the directory written (empty, or not absolute: the /// session's) gets its one +Pager, made or emptied; the serial is what a -/// read of this same open answers, never another client's. +/// read of this same open answers, never another client's. What the open +/// writes after that line is the text, held by tree.zig for `fillPager`. pub fn writePager(p: *Pardes, req: Req) Reply { // A refused write leaves its open no answer, not the last one's. p.fs.results_len = 0; @@ -690,6 +691,35 @@ pub fn writePager(p: *Pardes, req: Req) Reply { return .{ .tag = req.tag, .written = @intCast(req.data.len) }; } +/// The text a /pager open wrote after its directory (`held`), a program's +/// output for a terminal, put in the +Pager `serial` as `pardes -` once +/// wrote it to the body: through ghostty-vt (pager.zig), its colours kept +/// as the pane's spans unless PagerColor is off, one undo step, and left +/// clean. Reads of the pane are its plain text. The held bytes go either way. +pub fn fillPager(p: *Pardes, serial: u32, held: *std.ArrayList(u8)) error{OutOfMemory}!void { + if (held.items.len == 0) return; + defer held.clearAndFree(p.gpa); + const id = p.paneBySerial(serial) orelse return; + const pane = p.panes[id].?; + const f = if (pane.file) |*file| file else return; + const page = try pardes.pager.parse(p.gpa, held.items, p.settings.pager_color); + held.clearAndFree(p.gpa); + if (page.text.len == 0 and f.content.len == 0) return page.deinit(p.gpa); + if (!pane.fs.nomark) panes.File.pushUndo(p, pane); + panes.File.setContent(p, f, page.text); + f.pager_spans = page.spans; + f.saved_revision = f.revision; +} + +/// The editor's step: the text of /pager opens closed unread goes in. +pub fn fillClosedPagers(p: *Pardes) void { + for (p.fs.pages.items) |*page| { + fillPager(p, page.serial, &page.bytes) catch {}; + page.bytes.deinit(p.gpa); + } + p.fs.pages.clearRetainingCapacity(); +} + /// One session builtin a line, at whichever pane has the keyboard as each /// runs, as the root's look and exec click there; all are checked first. pub fn writeRoot(p: *Pardes, req: Req) Reply { @@ -4088,21 +4118,26 @@ test "pager answers its +Pager on the open that asked, whatever another client e // `pardes -` once read, and wrote its text into. try testing.expect(!std.mem.eql(u8, want, rd(p, exec, 0, 64).bytes)); try testing.expectEqualStrings(want, call(p, .{ .tag = 5, .op = .read, .node = pager, .handle = asked, .size = 64 }).bytes); - // Refused, the same open answers nothing, not its last answer. - try testing.expectEqual(E.INVAL, call(p, .{ .tag = 6, .op = .write, .node = pager, .handle = asked, .data = "relative\n" }).errno()); - try testing.expectEqualStrings("", call(p, .{ .tag = 7, .op = .read, .node = pager, .handle = asked, .size = 64 }).bytes); + _ = call(p, .{ .tag = 6, .op = .release, .node = pager, .handle = asked, .opened = true }); + // Refused, an open answers nothing, not the session's last answer. + const refused = call(p, .{ .tag = 7, .op = .open, .node = pager, .omode = 2 }).reply.handle; + try testing.expectEqual(E.INVAL, call(p, .{ .tag = 8, .op = .write, .node = pager, .handle = refused, .data = "relative\n" }).errno()); + try testing.expectEqualStrings("", call(p, .{ .tag = 9, .op = .read, .node = pager, .handle = refused, .size = 64 }).bytes); + _ = call(p, .{ .tag = 10, .op = .release, .node = pager, .handle = refused, .opened = true }); // Resolved: `/tmp/../tmp/.` is /tmp's +Pager, the one made above. - const again = call(p, .{ .tag = 8, .op = .open, .node = pager, .omode = 2 }).reply.handle; - try testing.expectEqual(Status.ok, call(p, .{ .tag = 8, .op = .write, .node = pager, .handle = again, .data = "/tmp/../tmp/.\n" }).reply.status); - try testing.expectEqualStrings(want, call(p, .{ .tag = 9, .op = .read, .node = pager, .handle = again, .size = 64 }).bytes); - _ = call(p, .{ .tag = 9, .op = .release, .node = pager, .handle = again }); + const resolved = call(p, .{ .tag = 11, .op = .open, .node = pager, .omode = 2 }).reply.handle; + try testing.expectEqual(Status.ok, call(p, .{ .tag = 12, .op = .write, .node = pager, .handle = resolved, .data = "/tmp/../tmp/.\n" }).reply.status); + try testing.expectEqualStrings(want, call(p, .{ .tag = 13, .op = .read, .node = pager, .handle = resolved, .size = 64 }).bytes); + _ = call(p, .{ .tag = 14, .op = .release, .node = pager, .handle = resolved, .opened = true }); // One that may not be written is refused, permission denied. try testing.expectEqual(E.PERM, wr(p, pager, "/proc/1\n").errno()); // One directory a write, absolute, and there. try testing.expectEqual(E.INVAL, wr(p, pager, "/a\n/b\n").errno()); - // A second line on an open that asked already, as a mount sends two. + // One directory an open: one refused is not followed by another, as a + // mount sends two lines in two writes. (After one taken, what follows + // is the paged text: the test below.) const twice = call(p, .{ .tag = 20, .op = .open, .node = pager, .omode = 2 }).reply.handle; - try testing.expectEqual(Status.ok, call(p, .{ .tag = 21, .op = .write, .node = pager, .handle = twice, .data = "/tmp\n" }).reply.status); + try testing.expectEqual(E.INVAL, call(p, .{ .tag = 21, .op = .write, .node = pager, .handle = twice, .data = "relative\n" }).errno()); try testing.expectEqual(E.INVAL, call(p, .{ .tag = 22, .op = .write, .node = pager, .handle = twice, .data = "/tmp\n" }).errno()); _ = call(p, .{ .tag = 23, .op = .release, .node = pager, .handle = twice }); const relative = wr(p, pager, "relative\n"); @@ -4112,6 +4147,54 @@ test "pager answers its +Pager on the open that asked, whatever another client e try testing.expectEqual(E.NOTDIR, wr(p, pager, "/etc/passwd\n").errno()); } +test "what a /pager open writes after its directory is the text: plain in the body, its colours the pane's, clean, in by the read" { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + const pager = @intFromEnum(tree.TopFile.pager); + const asked = call(p, .{ .tag = 1, .op = .open, .node = pager, .omode = 2 }).reply.handle; + // The directory and the text's start in one write, escapes and all, a + // second line no directory; the rest in writes after it. + try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = pager, .handle = asked, .data = "/tmp\n\x1b[31mred\x1b[m /a\n" }).reply.status); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 3, .op = .write, .node = pager, .handle = asked, .data = "\x1b]0;title\x07N\x08Next\r\n" }).reply.status); + const id = for (p.panes, 0..) |slot, i| { + const pn = slot orelse continue; + if (pn.file) |f| if (std.mem.eql(u8, f.path, "/tmp/+Pager")) break i; + } else return error.NoPager; + const pn = p.panes[id].?; + try testing.expectEqualStrings("", pn.file.?.content); + // The read that answers the pane finds the text in. + var line: [16]u8 = undefined; + try testing.expectEqualStrings(try std.fmt.bufPrint(&line, "{d}\n", .{pn.serial}), call(p, .{ .tag = 4, .op = .read, .node = pager, .handle = asked, .size = 64 }).bytes); + _ = call(p, .{ .tag = 5, .op = .release, .node = pager, .handle = asked, .opened = true }); + const f = &pn.file.?; + try testing.expectEqualStrings("red /a\nNext\n", f.content); + try testing.expectEqualStrings("red /a\nNext\n", rd(p, Node.of(pn.serial, .body), 0, 64).bytes); + try testing.expectEqual(f.revision, f.saved_revision); + try testing.expectEqual(@as(usize, 2), f.pager_spans.len); + try testing.expectEqualStrings("red", f.content[f.pager_spans[0].start..f.pager_spans[0].end]); + try testing.expectEqual(pardes.Color{ .index = 1 }, f.pager_spans[0].style.fg); + try testing.expect(f.pager_spans[1].style.bold); + // One undo step back to the empty pane. + try testing.expect(f.history.undo_len > 0); + try testing.expectEqualStrings("", f.history.undo[f.history.undo_len - 1].content); + // An edit drops the colours (pager.zig's ponytail). + try testing.expectEqual(Status.ok, call(p, .{ .tag = 6, .op = .write, .node = Node.of(pn.serial, .body), .data = "more\n" }).reply.status); + try testing.expectEqual(@as(usize, 0), f.pager_spans.len); + + // PagerColor off, and an open closed with no read: the same text, plain, + // in at the editor's next step (a close through a mount never waits). + p.settings.pager_color = false; + const shut = call(p, .{ .tag = 7, .op = .open, .node = pager, .omode = 1 }).reply.handle; + try testing.expectEqual(Status.ok, call(p, .{ .tag = 8, .op = .write, .node = pager, .handle = shut, .data = "/tmp\n" }).reply.status); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 9, .op = .write, .node = pager, .handle = shut, .data = "\x1b[1;32mgreen\x1b[m\n" }).reply.status); + _ = call(p, .{ .tag = 10, .op = .release, .node = pager, .handle = shut, .opened = true }); + try testing.expectEqualStrings("", f.content); + fillClosedPagers(p); + try testing.expectEqualStrings("green\n", f.content); + try testing.expectEqual(@as(usize, 0), f.pager_spans.len); + try testing.expectEqual(f.revision, f.saved_revision); +} + test "a command pane an exec open was answered is leased to it while it stays open: another client's command gets a pane of its own" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 40543ecf..5499a337 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -89,6 +89,7 @@ pub fn needsQuiet(p: *Pardes, req: Req) bool { return switch (req.op) { .write, .setattr => true, .release => req.remove or holdsLines(p, req), + .read => holdsPage(p, req), else => false, }; } @@ -99,8 +100,9 @@ pub fn changesPane(p: *Pardes, req: Req) bool { return switch (req.op) { .write, .setattr => true, .open => req.node == @intFromEnum(TopFile.new), - .release => req.remove or holdsLines(p, req), - .lookup, .getattr, .read, .readdir => false, + .release => req.remove or holdsLines(p, req) or holdsPage(p, req), + .read => holdsPage(p, req), + .lookup, .getattr, .readdir => false, }; } @@ -138,6 +140,10 @@ pub const Open = struct { /// `/listeners`, a ctl opened to read) frozen at the open, as /// `/screen` is: reads in several chunks never splice two moments. frozen: []const u8, + /// A /pager open past its directory line: the +Pager's serial, the + /// text after that line held in `pending` until its read puts it + /// in (ctl.fillPager), or its close hands it to the editor's step. + pager: u32, } = .{ .snapshot = null }, /// What a write to a file of command lines left unfinished: a last line /// with no newline yet, or an Edit block still open. A write through a @@ -194,7 +200,7 @@ pub const Open = struct { gpa.free(run.line); }, .frozen => |bytes| gpa.free(bytes), - .event, .pty_data, .ctl, .lines, .writes => {}, + .event, .pty_data, .ctl, .lines, .writes, .pager => {}, } o.pending.deinit(gpa); if (o.replay) |r| gpa.free(r.bytes); @@ -899,7 +905,7 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { pn.fs.event_reader = pn.fs.event_reader or reader; }, .pty_data => pane_of.?.fs.pty_reader = true, - .run, .ctl, .lines, .writes => {}, + .run, .ctl, .lines, .writes, .pager => {}, } return .{ .tag = req.tag, .handle = @intCast(i + 1) }; } @@ -961,6 +967,12 @@ fn releaseHandle(p: *Pardes, req: Req) void { if (t == .col and t.col.file == .tag) cols.released(p, t.col.serial); if (t == .top and t.top == .tag) cols.released(p, null); const o = openOf(p, req) orelse return; + // A /pager open's text, not read for, goes in at the editor's next + // step (ctl.fillClosedPagers): this close need not wait for quiet. + if (o.what == .pager and o.pending.items.len > 0) { + p.fs.pages.append(p.gpa, .{ .serial = o.what.pager, .bytes = o.pending }) catch o.pending.deinit(p.gpa); + o.pending = .empty; + } // The last line an open wrote with no newline after it runs now. if (o.pending.items.len > 0) { const rest = p.scratch.allocator().dupe(u8, o.pending.items) catch ""; @@ -990,7 +1002,7 @@ fn releaseHandle(p: *Pardes, req: Req) void { .ctl => if (pn.fs.lock == req.handle) { pn.fs.lock = null; }, - .snapshot, .log, .lines, .writes, .frozen => {}, + .snapshot, .log, .lines, .writes, .frozen, .pager => {}, }; o.deinit(p.gpa); } @@ -1014,6 +1026,8 @@ fn setattr(p: *Pardes, req: Req, target: Target) Reply { } fn read(p: *Pardes, req: Req, target: Target) Reply { + // A /pager open's text goes in before its read answers the pane. + if (openOf(p, req)) |o| if (o.what == .pager) ctl.fillPager(p, o.what.pager, &o.pending) catch return Reply.fail(req.tag, E.NOMEM); // A listing reads what it was at the open. if (openOf(p, req)) |o| if (o.what == .frozen) { const bytes = o.what.frozen; @@ -1158,7 +1172,7 @@ fn linesOpen(target: Target, req: Req) bool { /// A release that will run a line its open held back. fn holdsLines(p: *Pardes, req: Req) bool { const o = openOf(p, req) orelse return false; - return o.pending.items.len > 0; + return o.pending.items.len > 0 and o.what != .pager; } /// A line held back longer than this is refused rather than kept growing. @@ -1173,7 +1187,39 @@ fn ctlFile(target: Target) bool { }; } +/// /pager on an open: its first line names the directory and runs as any +/// line does; what follows it, in that write and the open's later ones, is +/// a program's output, escapes and all, held whole and never run as lines. fn write(p: *Pardes, req: Req, target: Target) Reply { + const o = (if (target == .top and target.top == .pager) openOf(p, req) else null) orelse return writeLines(p, req, target); + if (o.what == .pager) { + if (o.pending.items.len + req.data.len > pager_cap) return failText(req.tag, E.NOSPC, "pager: no space: the text is over a file's limit"); + o.pending.appendSlice(p.gpa, req.data) catch return Reply.fail(req.tag, E.NOMEM); + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; + } + const nl = std.mem.indexOfScalar(u8, req.data, '\n') orelse return writeLines(p, req, target); + var head = req; + head.data = req.data[0 .. nl + 1]; + const reply = writeLines(p, head, target); + if (reply.status != .ok or o.results.len == 0) return reply; + o.what = .{ .pager = o.results.list[0] }; + o.pending.clearRetainingCapacity(); + o.pending.appendSlice(p.gpa, req.data[nl + 1 ..]) catch return Reply.fail(req.tag, E.NOMEM); + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; +} + +/// The most a /pager open holds: a file's limit, and `pardes -`'s note +/// that its stdin was cut there. +const pager_cap = @import("../memory.zig").limits.max_file_bytes + 4096; + +/// A /pager open holding text: its read puts it in (ctl.fillPager), its +/// close hands it to the editor's step. +pub fn holdsPage(p: *Pardes, req: Req) bool { + const o = openOf(p, req) orelse return false; + return o.what == .pager and o.pending.items.len > 0; +} + +fn writeLines(p: *Pardes, req: Req, target: Target) Reply { // A command line holds no control character but a tab: the whole write // is refused at once, not held to fail unseen at the close. if (resultsFile(target) or ctlFile(target)) for (req.data) |c| if ((c < ' ' and c != '\t' and c != '\n' and c != '\r') or c == 0x7f) return failText(req.tag, E.INVAL, ctl.e_control); diff --git a/src/pager.zig b/src/pager.zig new file mode 100644 index 00000000..30418623 --- /dev/null +++ b/src/pager.zig @@ -0,0 +1,373 @@ +//! A program's output, paged into a +Pager (`pardes -`): the text it +//! prints, and its SGR colours as spans over that text. ghostty-vt, which +//! terminal panes already drive, parses every escape; this keeps what is +//! printed and how SGR styles it, and drops every other control (cursor +//! motion, OSC titles and hyperlinks, modes). The spans are display state +//! of the pane only: no 9P file reads them (File.recolorSyntax draws them). +const std = @import("std"); +const pardes = @import("pardes.zig"); +const CellStyle = @import("surface.zig").CellStyle; +const ghostty_vt = if (pardes.terminal_panes) @import("ghostty-vt") else struct {}; + +/// Bytes `start..end` of the text, drawn in `style`. A palette colour stays +/// `.index`, resolved through the theme as it is drawn (terminal.palColor), +/// and `.default` is the pane's own. +pub const Span = struct { start: u32, end: u32, style: CellStyle }; + +/// ponytail: past this many spans the rest of a page is plain, rather than +/// ~100 MB of spans for a 256 MiB coloured log; a packed style if it matters. +pub const max_spans = 4 << 20; + +pub const Page = struct { + text: []u8, + spans: []Span, + + pub fn deinit(page: Page, gpa: std.mem.Allocator) void { + gpa.free(page.text); + gpa.free(page.spans); + } +}; + +/// `raw`, a program's output for a terminal, as text and, `colour` on +/// (PagerColor), its spans. Both are `gpa`'s. +pub fn parse(gpa: std.mem.Allocator, raw: []const u8, colour: bool) !Page { + // ponytail: no ghostty-vt on esp32p4 (no terminal panes, no PAGER): + // the text is taken as sent. + if (comptime !pardes.terminal_panes) return .{ .text = try gpa.dupe(u8, raw), .spans = &.{} }; + var h: Handler = .{ .gpa = gpa, .colour = colour }; + errdefer h.text.deinit(gpa); + errdefer h.spans.deinit(gpa); + try h.text.ensureTotalCapacity(gpa, raw.len); + var stream: ghostty_vt.Stream(*Handler) = .init(&h); + defer stream.deinit(); + stream.nextSlice(raw); + if (h.failed) return error.OutOfMemory; + const text = try h.text.toOwnedSlice(gpa); + errdefer gpa.free(text); + return .{ .text = text, .spans = try h.spans.toOwnedSlice(gpa) }; +} + +const Handler = struct { + gpa: std.mem.Allocator, + colour: bool, + text: std.ArrayList(u8) = .empty, + spans: std.ArrayList(Span) = .empty, + /// What SGR has set so far. + style: CellStyle = .{}, + /// Where the line being printed starts, and its last character. + line_start: usize = 0, + last: usize = 0, + /// A carriage return not yet followed by a newline: the line starts + /// over at the next print, as on a terminal, so a progress line keeps + /// its last state. + cr: bool = false, + /// A backspace: the next print strikes over the character before it. + bs: bool = false, + failed: bool = false, + + const Action = ghostty_vt.StreamAction; + + pub fn vt(h: *Handler, comptime action: Action.Tag, value: Action.Value(action)) void { + switch (action) { + .print => h.print(value.cp), + .print_slice => h.printRun(value.cps), + // CSI b repeats the last character, as a terminal draws it; + // a terminal stops at its edge, and this at a line's worth. + .print_repeat => if (h.text.items.len > h.last) { + const cp = std.unicode.utf8Decode(h.text.items[h.last..]) catch return; + for (0..@min(value, 1024)) |_| h.print(cp); + }, + .set_attribute => if (h.colour) h.attribute(value), + .linefeed => { + h.append("\n"); + h.line_start = h.text.items.len; + h.last = h.line_start; + h.cr = false; + h.bs = false; + }, + .carriage_return => h.cr = true, + .backspace => h.bs = h.text.items.len > h.line_start, + .horizontal_tab => for (0..@min(value, 64)) |_| h.print('\t'), + else => {}, + } + } + + pub fn deinit(_: *Handler) void {} + + // ponytail: bytes that are not UTF-8 reach here as U+FFFD (ghostty's + // decoder replaces them, as a terminal shows them); a raw-byte pass + // through the stream if a +Pager must keep them. + fn print(h: *Handler, cp: u21) void { + // A control a terminal acts on and never draws: ghostty's fast path + // hands those past 0x0f (CAN, DEL, the C1 set) on as printed text. + // A tab is HT's, printed here. + if ((cp < 0x20 and cp != '\t') or (cp >= 0x7f and cp < 0xa0)) return; + if (h.cr) { + h.text.shrinkRetainingCapacity(h.line_start); + h.cut(h.line_start); + h.last = h.line_start; + h.cr = false; + h.bs = false; + } + var buf: [4]u8 = undefined; + const n = std.unicode.utf8Encode(cp, &buf) catch std.unicode.utf8Encode(0xfffd, &buf) catch unreachable; + if (h.bs) { + // A man page's overstrike: a character struck over itself is + // bold, one struck with `_` (either way round) is underlined; + // any other is replaced, as on a terminal. + h.bs = false; + const prev = h.text.items[h.last..]; + var struck = h.style; + if (std.mem.eql(u8, prev, buf[0..n])) { + struck.bold = true; + } else if (std.mem.eql(u8, prev, "_")) { + h.text.shrinkRetainingCapacity(h.last); + h.append(buf[0..n]); + struck.ul = .single; + } else if (cp == '_') { + struck.ul = .single; + } else { + h.text.shrinkRetainingCapacity(h.last); + h.cut(h.last); + h.last = h.text.items.len; + h.append(buf[0..n]); + h.span(h.last, h.style); + return; + } + h.cut(h.last); + h.span(h.last, struck); + return; + } + h.last = h.text.items.len; + h.append(buf[0..n]); + h.span(h.last, h.style); + } + + /// A run of printed characters (most of a page): the first as `print` + /// takes it, a pending return or backspace and all, the rest straight + /// on, as one span. A 256 MiB page goes through here. + fn printRun(h: *Handler, cps: []const u32) void { + if (cps.len == 0) return; + h.print(@intCast(cps[0])); + const rest = cps[1..]; + if (rest.len == 0) return; + var need: usize = 0; + for (rest) |cp| need += if (cp < 0x80) 1 else std.unicode.utf8CodepointSequenceLength(@intCast(cp)) catch 3; + h.text.ensureUnusedCapacity(h.gpa, need) catch { + h.failed = true; + return; + }; + const from = h.text.items.len; + for (rest) |cp| { + if (cp < 0x20 or (cp >= 0x7f and cp < 0xa0)) continue; + h.last = h.text.items.len; + if (cp < 0x80) { + h.text.appendAssumeCapacity(@intCast(cp)); + continue; + } + var buf: [4]u8 = undefined; + const n = std.unicode.utf8Encode(@intCast(cp), &buf) catch std.unicode.utf8Encode(0xfffd, &buf) catch unreachable; + h.text.appendSliceAssumeCapacity(buf[0..n]); + } + h.span(from, h.style); + } + + fn append(h: *Handler, bytes: []const u8) void { + h.text.appendSlice(h.gpa, bytes) catch { + h.failed = true; + }; + } + + /// `from` to the text's end drawn in `style`: the span before it goes + /// on when it ends there in the same style. + fn span(h: *Handler, from: usize, style: CellStyle) void { + if (!h.colour or std.meta.eql(style, CellStyle{})) return; + const end: u32 = @intCast(h.text.items.len); + if (h.spans.items.len > 0) { + const tail = &h.spans.items[h.spans.items.len - 1]; + if (tail.end == from and std.meta.eql(tail.style, style)) { + tail.end = end; + return; + } + } + if (h.spans.items.len >= max_spans) return; + h.spans.append(h.gpa, .{ .start = @intCast(from), .end = end, .style = style }) catch { + h.failed = true; + }; + } + + /// No span reaches past `at` any more: the text there is gone. + fn cut(h: *Handler, at: usize) void { + while (h.spans.items.len > 0) { + const tail = &h.spans.items[h.spans.items.len - 1]; + if (tail.end <= at) return; + if (tail.start < at) { + tail.end = @intCast(at); + return; + } + _ = h.spans.pop(); + } + } + + fn attribute(h: *Handler, attr: ghostty_vt.Attribute) void { + const s = &h.style; + switch (attr) { + .unset => s.* = .{}, + .bold => s.bold = true, + // SGR 22 ends faint as well as bold. + .reset_bold => { + s.bold = false; + s.dim = false; + }, + .faint => s.dim = true, + .italic => s.italic = true, + .reset_italic => s.italic = false, + .underline => |u| s.ul = switch (u) { + .none => .off, + .single => .single, + .double => .double, + .curly => .curly, + .dotted => .dotted, + .dashed => .dashed, + }, + .blink => s.blink = true, + .reset_blink => s.blink = false, + .inverse => s.reverse = true, + .reset_inverse => s.reverse = false, + .invisible => s.invisible = true, + .reset_invisible => s.invisible = false, + .strikethrough => s.strikethrough = true, + .reset_strikethrough => s.strikethrough = false, + .direct_color_fg => |c| s.fg = .{ .rgb = .{ c.r, c.g, c.b } }, + .direct_color_bg => |c| s.bg = .{ .rgb = .{ c.r, c.g, c.b } }, + .@"8_fg", .@"8_bright_fg" => |name| s.fg = .{ .index = @intFromEnum(name) }, + .@"8_bg", .@"8_bright_bg" => |name| s.bg = .{ .index = @intFromEnum(name) }, + .@"256_fg" => |i| s.fg = .{ .index = i }, + .@"256_bg" => |i| s.bg = .{ .index = i }, + .reset_fg => s.fg = .default, + .reset_bg => s.bg = .default, + // A cell has no overline and no underline colour to take. + .overline, .reset_overline, .underline_color, .@"256_underline_color", .reset_underline_color, .unknown => {}, + } + } +}; + +// ---- tests ---- + +const testing = std.testing; + +/// The text `raw` pages to, and its spans as `text[start..end]=style` lines. +fn expectPage(raw: []const u8, text: []const u8, spans: []const struct { []const u8, CellStyle }) !void { + if (comptime !pardes.terminal_panes) return error.SkipZigTest; + const page = try parse(testing.allocator, raw, true); + defer page.deinit(testing.allocator); + try testing.expectEqualStrings(text, page.text); + for (spans, 0..) |want, i| { + if (i >= page.spans.len) { + std.debug.print("missing span {d}: \"{s}\"\n", .{ i, want[0] }); + return error.TestExpectedEqual; + } + const got = page.spans[i]; + try testing.expectEqualStrings(want[0], page.text[got.start..got.end]); + try testing.expectEqualDeep(want[1], got.style); + } + try testing.expectEqual(spans.len, page.spans.len); +} + +test "git log --color: the commit line yellow, the rest plain" { + try expectPage( + "\x1b[33mcommit 0123abc\x1b[m\x1b[33m (\x1b[m\x1b[1;36mHEAD -> \x1b[m\x1b[1;32mmain\x1b[m\x1b[33m)\x1b[m\nAuthor: a \n\n subject\n", + "commit 0123abc (HEAD -> main)\nAuthor: a \n\n subject\n", + &.{ + .{ "commit 0123abc (", .{ .fg = .{ .index = 3 } } }, + .{ "HEAD -> ", .{ .fg = .{ .index = 6 }, .bold = true } }, + .{ "main", .{ .fg = .{ .index = 2 }, .bold = true } }, + .{ ")", .{ .fg = .{ .index = 3 } } }, + }, + ); +} + +test "ls --color=always: 01;34 directories and 01;32 executables, reset by 0 and none" { + try expectPage( + "\x1b[0m\x1b[01;34mdir\x1b[0m\n\x1b[01;32mrun.sh\x1b[0m\nplain.txt\n", + "dir\nrun.sh\nplain.txt\n", + &.{ + .{ "dir", .{ .fg = .{ .index = 4 }, .bold = true } }, + .{ "run.sh", .{ .fg = .{ .index = 2 }, .bold = true } }, + }, + ); +} + +test "grep --color=always: the match, the file name and the separator, and EL dropped" { + try expectPage( + "\x1b[35m\x1b[Ka.txt\x1b[m\x1b[K\x1b[36m\x1b[K:\x1b[m\x1b[Kone \x1b[01;31m\x1b[Kfoo\x1b[m\x1b[K two\n", + "a.txt:one foo two\n", + &.{ + .{ "a.txt", .{ .fg = .{ .index = 5 } } }, + .{ ":", .{ .fg = .{ .index = 6 } } }, + .{ "foo", .{ .fg = .{ .index = 1 }, .bold = true } }, + }, + ); +} + +test "a man page's overstrike: bold and underline, and a stray backspace" { + try expectPage( + "N\x08NA\x08AM\x08ME\x08E _\x08u_\x08s x\x08_ a\x08b\x08\n", + "NAME us x b\n", + &.{ + .{ "NAME", .{ .bold = true } }, + .{ "us", .{ .ul = .single } }, + .{ "x", .{ .ul = .single } }, + }, + ); +} + +test "truecolor, 256 colours, background, italic, faint, inverse and curly underline" { + try expectPage( + "\x1b[38;2;255;128;0mo\x1b[48;5;236mb\x1b[0;3;2mi\x1b[7mr\x1b[0;4:3mc\x1b[m.\n", + "obirc.\n", + &.{ + .{ "o", .{ .fg = .{ .rgb = .{ 255, 128, 0 } } } }, + .{ "b", .{ .fg = .{ .rgb = .{ 255, 128, 0 } }, .bg = .{ .index = 236 } } }, + .{ "i", .{ .italic = true, .dim = true } }, + .{ "r", .{ .italic = true, .dim = true, .reverse = true } }, + .{ "c", .{ .ul = .curly } }, + }, + ); +} + +test "every other escape is dropped, and a stray or broken one loses no text after it" { + const cases = [_][2][]const u8{ + .{ "a\x1b]8;;http://x\x1b\\link\x1b]8;;\x07b", "alinkb" }, + .{ "\x1b]0;title\x07\x1b[2J\x1b[H\x1b[?1049hdone\n", "done\n" }, + .{ "\x1b(Bdone", "done" }, + .{ "plain\ttext\n", "plain\ttext\n" }, + .{ "a\r\nb\r\n", "a\nb\n" }, + .{ "10%\r50%\r\x1b[K100%\ndone\n", "100%\ndone\n" }, + .{ "x\x00y\x07z\x0e\x0f\n", "xyz\n" }, + // Controls ghostty's fast path prints: CAN, FS, DEL and a C1. + .{ "x\x18y\x1cz\x7f!\u{85}?\n", "xyz!?\n" }, + // A broken CSI: its parameter bytes are eaten up to a final byte, as + // a terminal eats them; CAN abandons one, and the text goes on. + .{ "a\x1b[31;\x18b\x1b[m\n", "ab\n" }, + // An unknown SGR changes nothing; an ESC at the very end is dropped. + .{ "\x1b[99mz\x1b", "z" }, + }; + for (cases) |c| try expectPage(c[0], c[1], &.{}); +} + +test "bytes that are not UTF-8 page as U+FFFD, the text around them kept" { + try expectPage("caf\xe9 \xff\xfe ok\n", "caf\u{fffd} \u{fffd}\u{fffd} ok\n", &.{}); +} + +test "PagerColor off: the same text, no spans, overstrike included" { + if (comptime !pardes.terminal_panes) return error.SkipZigTest; + const page = try parse(testing.allocator, "\x1b[31mred\x1b[m N\x08N\n", false); + defer page.deinit(testing.allocator); + try testing.expectEqualStrings("red N\n", page.text); + try testing.expectEqual(@as(usize, 0), page.spans.len); +} + +test "a carriage return's rewrite takes the spans of what it rewrote with it" { + try expectPage("\x1b[31m10%\r\x1b[32m100%\x1b[m\n", "100%\n", &.{.{ "100%", .{ .fg = .{ .index = 2 } } }}); +} diff --git a/src/pardes.zig b/src/pardes.zig index c6850451..5d9f8606 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -11,6 +11,7 @@ pub const ctlfs = @import("ninep/tree.zig"); pub const syntax = @import("syntax.zig"); const tracy = @import("tracy.zig"); pub const panes = @import("panes.zig"); +pub const pager = @import("pager.zig"); const locations = @import("locations.zig"); pub const tagline = @import("tagline.zig"); pub const exec = @import("exec.zig"); @@ -496,6 +497,7 @@ test { _ = @import("recent.zig"); _ = @import("Presentation.zig"); _ = @import("animation.zig"); + _ = @import("pager.zig"); } pub const Builtin = builtins.registry.Builtin(); @@ -4221,7 +4223,8 @@ pub const Options = struct { file: ?[]const u8 = null, file_line: usize = 0, missing: ?struct { word: []const u8, dir: []const u8 } = null, - /// `pardes -`: stdin, its escapes stripped, for a +Pager pane at boot. + /// `pardes -`: stdin as it came, for a +Pager pane at boot (pager.zig + /// parses it). stdin_text: ?[]const u8 = null, tty_toggle: u21 = config.tty_toggle_default, /// load a dump of another instance instead of spawning shells (acme -l) @@ -4638,7 +4641,9 @@ pub const Pardes = struct { p.oneColumn(); }, .stdin => { - const content = try gpa.dupe(u8, opts.stdin_text.?); + const page = try pager.parse(gpa, opts.stdin_text.?, p.settings.pager_color); + errdefer gpa.free(page.spans); + const content = page.text; errdefer gpa.free(content); const dir = p.sessionDir(); const shown = try panes.Output.open(p, 0, dir, .{ .cmd = .New }, "", content); @@ -4647,6 +4652,7 @@ pub const Pardes = struct { gpa.free(shown.file.?.path); shown.file.?.path = named; shown.file.?.pager_diff = panes.File.looksLikeDiff(content[0..@min(content.len, 64 * 1024)]); + shown.file.?.pager_spans = page.spans; p.oneColumn(); }, .embedded => { @@ -5748,6 +5754,8 @@ pub const Pardes = struct { if (v.now) |clock| p.advance(clock(h.ctx)); // What a 9P open wrote in a row goes in once the writes pause. ctlfs.pane.flushPausedBatch(p); + // ...and what a /pager open was written before its close. + ctlfs.ctl.fillClosedPagers(p); while (p.nextQueued()) |ev| p.update(ev); while (p.nextEffect()) |e| p.perform(e); turn.settle(); diff --git a/test/fs.py b/test/fs.py index 8eed2e29..33abb835 100644 --- a/test/fs.py +++ b/test/fs.py @@ -1529,6 +1529,26 @@ def test(binary, quic=False): log_now = client.read('/log').decode() assert f'\nnew {made_now} {root}/+Pager\n' in '\n' + log_now, log_now[-400:] assert f'\nrename {made_now} ' not in '\n' + log_now + # Its colours are the pane's, drawn and never read: the body is + # the plain text, and the screen shows `red` in the theme's red + # and `rgb` in the colour given, the rest in the pane's ink. + fed = subprocess.run([binary, '-'], cwd=root, env=env, + input=b'\x1b]0;title\x07\x1b[31mred\x1b[m \x1b[38;2;1;2;3mrgb\x1b[m plain\n', + stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10) + assert fed.returncode == 0, fed.stderr + assert client.read(f'/pane/{made_now}/body') == b'red rgb plain\n' + screen = client.screen() + for row in range(screen['rows']): + cells = screen['cells'][row * screen['cols']:(row + 1) * screen['cols']] + text = ''.join(cell[0] for cell in cells) + at = text.find('red rgb plain') + if at >= 0: + break + else: + raise AssertionError(('the paged text is not on the screen', screen)) + ink = [screen['styles'][cells[at + i][1]]['fg'] for i in (0, 4, 8)] + assert ink[1] == {'rgb': [1, 2, 3]}, ink + assert ink[0] != ink[2] and ink[0] != ink[1], ink # The directory's one +Pager: the next paged text refills it. fed = subprocess.run([binary, '-'], cwd=root, env=env, input=b'again\r\nprogress 10%\rprogress 100%\n', stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=10) diff --git a/test/selfmount.py b/test/selfmount.py index ddfb77dc..57dfffa8 100644 --- a/test/selfmount.py +++ b/test/selfmount.py @@ -182,6 +182,20 @@ def run(binary): log = client.read('/log').decode() check(log.count('over 1 MiB') == 1 and 'unknown control message' not in log and 'after-long' in log, 'a 1.1 MiB line is refused once, its tail never a line, the next line runs') + # `pardes -` by hand through the mount: the directory, then a + # program's output, escapes and all, on one open of /pager; the + # +Pager reads back the plain text. + got = run(f"{{ pwd; printf '\\033[31mred\\033[m\\n'; }} > {mount}/pager\n".encode()) + rows = [row.rsplit(maxsplit=1)[0].split(maxsplit=3) for row in client.read('/index').decode().splitlines()] + paged = [row[0] for row in rows if len(row) == 4 and row[3].endswith('/+Pager')] + check(got == '0' and len(paged) == 1, f'a +Pager made through the mount ({got!r}, {paged!r})') + if paged: + # The text goes in at the open's close, and a mount's close + # (FUSE's release) comes after close(2) has returned. + deadline = time.monotonic() + 5 + while (said := client.read(f'/pane/{paged[0]}/body')) != b'red\n' and time.monotonic() < deadline: + time.sleep(.05) + check(said == b'red\n', f'its body is the plain text ({said!r})') # Forty event reads held through the mount, a follower each, and # the mount still answers the rest: 9ns keeps workers past what # the editor holds (128), so `cat layout` is not queued behind diff --git a/test/snapshots/pagercolor.golden b/test/snapshots/pagercolor.golden new file mode 100644 index 00000000..811d3d96 --- /dev/null +++ b/test/snapshots/pagercolor.golden @@ -0,0 +1,120 @@ +== snap pager grid=100x50 cursor=4,5 +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/pagercolor/cwd Tty+bash Save Mode Filter Collapse Del +| $ printf '\033]0;title\007\033[31mred\033[m \033[1;32mbold green\033[m \033[38;2;200;100;0mrgb\033 +| [m \033[4mul\033[m N\bNA\bAM\bME\bE _\bu_\bs plain\n' | $(readlink /proc/$PPID/exe) - +| $ +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| +| /tmp/pardes-snap/pagercolor/cwd/+New Save Tty Collapse Del +| 1 +| +| +| +| +| +| +| /tmp/pardes-snap/pagercolor/cwd/+Pager Save Tty Collapse Del +| 1 red bold green rgb ul NAME us plain +| 2 +== style pager-colours grid=100x50 +|0: 0-99 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-2 d,#314738, 3-99 #becfc4,#314738, +|2: 0-1 #000000,#add38a, 2-2 #000000,#314738, 3-34 #becfc4,#314738, 35-43 #dfbce5,#314738, 44-99 #becfc4,#314738, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|6: 0-0 d,#608269, 1-99 d,#0d1410, +|7: 0-0 d,#608269, 1-99 d,#0d1410, +|8: 0-0 d,#608269, 1-99 d,#0d1410, +|9: 0-0 d,#608269, 1-99 d,#0d1410, +|10: 0-0 d,#608269, 1-99 d,#0d1410, +|11: 0-0 d,#608269, 1-99 d,#0d1410, +|12: 0-0 d,#608269, 1-99 d,#0d1410, +|13: 0-0 d,#608269, 1-99 d,#0d1410, +|14: 0-0 d,#608269, 1-99 d,#0d1410, +|15: 0-0 d,#608269, 1-99 d,#0d1410, +|16: 0-0 d,#608269, 1-99 d,#0d1410, +|17: 0-0 d,#608269, 1-99 d,#0d1410, +|18: 0-0 d,#608269, 1-99 d,#0d1410, +|19: 0-0 d,#608269, 1-99 d,#0d1410, +|20: 0-0 d,#608269, 1-99 d,#0d1410, +|21: 0-0 d,#608269, 1-99 d,#0d1410, +|22: 0-0 d,#608269, 1-99 d,#0d1410, +|23: 0-0 d,#608269, 1-99 d,#0d1410, +|24: 0-0 d,#608269, 1-99 d,#0d1410, +|25: 0-0 d,#608269, 1-99 d,#0d1410, +|26: 0-0 d,#608269, 1-99 d,#0d1410, +|27: 0-0 d,#608269, 1-99 d,#0d1410, +|28: 0-0 d,#608269, 1-99 d,#0d1410, +|29: 0-0 d,#608269, 1-99 d,#0d1410, +|30: 0-0 d,#608269, 1-99 d,#0d1410, +|31: 0-0 d,#608269, 1-99 d,#0d1410, +|32: 0-0 d,#608269, 1-99 d,#0d1410, +|33: 0-0 d,#608269, 1-99 d,#0d1410, +|34: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-39 #d3b0d9,#1d2824, 40-99 #b2c3b8,#1d2824, +|35: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, +|36: 0-0 d,#608269, 1-99 d,#0d1410, +|37: 0-0 d,#608269, 1-99 d,#0d1410, +|38: 0-0 d,#608269, 1-99 d,#0d1410, +|39: 0-0 d,#608269, 1-99 d,#0d1410, +|40: 0-0 d,#608269, 1-99 d,#0d1410, +|41: 0-0 d,#608269, 1-99 d,#0d1410, +|42: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-41 #d3b0d9,#1d2824, 42-99 #b2c3b8,#1d2824, +|43: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f1a39b,#0d1410, 11-20 #b6ce94,#0d1410,b 21-21 #b6ce94,#0d1410, 22-25 #c86400,#0d1410, 26-27 #e5eee5,#0d1410,u 28-28 #e5eee5,#0d1410, 29-32 #e5eee5,#0d1410,b 33-33 #e5eee5,#0d1410, 34-35 #e5eee5,#0d1410,u 36-99 #e5eee5,#0d1410, +|44: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, +|45: 0-0 d,#608269, 1-99 d,#0d1410, +|46: 0-0 d,#608269, 1-99 d,#0d1410, +|47: 0-0 d,#608269, 1-99 d,#0d1410, +|48: 0-0 d,#608269, 1-99 d,#0d1410, +|49: 0-0 d,#608269, 1-99 d,#0d1410, +== snap pager-diff grid=100x50 cursor=4,8 +|5: $ printf '\033[33mcommit 0123\033[33mabc\033[m\n\033[1mdiff --git a/x b/x\033[m\n\033[1m--- a/x\03 +|6: 3[m\n\033[1m+++ b/x\033[m\n\033[36m@@ -1 +1 @@\033[m\n\033[31m-old\033[m\n\033[32m+new\033[m\n' | +|7: $(readlink /proc/$PPID/exe) - +|8: $ +|43: 1 commit 0123abc +|44: 2 diff --git a/x b/x +|45: 3 --- a/x +|46: 4 +++ b/x +|47: 5 @@ -1 +1 @@ +|48: 6 -old +|49: 7 +new +== style pager-diff-colours grid=100x50 +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|43: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e9c680,#0d1410, +|44: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-24 #b9f480,#0d1410,b 25-99 #b9f480,#0d1410, +|45: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-13 #b9f480,#0d1410,b 14-99 #b9f480,#0d1410, +|46: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-13 #b9f480,#0d1410,b 14-99 #b9f480,#0d1410, +|47: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #b6c59e,#0d1410, +|48: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-7 #f1a39b,#302b25,b 8-99 #f8c082,#302b25, +|49: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-7 #b6ce94,#263025,b 8-99 #b8d88a,#263025, diff --git a/test/snapshots/pagercolor.snap b/test/snapshots/pagercolor.snap new file mode 100644 index 00000000..650792b3 --- /dev/null +++ b/test/snapshots/pagercolor.snap @@ -0,0 +1,24 @@ +# `pardes -` keeps a program's colours (PagerColor, on by default): its SGR +# becomes the +Pager's own colours over the plain text (red through the +# theme's palette, truecolor as given, bold and underline, a man page's +# overstrike), and every other escape (the OSC title) is dropped. The +# needles waited for are split by escapes in the typed line, so only the +# paged text holds them. +start 50 100 +wait 8000 $ +stable 700 20000 +text printf '\033]0;title\007\033[31mred\033[m \033[1;32mbold green\033[m \033[38;2;200;100;0mrgb\033[m \033[4mul\033[m N\bNA\bAM\bME\bE _\bu_\bs plain\n' | $(readlink /proc/$PPID/exe) - +key enter +wait 20000 red bold green +stable 700 20000 +snap pager +snapstyle pager-colours +# A coloured diff: the rows pardes tints as added or removed are drawn as +# its own diff, and git's colours stay on the rest (the bold header, the +# cyan hunk line, the yellow commit line). +text printf '\033[33mcommit 0123\033[33mabc\033[m\n\033[1mdiff --git a/x b/x\033[m\n\033[1m--- a/x\033[m\n\033[1m+++ b/x\033[m\n\033[36m@@ -1 +1 @@\033[m\n\033[31m-old\033[m\n\033[32m+new\033[m\n' | $(readlink /proc/$PPID/exe) - +key enter +wait 20000 0123abc +stable 700 20000 +snap pager-diff +snapstyle pager-diff-colours -- cgit v1.3 From 2dbb047a82523c578cb511058c6e1b745cfc8073 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 17:36:52 -0300 Subject: A look at a directory opens a pane listing it, as acme's directory window: named dir/, its entries in acme's columns (bytewise, dotfiles kept, a directory's marked /), a look at an entry from there, Get or a look again reads it again, never dirty, Save refused; DirLook terminal keeps ls in a terminal Co-Authored-By: Claude Opus 5.5 --- docs/typ/builtins-gui.json | 1 + docs/typ/builtins-tty.json | 1 + docs/typ/cheatsheet.typ | 2 +- docs/typ/guide.typ | 2 +- docs/typ/reference.typ | 7 +- src/CHANGELOG.md | 4 + src/Dir.zig | 507 ++++++++++++++++++++++++++++++++++++++++++ src/File.zig | 11 + src/Output.zig | 15 +- src/builtins.zig | 10 +- src/config.zig | 14 +- src/exec.zig | 6 + src/host_io.zig | 2 +- src/look.zig | 5 + src/ninep/ctl.zig | 21 +- src/ninep/pane.zig | 2 +- src/panes.zig | 3 + src/pardes.zig | 8 +- src/tagline.zig | 2 + test/fs.py | 26 +++ test/snapshots/cmdword.snap | 3 + test/snapshots/dirpane.golden | 13 ++ test/snapshots/dirpane.snap | 27 +++ test/snapshots/look-dir.snap | 3 + test/snapshots/lookpanes.snap | 3 + test/snapshots/nested.golden | 8 +- test/snapshots/ttylook.snap | 3 + 27 files changed, 684 insertions(+), 25 deletions(-) create mode 100644 src/Dir.zig create mode 100644 test/snapshots/dirpane.golden create mode 100644 test/snapshots/dirpane.snap (limited to 'src/File.zig') diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index ec214069..e4a8f611 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -26,6 +26,7 @@ {"name": "Delcol", "leader": "SPC c d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close this column and its panes, refusing once over unsaved text."}, {"name": "Detach", "leader": "SPC s D", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Detach this pardes from its terminal, leaving the session running."}, {"name": "Diagnostics", "leader": "SPC l d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the file's diagnostics from the language server."}, + {"name": "DirLook", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "pane, terminal", "doc": "A directory looked at: pane, a pane listing it as acme's directory window, or terminal, ls in a terminal there."}, {"name": "Down", "leader": "SPC w j", "also": ["C-w j", "C-w down"], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane below, off a tag onto the pane under it."}, {"name": "Dump", "leader": "SPC s d", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Write the session's panes and layout to a dump file, for Restore."}, {"name": "DumpConfig", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the settings in effect, each a word to click, and the startup file's path."}, diff --git a/docs/typ/builtins-tty.json b/docs/typ/builtins-tty.json index 6dd09882..959f88ce 100644 --- a/docs/typ/builtins-tty.json +++ b/docs/typ/builtins-tty.json @@ -23,6 +23,7 @@ {"name": "Delcol", "leader": "SPC c d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close this column and its panes, refusing once over unsaved text."}, {"name": "Detach", "leader": "SPC s D", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Detach this pardes from its terminal, leaving the session running."}, {"name": "Diagnostics", "leader": "SPC l d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the file's diagnostics from the language server."}, + {"name": "DirLook", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "pane, terminal", "doc": "A directory looked at: pane, a pane listing it as acme's directory window, or terminal, ls in a terminal there."}, {"name": "Down", "leader": "SPC w j", "also": ["C-w j", "C-w down"], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane below, off a tag onto the pane under it."}, {"name": "Dump", "leader": "SPC s d", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Write the session's panes and layout to a dump file, for Restore."}, {"name": "DumpConfig", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the settings in effect, each a word to click, and the startup file's path."}, diff --git a/docs/typ/cheatsheet.typ b/docs/typ/cheatsheet.typ index d8ea87ac..e95f5076 100644 --- a/docs/typ/cheatsheet.typ +++ b/docs/typ/cheatsheet.typ @@ -41,7 +41,7 @@ Typed anywhere, then #btn("B3") or #key("Enter"): addr(":40"), [the pane looked from, line 40 (`:40:5`, any address after `:`)], addr("~/x"), [home; also in #word("Save"), #word("Restore"), `pardes ~/x`], addr("@p3:12"), [pane 3 by serial, a terminal's lines too], - addr("src/"), [a directory: `ls` in an idle terminal there, else a new one], + addr("src/"), [a directory: a pane listing it; `Get` reads it again], ) Addresses are sam's: `#n`, `/re/`, `?re?`, `$`, `a,b`. #doc("fs", section: "look-and-exec") diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index 077c62f1..5bfff0ce 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -157,7 +157,7 @@ pardes. addr("notes.txt"), [opens it, or goes to the pane already showing it], addr("notes.txt:12"), [line 12], addr("notes.txt:/TODO/"), [the next match of `TODO`], - addr("src/"), [`ls` typed into a terminal idle there, else a new terminal there], + addr("src/"), [a pane listing it, as acme's directory window: a #word("Look") at an entry opens it, `..` goes up, `Get` reads it again (#word("DirLook") `terminal`: `ls` in a terminal there)], addr("https://ziglang.org"), [the browser, through `xdg-open` (`open` on macOS); there is no plumber], ) diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index 29f535ee..a7ac997e 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -403,6 +403,7 @@ word clicked in a tag does. The same lines go in the startup file [#word("Placement") `acme|pardes`], [`acme`: where new panes go (#doc("fs", section: "placement"))], [#word("BootShell") `keep|replace`], [`keep`; `replace` closes the untouched lone shell a dragged document lands beside], [#word("LookWord") `search|list`], [`search`: a word given to #word("Look") selects its next place, or lists all in `+Search`], + [#word("DirLook") `pane|terminal`], [`pane`: #word("Look") on a directory opens a pane listing it, as acme's directory window (#doc("reference", section: "from-acme")); `terminal` types `ls` into a terminal idle there, else opens one], [#word("TermImages") `real|petscii`], [`real`: a new terminal draws its program's kitty graphics (yazi's previews) as pixels where the shell can; #word("Petscii") flips one terminal; a tty under a terminal without kitty graphics draws them as glyph art either way], [#word("Shell") ``], [`$SHELL` when it is executable, else `/bin/sh`: the shell the next terminal and command pane run; a bare name is searched for in the usual bin directories, not `$PATH`; bare #word("Shell"): `$SHELL` if it is executable, else `/bin/sh`], [#word("DumpDir") ``], [`$XDG_DATA_HOME/pardes`, else `~/.local/share/pardes`: where #word("Dump") writes, an absolute or `~` path to a directory that may be written (made if missing); a relative one, or one under a directory that may not be written, is refused; bare returns to the default], @@ -564,7 +565,7 @@ makes its column the active one (a folded pane stays folded); `no such pane`, or while a column or workspace tag has the keyboard. *Pane ctl.* Reading it gives acme's status line: serial, tag length, body -length, isdir (0), dirty, width in cells, font, tab width, undo available, +length, isdir (1 for a directory pane, else 0), dirty, width in cells, font, tab width, undo available, redo available, then `current`/`notcurrent`, a REPL's id if bound, `collapsed` when it is, and for a PDF `fit:width|height tint:disabled|filtered|full`. It @@ -1026,13 +1027,13 @@ with Client(sys.argv[1]) as c: # a socket path, or (ip, port) [`addr` reset on first open], [#file("addr") is the pane's; no open resets it (write `0`)], [OTRUNC on `data` ignored], [`: > data` deletes the addressed text; OTRUNC on #file("body") (`9p write`) replaces it all], [event flags 1, 2, 4, 8], [1, 4 and 8; never 2, so no expansion record follows], - [`Get`], [`get` on the pane's #file("ctl")], + [`Get`], [`get` on the pane's #file("ctl"); `Get` itself only in a directory pane], [`Put`, `Delete`], [#word("Save"); a #word("Del") that does not ask], [`Snarf`, `Cut`, `Paste`], [refused: the chords, #key("y"), #key("p")], [acme's other builtins], [refused: `Putall`, `Zerox`, `Sort`, `Load`, `ID`, `Send`, `Tab`, `Indent`, `Local`, `Incl`, `Abort`], [Edit], [no `< | >`, `X`, `Y`, `b B D e r w f`, no `\1`-`\9`; an alternation takes the first branch that matches, not the longest (#doc("fs", section: "edit"))], [`win`], [#word("Tty") is a VT terminal pane; #file("pty/run") runs a line at its prompt and answers `exit N` and the output; with #word("Repl") bound, #word("Exec") on a source pane types the text into it], - [a directory window], [#word("Look") on a directory types `ls` into a terminal idle there, else opens one], + [a directory window], [as acme's: a text pane named `dir/` (#file("index") kind `text`, #file("ctl") isdir 1), its entries in columns sorted bytewise, dotfiles shown, a directory's marked `/`; blanks pad the columns where acme's tabs do; a #word("Look") at an entry is from that directory, `Get` or a look at it again reads it again, and an edit is kept until then rather than lost to a resize; never dirty, #word("Save") refuses it; #word("DirLook") `terminal` types `ls` into a terminal there instead], [the plumber], [none: #word("Look") on an `http://` or `https://` URL runs `xdg-open` (`open` on macOS); files, addresses and directories follow built-in rules], [#key("Esc") selects what was typed], [#key("Esc") leaves insert mode, or goes back a pane (#doc("tags", section: "modes"))], ) diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index 941ff2b1..6be39c7a 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,10 @@ ## 0.23 +- A look at a directory opens a pane listing it, as acme's directory + window does: its entries in columns, a directory's marked `/`. A look at + an entry opens it from there, and `Get` or a look at it again reads it + again. `DirLook terminal` types `ls` into a terminal there, as before. - Restore reads a clean file pane from disk, so a file changed since the Dump comes back as it is now. An unsaved pane keeps its text, and if its file changed on disk its first Save asks before overwriting. A dump holds diff --git a/src/Dir.zig b/src/Dir.zig new file mode 100644 index 00000000..979cd51a --- /dev/null +++ b/src/Dir.zig @@ -0,0 +1,507 @@ +//! Directory panes, acme's directory windows (plan9port acme text.c, +//! textload and textcolumnate): a look at a directory opens a pane named +//! for it with a trailing `/`, its body the directory's entries in columns +//! that fit the pane, a directory's marked with a `/`. A look at an entry +//! is a look from that directory; Get, or a look at the directory again, +//! reads it again. Otherwise it is a text pane like +Errors (Output's +//! `.dir`): searched, selected and edited as any, and never dirty. +const std = @import("std"); +const pardes = @import("pardes.zig"); +const panes = @import("panes.zig"); +const config = @import("config.zig"); +const exec = @import("exec.zig"); +const filesystem = @import("fs.zig"); +const limits = @import("memory.zig").limits; +const Pardes = pardes.Pardes; +const Pane = panes.Pane; +const File = panes.File; + +/// What a directory pane keeps of its listing, as acme's Window keeps +/// dlp/ndl: the entries, for a change of width to lay them out again. +pub const State = struct { + /// The entries, sorted, each ending in a newline; gpa-owned. + names: []u8, + /// The text width they were laid out at (none yet: the most there is), + /// and the text's revision then: a body edited since is left as it is. + width: usize = std.math.maxInt(usize), + revision: u32 = 0, +}; + +/// acme's tab in a directory window (text.c TABDIR), in cells: a column is +/// a whole number of them, at least a cell wider than its widest entry. +const tab = 3; + +/// The directory a pane named `name` works in, as acme's dirname reads a +/// window's name: a directory pane's (ending in `/`) is its own, a file's +/// the one it is in. +pub fn ofName(name: []const u8) []const u8 { + if (std.mem.endsWith(u8, name, "/")) { + const dir = std.mem.trimEnd(u8, name, "/"); + return if (dir.len == 0) "/" else dir; + } + return std.fs.path.dirname(name) orelse "/"; +} + +/// The entries of directory `dir` on this host as acme lists them +/// (plan9port lib9 dirread, acme's dircmp): every name but `.` and `..`, +/// dotfiles too; a directory's, a link to one's too, ending in `/`; sorted +/// bytewise, the `/` counted; each ending in a newline. +pub fn read(gpa: std.mem.Allocator, dir: []const u8) ![]u8 { + if (comptime !filesystem.platform_has_fs) return error.FileNotFound; + const local = filesystem.localPath(dir) orelse return error.NotLocal; + // Its own copy: the caller's may be a pane's, gone while the turn is out. + var own: [4096]u8 = undefined; + if (local.len > own.len) return error.NameTooLong; + @memcpy(own[0..local.len], local); + var entries: std.ArrayList([]u8) = .empty; + defer { + for (entries.items) |entry| gpa.free(entry); + entries.deinit(gpa); + } + var total: usize = 0; + { + pardes.turn.yield(); + defer pardes.turn.back(); + const io = std.Io.Threaded.global_single_threaded.io(); + var d = try std.Io.Dir.cwd().openDir(io, own[0..local.len], .{ .iterate = true }); + defer d.close(io); + var it = d.iterate(); + while (try it.next(io)) |entry| { + if (std.mem.eql(u8, entry.name, ".") or std.mem.eql(u8, entry.name, "..")) continue; + const is_dir = switch (entry.kind) { + .directory => true, + // Followed, as dirread's stat is: a link to a directory is one. + .sym_link, .unknown => if (d.statFile(io, entry.name, .{})) |st| st.kind == .directory else |_| false, + else => false, + }; + total += entry.name.len + 2; + if (total > limits.max_file_bytes) return error.FileTooLarge; + const name = try std.mem.concat(gpa, u8, &.{ entry.name, if (is_dir) "/" else "" }); + entries.append(gpa, name) catch |err| { + gpa.free(name); + return err; + }; + } + } + std.mem.sort([]u8, entries.items, {}, struct { + fn lt(_: void, a: []u8, b: []u8) bool { + return std.mem.lessThan(u8, a, b); + } + }.lt); + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(gpa); + try out.ensureTotalCapacity(gpa, total); + for (entries.items) |entry| { + out.appendSliceAssumeCapacity(entry); + out.appendAssumeCapacity('\n'); + } + return out.toOwnedSlice(gpa); +} + +/// `entries` in columns at most `width` cells wide, as acme's +/// textcolumnate lays them out with its 3-cell tabs: down each column +/// first, every column as wide as the widest entry and a cell more, +/// rounded up to a tab, and each row ending in a newline. Blanks pad where +/// acme's tabs do: a pardes tab is a fixed width, not a stop. +pub fn columnate(gpa: std.mem.Allocator, entries: []const []const u8, width: usize) ![]u8 { + var colw: usize = 0; + for (entries) |entry| { + const w = File.displayWidth(entry) + 1; + colw = @max(colw, (w + tab - 1) / tab * tab); + } + const ncol = if (colw == 0) 1 else @max(1, width / colw); + const nrow = (entries.len + ncol - 1) / ncol; + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(gpa); + for (0..nrow) |row| { + var j = row; + while (j < entries.len) : (j += nrow) { + try out.appendSlice(gpa, entries[j]); + if (j + nrow >= entries.len) break; + try out.appendNTimes(gpa, ' ', colw - File.displayWidth(entries[j])); + } + try out.append(gpa, '\n'); + } + return out.toOwnedSlice(gpa); +} + +/// The cells a directory pane `cols` wide lays its entries out in: what +/// is left of a row after the line numbers and the cell a wrap keeps +/// (File.wrapWidth), the numbers as wide as `count` lines would need. +fn textWidth(cols: usize, count: usize) usize { + var lines = count + 1; + var digits: usize = 1; + while (lines >= 10) : (lines /= 10) digits += 1; + return cols -| @max(config.PREFIX_W, digits + 1) -| 1; +} + +/// Lays the pane's entries out again `cols` wide, when the width they need +/// changed and the body is still theirs: a body edited since is kept, as +/// typed, until a Get or a look at the directory reads it again. +pub fn fit(p: *Pardes, pane: *Pane, cols: usize) void { + const f = if (pane.file) |*file| file else return; + const l = if (f.listing) |*listing| listing else return; + const count = std.mem.count(u8, l.names, "\n"); + const width = textWidth(cols, count); + if (f.revision != l.revision or width == l.width) return; + // Not the scratch arena: this runs from sync, on every event. + const entries = p.gpa.alloc([]const u8, count) catch return; + defer p.gpa.free(entries); + var it = std.mem.splitScalar(u8, l.names, '\n'); + for (entries) |*entry| entry.* = it.next().?; + const text = columnate(p.gpa, entries, width) catch return; + if (std.mem.eql(u8, text, f.content)) p.gpa.free(text) else { + File.setContent(p, f, text); + panes.Output.resetBody(p, pane); + } + l.width = width; + l.revision = f.revision; +} + +/// Reads pane `id`'s directory again and lays it out anew, its edits gone, +/// as acme's Get does in a directory window. +pub fn refresh(p: *Pardes, id: usize) !void { + const pane = p.panes[id] orelse return error.NoPane; + const serial = pane.serial; + const names = try read(p.gpa, ofName(pane.file.?.path)); + // The pane may have closed while the turn was out. + const now = p.panes[id] orelse return p.gpa.free(names); + if (now.serial != serial) return p.gpa.free(names); + const f = &now.file.?; + const l = &f.listing.?; + p.gpa.free(l.names); + l.names = names; + l.width = std.math.maxInt(usize); + l.revision = f.revision; + fit(p, now, now.cols); + panes.Output.resetBody(p, now); +} + +/// A look at directory `dir` (look.zig's `.dir`, with `DirLook pane`): its +/// pane, read again, or a new one, placed as a document is. +pub fn look(p: *Pardes, from: usize, dir: []const u8) void { + const name = (if (std.mem.endsWith(u8, dir, "/")) + p.gpa.dupe(u8, dir) + else + std.mem.concat(p.gpa, u8, &.{ dir, "/" })) catch |err| return p.reportError(from, "look", err); + for (p.panes, 0..) |slot, i| { + const pane = slot orelse continue; + const f = pane.file orelse continue; + if (f.listing == null or !std.mem.eql(u8, f.path, name)) continue; + p.gpa.free(name); + return show(p, from, i); + } + var said: [limits.host_path_cap + 16]u8 = undefined; + const what = std.fmt.bufPrint(&said, "look: {s}", .{name[0..@min(name.len, limits.host_path_cap)]}) catch "look"; + const names = read(p.gpa, dir) catch |err| { + p.gpa.free(name); + return p.reportError(from, what, err); + }; + const free = p.freeSlot() orelse { + p.gpa.free(name); + p.gpa.free(names); + return p.reportError(from, "look", error.NoPaneSlots); + }; + const pane = open(p, free, name, names) catch |err| return p.reportError(from, "look", err); + const failures = p.fs.failures; + exec.placeNew(p, from, from, free, .doc); + // Refused a place: that is the look's one failure. + if (p.fs.failures != failures) return; + fit(p, pane, @max(1, p.rects[free].w -| config.GUTTER)); +} + +/// A pane on directory `name` (ending in `/`) with its entries `names`, +/// both taken, in slot `id`, not yet placed and laid out. +pub fn open(p: *Pardes, id: usize, name: []u8, names: []u8) !*Pane { + errdefer p.gpa.free(name); + errdefer p.gpa.free(names); + const content = try p.gpa.dupe(u8, ""); + errdefer p.gpa.free(content); + const history = try File.History.create(p.gpa); + errdefer p.gpa.destroy(history); + const pane = try p.newDocPane(id); + pane.file = .{ + .path = name, + .content = content, + .output = .{ .from = .dir }, + .history = history, + .listing = .{ .names = names }, + }; + pane.body.cur_pinned = true; + return pane; +} + +/// The directory pane `id` read again and given the keyboard, a look at it +/// coming from pane `from`. +pub fn show(p: *Pardes, from: usize, id: usize) void { + const pane = p.panes[id] orelse return; + const serial = pane.serial; + var said: [limits.host_path_cap + 16]u8 = undefined; + const name = pane.file.?.path; + const what = std.fmt.bufPrint(&said, "look: {s}", .{name[0..@min(name.len, limits.host_path_cap)]}) catch "look"; + refresh(p, id) catch |err| return p.reportError(from, what, err); + // Closed while the turn was out: nothing to give the keyboard to. + const now = p.panes[id] orelse return; + if (now.serial == serial) p.active = id; +} + +// ---- tests ---- + +const testing = std.testing; + +fn laidOut(names: []const []const u8, width: usize) ![]u8 { + return columnate(testing.allocator, names, width); +} + +test "entries go down each column first, a column a tab wider than its widest entry, as acme's" { + // The widest, 5 cells, makes 6: two tabs. 20 cells take three columns. + const names = [_][]const u8{ "a", "bb", "ccc/", "ddddd", "e", "f", "g" }; + const text = try laidOut(&names, 20); + defer testing.allocator.free(text); + try testing.expectEqualStrings( + "a ddddd g\n" ++ + "bb e\n" ++ + "ccc/ f\n", + text, + ); +} + +test "a width that is a whole number of tabs takes one more cell, so a column never touches the next" { + // "abc" is 3 cells, a tab exactly: its column is 6, not 3. + const names = [_][]const u8{ "abc", "de", "f" }; + const text = try laidOut(&names, 12); + defer testing.allocator.free(text); + try testing.expectEqualStrings("abc f\nde\n", text); +} + +test "one column when a row has room for no more, and nothing at all for an empty directory" { + const names = [_][]const u8{ "alpha", "beta" }; + const narrow = try laidOut(&names, 4); + defer testing.allocator.free(narrow); + try testing.expectEqualStrings("alpha\nbeta\n", narrow); + const none = try laidOut(&.{}, 80); + defer testing.allocator.free(none); + try testing.expectEqualStrings("", none); +} + +test "a wide character counts its cells, not its bytes" { + // 世界 is 4 cells: its column is 6 cells, padded with two blanks. + const names = [_][]const u8{ "世界", "x" }; + const text = try laidOut(&names, 12); + defer testing.allocator.free(text); + try testing.expectEqualStrings("世界 x\n", text); +} + +test "a directory reads as acme lists it: dotfiles kept, . and .. not, directories and links to them marked, sorted bytewise" { + if (comptime !filesystem.platform_has_fs) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + const io = testing.io; + try tmp.dir.writeFile(io, .{ .sub_path = "b.txt", .data = "" }); + try tmp.dir.writeFile(io, .{ .sub_path = ".hidden", .data = "" }); + try tmp.dir.writeFile(io, .{ .sub_path = "B", .data = "" }); + try tmp.dir.createDir(io, "a", .default_dir); + try tmp.dir.createDir(io, "a.d", .default_dir); + try tmp.dir.symLink(io, "a", "link", .{ .is_directory = true }); + var buf: [4096]u8 = undefined; + const dir = buf[0..try tmp.dir.realPath(io, &buf)]; + const names = try read(testing.allocator, dir); + defer testing.allocator.free(names); + // Bytewise, as dircmp's memcmp: `.` before capitals before small + // letters, and `a.d/` before `a/` because `.` is before `/`. + try testing.expectEqualStrings(".hidden\nB\na.d/\na/\nb.txt\nlink/\n", names); +} + +test "a directory pane's directory is its own name, a file's the one it is in" { + try testing.expectEqualStrings("/a/b", ofName("/a/b/")); + try testing.expectEqualStrings("/", ofName("/")); + try testing.expectEqualStrings("/a", ofName("/a/b")); + try testing.expectEqualStrings("/", ofName("/a")); +} + +/// A session on a file in a fresh directory holding `sub/inner.txt`, +/// `top.txt` and `.dot`: the directory's path in `buf`. +fn session(tmp: *std.testing.TmpDir, buf: *[4096]u8) !struct { p: *Pardes, dir: []const u8 } { + const io = testing.io; + try tmp.dir.createDir(io, "sub", .default_dir); + try tmp.dir.writeFile(io, .{ .sub_path = "sub/inner.txt", .data = "inner\n" }); + try tmp.dir.writeFile(io, .{ .sub_path = "top.txt", .data = "top\n" }); + try tmp.dir.writeFile(io, .{ .sub_path = ".dot", .data = "" }); + const dir = buf[0..try tmp.dir.realPath(io, buf)]; + var path_buf: [4200]u8 = undefined; + const path = try std.fmt.bufPrint(&path_buf, "{s}/top.txt", .{dir}); + const p = try Pardes.init(testing.allocator, .{ .file = path, .tty_only = true, .cols = 80, .rows = 30 }); + while (p.nextEffect()) |_| {} + return .{ .p = p, .dir = dir }; +} + +/// The pane named `name`, and how many are. +fn named(p: *Pardes, name: []const u8) struct { id: ?usize, count: usize } { + var id: ?usize = null; + var count: usize = 0; + for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.file) |f| if (std.mem.eql(u8, f.path, name)) { + id = i; + count += 1; + }; + return .{ .id = id, .count = count }; +} + +test "a look at a directory opens a pane named for it with a /, its entries in columns, never dirty, its directory its own" { + if (comptime !pardes.hosted) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [4096]u8 = undefined; + const s = try session(&tmp, &buf); + defer s.p.deinit(); + const p = s.p; + pardes.look.lookAt(p, 0, s.dir); + p.sync(); + var name_buf: [4200]u8 = undefined; + const name = try std.fmt.bufPrint(&name_buf, "{s}/", .{s.dir}); + const id = named(p, name).id orelse return error.NoDirectoryPane; + try testing.expectEqual(id, p.active); + const pane = p.panes[id].?; + try testing.expectEqualStrings(".dot sub/ top.txt\n", pane.file.?.content); + try testing.expectEqualStrings(@import("tagline.zig").dir_pane_tail, @import("tagline.zig").curTail(pane)); + try testing.expectEqualStrings(s.dir, Pardes.paneDir(pane)); + // Edited, still never dirty, and no Save writes it. + try testing.expect(p.executeBuiltinLine(id, "Edit ,d")); + try testing.expectEqualStrings("", pane.file.?.content); + try testing.expect(!@import("tagline.zig").dirty(pane)); + const failures = p.fs.failures; + try testing.expect(p.executeBuiltinLine(id, "Save")); + try testing.expect(p.executeBuiltinLine(id, "Save elsewhere.txt")); + try testing.expectEqual(failures +% 2, p.fs.failures); + try testing.expect(p.panes[id].?.prompt == .none); +} + +test "a look at an entry is a look from the directory, .. goes up to the open pane, and Get or a look again reads it again" { + if (comptime !pardes.hosted) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [4096]u8 = undefined; + const s = try session(&tmp, &buf); + defer s.p.deinit(); + const p = s.p; + var name_buf: [4200]u8 = undefined; + pardes.look.lookAt(p, 0, s.dir); + p.sync(); + const top = named(p, try std.fmt.bufPrint(&name_buf, "{s}/", .{s.dir})).id.?; + // An entry that is a directory: a pane of its own. + pardes.look.lookAt(p, top, "sub/"); + p.sync(); + const sub = named(p, try std.fmt.bufPrint(&name_buf, "{s}/sub/", .{s.dir})).id orelse return error.NoSubPane; + try testing.expectEqualStrings("inner.txt\n", p.panes[sub].?.file.?.content); + // A file in it, by its name alone: that directory's file. + pardes.look.lookAt(p, sub, "inner.txt"); + p.sync(); + try testing.expect(named(p, try std.fmt.bufPrint(&name_buf, "{s}/sub/inner.txt", .{s.dir})).id != null); + // `..`: the open pane above, read again, not a second one. + try tmp.dir.writeFile(testing.io, .{ .sub_path = "new.txt", .data = "" }); + pardes.look.lookAt(p, sub, ".."); + p.sync(); + const again = named(p, try std.fmt.bufPrint(&name_buf, "{s}/", .{s.dir})); + try testing.expectEqual(@as(usize, 1), again.count); + try testing.expectEqual(top, p.active); + try testing.expect(std.mem.indexOf(u8, p.panes[top].?.file.?.content, "new.txt") != null); + // Get, in its tag or its text: read again. + try tmp.dir.writeFile(testing.io, .{ .sub_path = "sub/later.txt", .data = "" }); + try testing.expect(p.executeBuiltinLine(sub, "Get")); + try testing.expectEqualStrings("inner.txt later.txt\n", p.panes[sub].?.file.?.content); + // Get anywhere else is still the acme word pardes has not. + const failures = p.fs.failures; + try testing.expect(p.executeBuiltinLine(0, "Get")); + try testing.expect(p.fs.failures != failures); +} + +test "an exec in a directory pane runs in its directory, and its +Errors goes there" { + if (comptime !pardes.hosted) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [4096]u8 = undefined; + const s = try session(&tmp, &buf); + defer s.p.deinit(); + const p = s.p; + var name_buf: [4200]u8 = undefined; + pardes.look.lookAt(p, 0, s.dir); + p.sync(); + const sub_name = try std.fmt.bufPrint(&name_buf, "{s}/sub/", .{s.dir}); + pardes.look.lookAt(p, p.active, sub_name); + p.sync(); + const sub = named(p, sub_name).id.?; + try testing.expectEqualStrings(sub_name[0 .. sub_name.len - 1], p.execDir(sub)); + _ = @import("ninep/pane.zig").appendErrors(p, sub, "oops\n"); + var errors_buf: [4200]u8 = undefined; + try testing.expect(named(p, try std.fmt.bufPrint(&errors_buf, "{s}{s}", .{ sub_name, config.errors_buffer })).id != null); +} + +test "DirLook terminal: a look at a directory opens a terminal there, no pane listing it" { + if (comptime !pardes.hosted) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [4096]u8 = undefined; + const s = try session(&tmp, &buf); + defer s.p.deinit(); + const p = s.p; + try testing.expect(p.executeBuiltinLine(0, "DirLook terminal")); + try testing.expectEqual(config.Runtime.DirLook.terminal, p.settings.dir_look); + pardes.look.lookAt(p, 0, s.dir); + p.sync(); + var name_buf: [4200]u8 = undefined; + try testing.expectEqual(@as(usize, 0), named(p, try std.fmt.bufPrint(&name_buf, "{s}/", .{s.dir})).count); + try testing.expect(p.panes[p.active].?.isTerminal()); + try testing.expectEqualStrings(s.dir, p.panes[p.active].?.cwdSlice()); + // Bare, it steps back to pane, the default. + try testing.expect(p.executeBuiltinLine(0, "DirLook")); + try testing.expectEqual(config.Runtime.DirLook.pane, p.settings.dir_look); +} + +test "over 9P a directory pane is a text pane whose name ends in /, its body the listing, ctl's isdir 1, and get reads it again" { + if (comptime !pardes.hosted) return; + const th = @import("ninep/testing.zig"); + const tree = @import("ninep/tree.zig"); + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [4096]u8 = undefined; + const s = try session(&tmp, &buf); + defer s.p.deinit(); + const p = s.p; + var line_buf: [4200]u8 = undefined; + _ = th.wr(p, @intFromEnum(tree.TopFile.look), try std.fmt.bufPrint(&line_buf, "{s}\n", .{s.dir})); + p.sync(); + const pane = p.panes[p.active].?; + const index = th.rd(p, @intFromEnum(tree.TopFile.index), 0, 8192).bytes; + try testing.expect(std.mem.indexOf(u8, index, try std.fmt.bufPrint(&line_buf, "{d} text 0 {s}/ ", .{ pane.serial, s.dir })) != null); + try testing.expectEqualStrings(".dot sub/ top.txt\n", th.rd(p, tree.Node.of(pane.serial, .body), 0, 4096).bytes); + var fields = std.mem.tokenizeScalar(u8, th.rd(p, tree.Node.of(pane.serial, .ctl), 0, 4096).bytes, ' '); + for (0..3) |_| _ = fields.next(); + try testing.expectEqualStrings("1", fields.next().?); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "zz", .data = "" }); + try testing.expectEqual(tree.Status.ok, th.wr(p, tree.Node.of(pane.serial, .ctl), "get\n").reply.status); + const after = th.rd(p, tree.Node.of(pane.serial, .body), 0, 4096).bytes; + try testing.expect(std.mem.indexOf(u8, after, "zz") != null); + try testing.expectEqualStrings(pane.file.?.content, after); +} + +test "a directory pane lays its entries out again when its width changes, unless its text was edited" { + if (comptime !pardes.hosted) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var buf: [4096]u8 = undefined; + const s = try session(&tmp, &buf); + defer s.p.deinit(); + const p = s.p; + pardes.look.lookAt(p, 0, s.dir); + p.sync(); + const pane = p.panes[p.active].?; + // 9 cells a column: two of them want 18 cells and the line numbers. + fit(p, pane, 24); + try testing.expectEqualStrings(".dot top.txt\nsub/\n", pane.file.?.content); + fit(p, pane, 80); + try testing.expectEqualStrings(".dot sub/ top.txt\n", pane.file.?.content); + try testing.expect(p.executeBuiltinLine(p.active, "Edit 1d")); + const edited = try testing.allocator.dupe(u8, pane.file.?.content); + defer testing.allocator.free(edited); + fit(p, pane, 24); + try testing.expectEqualStrings(edited, pane.file.?.content); +} diff --git a/src/File.zig b/src/File.zig index b3c28290..eb11b0e4 100644 --- a/src/File.zig +++ b/src/File.zig @@ -84,6 +84,8 @@ pub const State = struct { mtime: u32 = 0, /// Non-null for a generated output buffer rather than an on-disk file. output: ?Output.State = null, + /// A directory pane's entries (Dir.zig), its output `.dir`. + listing: ?panes.Dir.State = null, mini: ?Mini.State = null, scroll: usize = 0, /// `line_starts[i]` is line i's byte offset. Empty means not built yet. @@ -943,6 +945,14 @@ pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { }; pane.cols = @max(1, src.cols); pane.rows = @max(1, src.rows); + // A directory pane is its directory as it is now, laid out at the next + // sync; one that cannot be read keeps the text the dump kept. + if (output) |o| if (o.from == .dir) { + const f = &pane.file.?; + if (panes.Dir.read(p.gpa, panes.Dir.ofName(path))) |names| { + f.listing = .{ .names = names, .revision = f.revision }; + } else |_| f.listing = .{ .names = &.{}, .revision = f.revision -% 1 }; + }; if (output == null and filesystem.localPath(path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true, .mode = .baseline_disk } }); // Its file gone from disk since the dump: its text is nowhere else now, // so it comes back as one deleted on disk, dirty, and Del, Exit and @@ -984,6 +994,7 @@ pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { }; p.gpa.free(file.path); p.gpa.free(file.content); + if (file.listing) |listing| p.gpa.free(listing.names); if (file.mini) |*mini| mini.deinit(p.gpa); if (file.line_starts.len > 0) p.gpa.free(file.line_starts); if (file.highlights.len > 0) p.tree_sitter_gpa.free(file.highlights); diff --git a/src/Output.zig b/src/Output.zig index 5422411f..3bae9ecf 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -31,6 +31,8 @@ pub const Origin = union(enum) { /// The panes a refusal (Exit, Restore, Del, Delcol, get) is over, kept /// in +Unsaved rather than a notice that goes. unsaved, + /// A directory's entries (Dir.zig), the pane named for it. + dir, }; pub const max_arg = dump.max_origin_arg; @@ -228,6 +230,8 @@ pub fn traits(o: Origin) Traits { .errors => .{ .name = config.errors_buffer, .doc = true }, .pdf_links => .{ .name = config.pdf_links_buffer, .steps = true, .locations = true }, .unsaved => .{ .name = config.unsaved_buffer, .doc = true }, + // Named for its directory, not a `+` name in it. + .dir => .{ .name = "", .doc = true }, .cmd => |b| builtins.registry.outputTraits(b) orelse unreachable, .query => |k| switch (k) { .hover => .{ .name = config.hover_buffer }, @@ -288,15 +292,20 @@ pub fn word(o: Origin) []const u8 { .errors => config.errors_buffer, .pdf_links => config.pdf_links_buffer, .unsaved => config.unsaved_buffer, + .dir => dir_word, }; } +/// A directory pane's origin as a dump names it. +const dir_word = "dir"; + pub fn fromWord(w: []const u8) ?Origin { if (w.len == 0) return null; if (std.mem.eql(u8, w, "/")) return .search; if (std.mem.eql(u8, w, config.errors_buffer)) return .errors; if (std.mem.eql(u8, w, config.pdf_links_buffer)) return .pdf_links; if (std.mem.eql(u8, w, config.unsaved_buffer)) return .unsaved; + if (std.mem.eql(u8, w, dir_word)) return .dir; if (std.meta.stringToEnum(Builtin, w)) |b| if (builtins.registry.outputTraits(b) != null) return .{ .cmd = b }; if (std.meta.stringToEnum(lsp.Kind, w)) |k| return .{ .query = k }; @@ -359,7 +368,7 @@ fn sortResults(arena: std.mem.Allocator, from: Origin, content: []u8, anchor: ?u => {}, else => return anchor, }, - .errors, .pdf_links, .unsaved => return anchor, + .errors, .pdf_links, .unsaved, .dir => return anchor, } if (content.len == 0) return anchor; const path_only = std.meta.eql(from, Origin{ .cmd = .Find }); @@ -666,7 +675,7 @@ pub fn openUnsaved(p: *Pardes, id: usize, content: []u8) void { return; } const pane = p.panes[id] orelse return p.gpa.free(content); - const own = if (pane.file) |f| (std.fs.path.dirname(f.path) orelse "/") else pane.cwdSlice(); + const own = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice(); // Its directory gone (or never there, a name not yet saved): the list // goes in the session's, where a look from it can still resolve. const dir = if (comptime pardes.hosted) (if (pardes.filesystem.localPath(own)) |local| (if (exec.isDirectory(local)) own else p.sessionDir()) else own) else own; @@ -820,7 +829,7 @@ pub fn openFonts(p: *Pardes, id: usize) !void { fn openStepped(p: *Pardes, id: usize, from: Origin, content: []u8) !void { errdefer p.gpa.free(content); const pane = p.panes[id] orelse return error.MissingPane; - const own = if (pane.file) |f| (std.fs.path.dirname(f.path) orelse "/") else pane.cwdSlice(); + const own = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice(); // A terminal whose shell has not said where it is yet (an init file's // word at boot): the session's directory, not `/`. const dir = if (own.len == 0) p.sessionDir() else own; diff --git a/src/builtins.zig b/src/builtins.zig index 1a2f132f..1172fa78 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1125,6 +1125,12 @@ pub const Save = struct { // silent success. if (c.pane.file == null and !c.pane.isTerminal()) return c.p.reportFailure(c.id, if (c.pane.hasPdf()) "Save: a PDF pane has no text to save" else "Save: an image pane has no text to save"); + // A directory's listing is no file to write, bare or to a path, as + // acme's Put does nothing in a directory window. + if (c.pane.file) |file| if (file.listing != null) { + var said: [limits.host_path_cap + 48]u8 = undefined; + return c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "Save: {s} is a directory", .{file.path[0..@min(file.path.len, limits.host_path_cap)]}) catch "Save: a directory pane has no file to save"); + }; const path = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); if (path.len > 0) return exec.saveTo(c.p, c.id, path); // A `+` name is a generated pane's (+Tutor), no file of its own: @@ -1505,7 +1511,7 @@ pub const LocationsConfig = struct { try c.p.locations_config.write(&out.writer); try out.writer.writeByte('\n'); const content = try out.toOwnedSlice(); - const dir = if (c.pane.file) |file| std.fs.path.dirname(file.path) orelse "/" else c.pane.cwdSlice(); + const dir = if (c.pane.file) |file| panes.Dir.ofName(file.path) else c.pane.cwdSlice(); try panes.Output.fillResults(c.p, c.id, dir, .{ .cmd = .LocationsConfig }, "", content, null); } }; @@ -2085,7 +2091,7 @@ const Board = struct { p.gpa.free(content); return error.MissingPane; }; - const dir = if (pane.file) |f| (std.fs.path.dirname(f.path) orelse "/") else pane.cwdSlice(); + const dir = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice(); try panes.Output.fillResults(p, id, dir, from, "", content, null); } diff --git a/src/config.zig b/src/config.zig index f83e7945..45deb7bb 100644 --- a/src/config.zig +++ b/src/config.zig @@ -81,6 +81,7 @@ pub const leader_path = paths: { .Placement = "cp", .BootShell = null, .LookWord = null, + .DirLook = null, .Pager = null, .PagerColor = null, .TermImages = null, @@ -296,6 +297,8 @@ pub const pdf_pane_builtins_str = "Tty PdfSections PdfTint Collapse Del"; pub const file_pane_builtins_str = "Save Tty Collapse Del"; pub const terminal_pane_builtins_str = "Tty Save Mode Filter Collapse Del"; pub const command_pane_builtins_str = "Kill Save Collapse Del"; +/// A directory pane's (Dir.zig): Get reads it again, as acme's does. +pub const dir_pane_builtins_str = "Get Tty Collapse Del"; // Each mode badge is one codepoint. pub const tag_normal = " "; @@ -774,6 +777,9 @@ pub const Runtime = struct { /// next place in that pane, wrapping; `list`, what pardes did before, /// lists every place in a +Search pane (look.zig, lookWord). look_word: LookWord = .search, + /// A directory looked at: `pane`, acme's, a pane listing it (Dir.zig); + /// `terminal`, what pardes did before, `ls` in a terminal there. + dir_look: DirLook = .pane, /// What a terminal's shell pages through (host_io.ChildEnv): `pardes`, /// PAGER and GIT_PAGER set to `pardes -`, a +Pager pane, where the /// user's environment set neither; `off`, the environment as it is. @@ -790,10 +796,11 @@ pub const Runtime = struct { pub const Placement = enum { acme, pardes }; pub const BootShell = enum { keep, replace }; pub const LookWord = enum { search, list }; + pub const DirLook = enum { pane, terminal }; pub const Pager = enum { pardes, off }; pub const TermImages = enum { real, petscii }; /// A setting that is one of a few words, each an enum field of Runtime. - pub const Choice = enum { placement, boot_shell, look_word, pager, term_images }; + pub const Choice = enum { placement, boot_shell, look_word, dir_look, pager, term_images }; /// shadow: a soft drop shadow. rim: a light hairline along the top of /// the focused pane's tag rows. auto: a shadow on a light page; on a @@ -1058,6 +1065,7 @@ pub const Runtime = struct { .{ .word = "Placement", .action = .{ .choice = .placement }, .doc = "Where a new pane goes: acme, as makenewwindow does, or pardes, the older rules." }, .{ .word = "BootShell", .action = .{ .choice = .boot_shell }, .doc = "A document dropped where a lone untouched shell stands: keep the shell, or replace it." }, .{ .word = "LookWord", .action = .{ .choice = .look_word }, .doc = "A plain word looked at: search selects its next place in the pane, list lists every place in a +Search." }, + .{ .word = "DirLook", .action = .{ .choice = .dir_look }, .doc = "A directory looked at: pane, a pane listing it as acme's directory window, or terminal, ls in a terminal there." }, .{ .word = "Pager", .action = .{ .choice = .pager }, .doc = "What a terminal's commands page through: pardes, a +Pager pane (pardes -), or off, the environment's own; for terminals started after it." }, .{ .word = "PagerColor", .action = .{ .toggle = .pager_color }, .doc = "A +Pager keeps its program's colours, on or off; for the next text paged." }, .{ .word = "TermImages", .action = .{ .choice = .term_images }, .doc = "How a new terminal draws its program's kitty graphics: real, as pixels where it can, or petscii, as glyph art." }, @@ -1745,6 +1753,7 @@ pub const Runtime = struct { .placement => "pardes", .boot_shell => "replace", .look_word => "list", + .dir_look => "terminal", .pager => "off", .term_images => "petscii", }, @@ -1817,6 +1826,7 @@ pub const Runtime = struct { .placement => "Placement pardes\n", .boot_shell => "BootShell replace\n", .look_word => "LookWord list\n", + .dir_look => "DirLook terminal\n", .pager => "Pager off\n", .term_images => "TermImages petscii\n", }, @@ -2188,7 +2198,7 @@ const doc_typ = struct { if (w.end > 0) w.writeByte(' ') catch return false; w.writeAll(x[0 .. std.mem.indexOfScalar(u8, x, '+') orelse x.len]) catch return false; } - const tags = [_][]const u8{ topbar_str, @import("tagline.zig").column_tag_default, pane_builtins_str, pdf_pane_builtins_str, file_pane_builtins_str, terminal_pane_builtins_str, command_pane_builtins_str }; + const tags = [_][]const u8{ topbar_str, @import("tagline.zig").column_tag_default, pane_builtins_str, pdf_pane_builtins_str, file_pane_builtins_str, terminal_pane_builtins_str, command_pane_builtins_str, dir_pane_builtins_str }; for (tags) |d| if (std.mem.eql(u8, d, w.buffered())) return true; return false; } diff --git a/src/exec.zig b/src/exec.zig index 8ddb9abd..92fb6244 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -968,6 +968,12 @@ pub fn executeBuiltinLine(p: *Pardes, id: usize, txt: []const u8) bool { var renamed: [1024 + 16]u8 = undefined; const cmd = for (acme_words) |w| { if (!std.mem.eql(u8, raw[0..word_end], w.acme)) continue; + // Get in a directory pane, its tag or its text: the directory read + // again (Dir.zig), as acme's Get is in a directory window. + if (std.mem.eql(u8, w.acme, "Get")) if (p.panes[id]) |pane| if (pane.file) |f| if (f.listing != null) { + panes.Dir.show(p, id, id); + return true; + }; const now = w.pardes orelse { var said: [128]u8 = undefined; p.reportFailure(id, std.fmt.bufPrint(&said, "invalid: acme's {s} is not a pardes builtin{s}", .{ w.acme, w.hint }) catch "invalid: an acme word pardes has not"); diff --git a/src/host_io.zig b/src/host_io.zig index 8ff55d74..ee503061 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -174,7 +174,7 @@ pub const Lsp = struct { errdefer gpa.free(source); const arg = try gpa.dupe(u8, req.arg); errdefer gpa.free(arg); - const declared_root = if (file) |f| std.fs.path.dirname(f.path) orelse "/" else pane.cwdSlice(); + const declared_root = if (file) |f| pardes.panes.Dir.ofName(f.path) else pane.cwdSlice(); const root = try gpa.dupe(u8, filesystem.localPath(declared_root) orelse declared_root); errdefer gpa.free(root); job.* = .{ diff --git a/src/look.zig b/src/look.zig index a358b31a..0df1f307 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1787,6 +1787,8 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { if (t.at.line > pv.page_count) return missedPage(p, id, pv.path, t.at.line); if (!pv.hitExists(p.pdf_gpa, @max(1, t.at.line), t.at.col)) return missedHit(p, id, pv.path, @max(1, t.at.line), t.at.col); }; + // A directory's pane, looked at again: read again. + if (target.file) |f| if (f.listing != null) return panes.Dir.show(p, id, t.id); const before = p.active; clearNavigationSelection(p, target); focusPaneLine(p, t.id, t.at, .center); @@ -1800,6 +1802,9 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { var said: [4200]u8 = undefined; return p.reportFailure(id, std.fmt.bufPrint(&said, "look: {s}: no such directory", .{dir[0..@min(dir.len, 4096)]}) catch "look: no such directory"); }; + // acme's: a pane listing it (Dir.zig). `DirLook terminal`, what + // pardes did before: `ls` in a terminal there. + if (p.settings.dir_look == .pane) return panes.Dir.look(p, id, dir); for (p.panes, 0..) |slot, i| { if (slot) |tt| if (std.mem.eql(u8, tt.cwdSlice(), dir) and exec.takesCommandLine(p, i)) { clearNavigationSelection(p, tt); diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 75e4b823..157bc8b9 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -385,10 +385,11 @@ fn writeQuoted(w: *std.Io.Writer, s: []const u8) !void { pub const pane_text_cap = 9 * 12 + 2 * 256 + 4 + "notcurrent ".len + 48 + "collapsed fit:height tint:filtered ".len; /// acme's winctlprint (plan9port wind.c), field for field: serial, tag -/// length, body length, isdir (0), the dirty flag, the width in cells, the -/// font, the tab width, whether Undo has a step, whether Redo has one. Then -/// pardes's own: rio's word for whether the window has the keyboard, -/// `current` or `notcurrent` (rio(4), wctl), and a REPL's id. +/// length, body length, isdir (1 for a directory pane), the dirty flag, +/// the width in cells, the font, the tab width, whether Undo has a step, +/// whether Redo has one. Then pardes's own: rio's word for whether the +/// window has the keyboard, `current` or `notcurrent` (rio(4), wctl), and +/// a REPL's id. pub fn paneText(p: *Pardes, pane: *Pane, buf: []u8) []const u8 { var w = std.Io.Writer.fixed(buf); w.print("{d:>11} {d:>11} {d:>11} {d:>11} {d:>11} {d:>11} ", .{ @@ -396,7 +397,8 @@ pub fn paneText(p: *Pardes, pane: *Pane, buf: []u8) []const u8 { pane_files.tagOf(p, pane).len, // A terminal's body is its history, read whole on an open's first read. if (pane.isTerminal()) panes.terminal.screenTextLen(pane) else pane_files.bodyOf(pane).len, - @as(u32, 0), + // A directory pane is one, as acme's isdir says. + @intFromBool(if (pane.file) |f| f.listing != null else false), @intFromBool(pane_files.dirtyOf(pane)), pane.cols, }) catch return w.buffered(); @@ -1148,6 +1150,14 @@ fn getRefused(p: *Pardes, pane: *Pane) ?[]const u8 { fn get(p: *Pardes, pane: *Pane, failed: *anyerror) u16 { const f = pane_files.fileOf(pane) orelse return 0; + // A directory pane: the directory read again (Dir.zig). + if (f.listing != null) { + panes.Dir.refresh(p, p.paneBySerial(pane.serial).?) catch |err| { + failed.* = err; + return if (err == error.FileNotFound) E.NOENT else E.IO; + }; + return 0; + } if (!panes.Output.fileTraits(f.output).saves) return 0; const bytes = fs.read(p, f.path) catch |err| { failed.* = err; @@ -2661,6 +2671,7 @@ test "a terminal told the directory it already goes by logs no rename" { test "a terminal with text typed at its prompt is never typed into: a look at its directory opens another" { const p = try th.withTerm(testing.allocator); defer p.deinit(); + p.settings.dir_look = .terminal; // `ls` in a terminal, not a directory pane const term = p.paneBySerial(serialOf(p)).?; p.setCwd(term, "/tmp"); p.update(.{ .output = .{ .pane = @intCast(term), .bytes = "\x1b]133;A;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07TYPED" } }); diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 92ce8d8a..981c2b0e 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -1014,7 +1014,7 @@ pub fn appendErrors(p: *Pardes, id: usize, text: []const u8) ?usize { if (text.len == 0) return 0; const pane = p.panes[id] orelse return null; const cwd = pane.cwdSlice(); - const dir = if (pane.file) |*f| std.fs.path.dirname(f.path) orelse "/" else if (cwd.len > 0) cwd else "/"; + const dir = if (pane.file) |*f| panes.Dir.ofName(f.path) else if (cwd.len > 0) cwd else "/"; for (p.panes) |slot| { const q = slot orelse continue; const qf = fileOf(q) orelse continue; diff --git a/src/panes.zig b/src/panes.zig index 9d1b7571..89362996 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -640,6 +640,8 @@ pub const File = @import("File.zig"); pub const Output = @import("Output.zig"); +pub const Dir = @import("Dir.zig"); + pub const mini = @import("mini.zig"); pub const Image = @import("image.zig"); @@ -653,6 +655,7 @@ test { _ = Text; _ = File; _ = Output; + _ = Dir; _ = mini; _ = Image; _ = Pdf; diff --git a/src/pardes.zig b/src/pardes.zig index 1cc1c5b8..164bc253 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -1986,6 +1986,7 @@ test "a Look on a directory does not type ls into an occupied terminal" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 100, .rows = 30 }); defer p.deinit(); + p.settings.dir_look = .terminal; // `ls` in a terminal, not a directory pane while (p.nextEffect()) |_| {} var realbuf: [4096]u8 = undefined; @@ -6433,7 +6434,7 @@ pub const Pardes = struct { .owned => |cwd| return cwd, .none => {}, } - if (pane.file) |f| return std.fs.path.dirname(f.path) orelse "/"; + if (pane.file) |f| return panes.Dir.ofName(f.path); if (comptime pdf_enabled) if (pane.pdf) |pv| return std.fs.path.dirname(pv.path) orelse "/"; if (pane.image) |iv| return std.fs.path.dirname(iv.path) orelse "/"; @@ -6807,7 +6808,7 @@ pub const Pardes = struct { return; } - const dir = if (pane.file) |f| (std.fs.path.dirname(f.path) orelse "/") else pane.cwdSlice(); + const dir = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice(); const content = p.gpa.dupe(u8, rows) catch return; const serial_before = p.next_serial; p.fs.refilled = null; @@ -7260,6 +7261,9 @@ pub const Pardes = struct { pane.rows = rows; if (pane.file) |*file| file.syntax_dirty = true; } + // A directory pane's entries follow its width, as acme's + // columns do (Dir.fit). + if (pane.file) |file| if (file.listing != null and r.h > pane.tag_rows) panes.Dir.fit(p, pane, pane.cols); panes.terminal.releasePendingCommandIfReady(p, id, pane); // The greeting `ls` of a new terminal in a directory is typed at // its shell's FIRST prompt, or never: typed later it would land diff --git a/src/tagline.zig b/src/tagline.zig index a1ce437d..d13f3c5f 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -23,6 +23,7 @@ pub const context_pane_tail = file_pane_tail ++ " TreeContext"; pub const locations_pane_tail = file_pane_tail ++ " LocationsConfig"; pub const terminal_pane_tail = " " ++ config.terminal_pane_builtins_str; pub const command_pane_tail = " " ++ config.command_pane_builtins_str; +pub const dir_pane_tail = " " ++ config.dir_pane_builtins_str; /// A file with changes it has not saved. pub fn dirty(pane: *const panes.Pane) bool { const f = pane.file orelse return false; @@ -162,6 +163,7 @@ pub fn curTail(pane: *Pane) []const u8 { pub fn defaultTail(pane: *const Pane) []const u8 { if (comptime pdf_enabled) if (pane.pdf != null) return pdf_pane_tail; + if (pane.file) |file| if (file.listing != null) return dir_pane_tail; if (pane.file) |file| if (file.output) |out| if (panes.Output.usesLocationsConfig(out.from)) return locations_pane_tail; if (panes.File.supportsContext(pane)) return context_pane_tail; diff --git a/test/fs.py b/test/fs.py index 204f4b37..65b354d9 100644 --- a/test/fs.py +++ b/test/fs.py @@ -605,6 +605,28 @@ def unattended_messages_expire(binary): assert not shown(), 'an unattended message outlived MessageLinger' +def directory_panes(binary): + """A look at a directory opens a pane listing it, as acme's directory + window: a text pane named with a trailing /, its body the entries (a + directory's marked /), ctl's isdir 1, and get reads it again.""" + with tempfile.TemporaryDirectory(prefix='pardes-dirpane-') as directory: + root = Path(directory).resolve() + listed = root / 'listed' + (listed / 'sub').mkdir(parents=True) + (listed / '.dot').write_bytes(b'') + with session(binary, root, 'dirpane') as (client, _): + serial = look(client, str(listed)) + rows = [row.split() for row in client.read('/index').decode().splitlines()] + row = next(r for r in rows if int(r[0]) == serial) + assert row[1:4] == ['text', '0', f'{listed}/'], row + body = client.read(f'/pane/{serial}/body').decode() + assert body.split() == ['.dot', 'sub/'], body + assert client.read(f'/pane/{serial}/ctl').split()[3] == b'1' + (listed / 'later').write_bytes(b'') + client.write(f'/pane/{serial}/ctl', b'get\n') + assert client.read(f'/pane/{serial}/body').decode().split() == ['.dot', 'later', 'sub/'] + + def new_terminals_named_once(binary): """A terminal started outside the session's directory is named by that directory from its `new` on: no rename to the session's and back.""" @@ -612,6 +634,9 @@ def new_terminals_named_once(binary): root = Path(directory) (root / 'sub').mkdir() with session(binary, root, 'names') as (client, _): + # A look at a directory starts a terminal there (DirLook + # terminal); DirLook pane, the default, lists it in a pane. + client.write('/ctl', b'DirLook terminal\n') made = [look(client, str(root / 'sub'))] before = {int(row.split()[0]) for row in client.read('/index').splitlines()} client.write('/pane/1/ctl', b'Tty\n') @@ -992,6 +1017,7 @@ def test(binary, quic=False): exit_answers(binary) unattended_messages_expire(binary) new_terminals_named_once(binary) + directory_panes(binary) workflow_canary(binary) recent_survives_restart(binary) python_repl_runs_one_line(binary) diff --git a/test/snapshots/cmdword.snap b/test/snapshots/cmdword.snap index 631fab8b..42a91e18 100644 --- a/test/snapshots/cmdword.snap +++ b/test/snapshots/cmdword.snap @@ -23,6 +23,9 @@ file zzmark.txt x # the top of the body -- which would move every row this script clicks. The # verbs are what is under test here, not the announcement. config Verbose off +# a directory looked at opens a terminal there (DirLook terminal), as this +# script was written for; DirLook pane, the default, is dirpane.snap's +config DirLook terminal start 31 120 cmds.txt wait 8000 Newcol Joincol wait 8000 cmds.txt diff --git a/test/snapshots/dirpane.golden b/test/snapshots/dirpane.golden new file mode 100644 index 00000000..3118079f --- /dev/null +++ b/test/snapshots/dirpane.golden @@ -0,0 +1,13 @@ +== snap dir-open grid=80x24 cursor=7,6 +|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/dirpane/cwd/top.txt Save Tty Collapse Del +| 1 sub +| +| /tmp/pardes-snap/dirpane/cwd/sub/ Get Tty Collapse Del +| 1 .hidden beta-gamma.txt inner.txt +| 2 alpha.txt deeper/ zeta +| 3 +== snap entry-open grid=80x24 cursor=7,9 +|8: /tmp/pardes-snap/dirpane/cwd/sub/inner.txt Save Tty Collapse Del +|9: 1 inner-marker diff --git a/test/snapshots/dirpane.snap b/test/snapshots/dirpane.snap new file mode 100644 index 00000000..a884b12e --- /dev/null +++ b/test/snapshots/dirpane.snap @@ -0,0 +1,27 @@ +# a look at a directory opens a pane named for it with a trailing /, its +# entries in columns as acme's directory window lays them out: down each +# column first, a directory's marked /, dotfiles shown. A look at an entry +# opens it from that directory. No shell anywhere: nothing here races a prompt. +dirmk sub +dirmk sub/deeper +file sub/inner.txt inner-marker +file sub/.hidden x +file sub/alpha.txt x +file sub/beta-gamma.txt x +file sub/zeta x +file top.txt sub +config Verbose off +start 24 80 top.txt +wait 8000 top.txt +stable 700 20000 +press right @sub 4 +release right @sub 4 +wait 8000 inner.txt +stable 700 20000 +snap dir-open +# an entry, by its name alone: sub's inner.txt +press right @inner.txt 7 +release right @inner.txt 7 +wait 8000 inner-marker +stable 700 20000 +snap entry-open diff --git a/test/snapshots/look-dir.snap b/test/snapshots/look-dir.snap index caf29da8..2032d0c0 100644 --- a/test/snapshots/look-dir.snap +++ b/test/snapshots/look-dir.snap @@ -2,6 +2,9 @@ dirmk sub file sub/inner.txt inner-marker file top.txt x +# a directory looked at opens a terminal there (DirLook terminal), as this +# script was written for; DirLook pane, the default, is dirpane.snap's +config DirLook terminal start 31 100 -n 3 wait 8000 top.txt stable 700 20000 diff --git a/test/snapshots/lookpanes.snap b/test/snapshots/lookpanes.snap index e1db907a..2834a4a9 100644 --- a/test/snapshots/lookpanes.snap +++ b/test/snapshots/lookpanes.snap @@ -24,6 +24,9 @@ file beta/bmark.txt both.txt\nb-marker # the top of the body -- which moves every row this script clicks. What the # verbs do is what is under test, not the announcement. config Verbose off +# a directory looked at opens a terminal there (DirLook terminal), as this +# script was written for; DirLook pane, the default, is dirpane.snap's +config DirLook terminal start 51 130 beta/bmark.txt wait 8000 b-marker stable 700 20000 diff --git a/test/snapshots/nested.golden b/test/snapshots/nested.golden index 07d6148d..44ab4b82 100644 --- a/test/snapshots/nested.golden +++ b/test/snapshots/nested.golden @@ -46,15 +46,15 @@ | | /tmp/pardes-snap/nested/cwd/+New Save Tty Collapse Del | 1 -== snap dir-arg grid=100x31 cursor=4,8 +== snap dir-arg grid=100x31 cursor=7,6 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol |$ /tmp/pardes-snap/nested/cwd Tty+bash Save Mode Filter Collapse Del | $ $(readlink /proc/$PPID/exe) nestdir | $ -| /tmp/pardes-snap/nested/cwd/nestdir Tty+bash Save Mode Filter Collapse Del -| ls -| inside-nested.txt +| /tmp/pardes-snap/nested/cwd/nestdir/ Get Tty Collapse Del +| 1 inside-nested.txt +| 2 | | | diff --git a/test/snapshots/ttylook.snap b/test/snapshots/ttylook.snap index 5b82bd89..91401a64 100644 --- a/test/snapshots/ttylook.snap +++ b/test/snapshots/ttylook.snap @@ -9,6 +9,9 @@ lines big.txt 40 file plain.txt just text dirmk sub +# a directory looked at opens a terminal there (DirLook terminal), as this +# script was written for; DirLook pane, the default, is dirpane.snap's +config DirLook terminal start 31 120 -n 3 wait 8000 big.txt stable 700 20000 -- cgit v1.3 From 2868516c215a96d9e1e933ded7ac5744ec16c368 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 19:20:19 -0300 Subject: Tab N sets a tab's width in cells, 1 through 16, in every pane, drawn and counted (wrapping, clicks, the cursor); bare Tab says it; the ctl read and a Dump keep it A session setting, not acme's per window: the width is read by File's pure width functions (~130 callers that are given no pane), so it is one value, config.tab_now, that Runtime.apply sets and a new session resets. A file:L:C column counts runes, as compilers do, and never depended on it. Co-Authored-By: Claude Opus 5.5 --- docs/typ/builtins-gui.json | 1 + docs/typ/builtins-tty.json | 1 + src/File.zig | 6 +++--- src/builtins.zig | 2 ++ src/config.zig | 22 ++++++++++++++++++++++ src/exec.zig | 10 ++++++++-- src/mini.zig | 4 ++-- src/ninep/ctl.zig | 7 ++++--- src/ninep/events.zig | 2 +- src/pardes.zig | 43 +++++++++++++++++++++++++++++++++++++++++++ src/surface.zig | 4 ++-- 11 files changed, 89 insertions(+), 13 deletions(-) (limited to 'src/File.zig') diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index 7674ca34..4833360e 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -117,6 +117,7 @@ {"name": "Supertypes", "leader": "SPC l t", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the supertypes of the type under the cursor."}, {"name": "Symbols", "leader": "SPC l s", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the file's symbols from the language server."}, {"name": "SyntaxBold", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Keywords and the like are drawn bold, on or off."}, + {"name": "Tab", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "A tab's width in cells, 1 through 16, in every pane; bare, it says the width."}, {"name": "Tagbottom", "leader": "SPC t b", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Each pane's tag goes at its foot rather than its head, on or off."}, {"name": "TaglineSize", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Scale the tag font, a percentage."}, {"name": "TermImages", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "real, petscii", "doc": "How a new terminal draws its program's kitty graphics: real, as pixels where it can, or petscii, as glyph art."}, diff --git a/docs/typ/builtins-tty.json b/docs/typ/builtins-tty.json index 837b2853..fa0a44a1 100644 --- a/docs/typ/builtins-tty.json +++ b/docs/typ/builtins-tty.json @@ -101,6 +101,7 @@ {"name": "Supertypes", "leader": "SPC l t", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the supertypes of the type under the cursor."}, {"name": "Symbols", "leader": "SPC l s", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the file's symbols from the language server."}, {"name": "SyntaxBold", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Keywords and the like are drawn bold, on or off."}, + {"name": "Tab", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "A tab's width in cells, 1 through 16, in every pane; bare, it says the width."}, {"name": "Tagbottom", "leader": "SPC t b", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Each pane's tag goes at its foot rather than its head, on or off."}, {"name": "TermImages", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "real, petscii", "doc": "How a new terminal draws its program's kitty graphics: real, as pixels where it can, or petscii, as glyph art."}, {"name": "Theme", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Switch to the named theme."}, diff --git a/src/File.zig b/src/File.zig index eb11b0e4..3ef1593d 100644 --- a/src/File.zig +++ b/src/File.zig @@ -311,7 +311,7 @@ test "stacked location metadata requires matching adjacent preview ownership" { } pub fn graphemeDisplayWidth(grapheme: []const u8) usize { - if (std.mem.eql(u8, grapheme, "\t")) return config.tab_width; + if (std.mem.eql(u8, grapheme, "\t")) return config.tab_now; if (grapheme.len == 1 and grapheme[0] >= 0x20 and grapheme[0] < 0x7f) return 1; if (std.unicode.utf8ValidateSlice(grapheme)) return @max(1, @as(usize, vaxis.gwidth.gwidth(grapheme, .unicode))); // vaxis's gwidth counts back a replacement rune's 3 bytes over the one @@ -346,7 +346,7 @@ test "an invalid byte in a grapheme is one cell, and never reaches vaxis's width } pub fn byteDisplayWidth(byte: u8) usize { - return if (byte == '\t') config.tab_width else 1; + return if (byte == '\t') config.tab_now else 1; } pub fn displayWidth(text: []const u8) usize { @@ -503,7 +503,7 @@ pub fn renderedLineDisplayCol(pane: *const Pane, row: i32, line_text: []const u8 test "the ASCII arm of graphemeDisplayWidth matches the gwidth it skips" { const ref = struct { fn width(grapheme: []const u8) usize { - if (std.mem.eql(u8, grapheme, "\t")) return config.tab_width; + if (std.mem.eql(u8, grapheme, "\t")) return config.tab_now; return @max(1, @as(usize, vaxis.gwidth.gwidth(grapheme, .unicode))); } }.width; diff --git a/src/builtins.zig b/src/builtins.zig index 780d0bb7..5fdabd87 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -227,6 +227,8 @@ pub const registry = struct { // are the default .toggle, .transition, .scene, .dump_dir, .choice, .lift, .shader_animation, .motion, .shell => false, .theme, .font, .tagline_size, .window_opacity, .window_blur, .message_ms, .shader, .inactive_dim, .grip_width => true, + // bare, it says the width (exec.applySettingBuiltin) + .tab => false, }; unreachable; } diff --git a/src/config.zig b/src/config.zig index 375b4c69..89e5f813 100644 --- a/src/config.zig +++ b/src/config.zig @@ -61,6 +61,7 @@ pub const leader_path = paths: { .Get = null, .Putall = null, .Incl = null, + .Tab = null, .ClipYank = "y", .ClipYankMain = "Y", .ClipPaste = "p", @@ -405,6 +406,11 @@ pub const PREFIX_W: u16 = 5; pub const default_incl = [_][]const u8{ "/usr/include", "/usr/local/include" }; pub const tab_width: u16 = 4; +/// The width a tab is drawn and counted at now: `Tab N` (Runtime.tab) sets +/// it, a new session starts it at tab_width. ponytail: one for the process, +/// as the session's setting is one; per pane would mean handing a pane to +/// every width function (File.graphemeDisplayWidth and its ~130 callers). +pub var tab_now: u16 = tab_width; comptime { if (tab_width == 0) @compileError("config.tab_width must be greater than zero"); } @@ -802,6 +808,9 @@ pub const Runtime = struct { /// the focused pane's file first, other files only once those run out /// that way; `all`, every place in the order it was jumped to. jump_scope: JumpScope = .file, + /// acme's Tab: a tab's width in cells, in every pane (config.tab_now + /// is what the drawing and the column arithmetic read). + tab: u16 = tab_width, pub const ShaderAnimation = enum { off, on, always }; pub const Placement = enum { acme, pardes }; @@ -999,6 +1008,7 @@ pub const Runtime = struct { /// A percentage, 0 through 100. inactive_dim, grip_width, + tab, transition: animation.Transition, scene: Scene, /// A Shadertoy file into the post chain or out of it; `off` empties @@ -1082,6 +1092,7 @@ pub const Runtime = struct { .{ .word = "PagerColor", .action = .{ .toggle = .pager_color }, .doc = "A +Pager keeps its program's colours, on or off; for the next text paged." }, .{ .word = "TermImages", .action = .{ .choice = .term_images }, .doc = "How a new terminal draws its program's kitty graphics: real, as pixels where it can, or petscii, as glyph art." }, .{ .word = "JumpScope", .action = .{ .choice = .jump_scope }, .doc = "What Back and Forward keep to: file, the focused pane's file until it runs out that way, or all, every place in order." }, + .{ .word = "Tab", .action = .tab, .doc = "A tab's width in cells, 1 through 16, in every pane; bare, it says the width." }, }; pub fn find(name: []const u8) ?Setting { @@ -1282,6 +1293,13 @@ pub const Runtime = struct { if (percent < 50 or percent > 300) return false; state.grip_width = percent; }, + .tab => { + const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); + const width = std.fmt.parseInt(u16, text, 10) catch return false; + if (width < 1 or width > 16) return false; + state.tab = width; + tab_now = width; + }, .theme, .font => return false, } return true; @@ -1317,6 +1335,7 @@ pub const Runtime = struct { return choices(action) orelse switch (action) { .inactive_dim, .window_opacity, .window_blur => "0-100 (a percentage)", .grip_width => "50-300 (a percentage)", + .tab => "1-16 (cells)", .tagline_size => std.fmt.comptimePrint("{d}-{d} (a percentage)", .{ tagline_percent_min, tagline_percent_max }), .message_ms => std.fmt.comptimePrint("0-{d} (milliseconds)", .{message_ms_max}), .shell => "a path of at most 255 bytes; bare, $SHELL, else /bin/sh", @@ -1479,6 +1498,7 @@ pub const Runtime = struct { try out.print("# {s} unsupported\n", .{setting.word}), .motion => try out.print("{s} {s}\n", .{ setting.word, @tagName(state.motion) }), .inactive_dim => try out.print("{s} {d}\n", .{ setting.word, state.inactive_dim }), + .tab => try out.print("{s} {d}\n", .{ setting.word, state.tab }), .grip_width => if (setting.enabled(context.capabilities)) try out.print("{s} {d}\n", .{ setting.word, state.grip_width }) else @@ -1775,6 +1795,7 @@ pub const Runtime = struct { .motion => "playful", .inactive_dim => "35", .grip_width => "200", + .tab => "8", else => null, }; try std.testing.expect(apply(&state, setting, argument)); @@ -1849,6 +1870,7 @@ pub const Runtime = struct { .motion => "Motion playful\n", .inactive_dim => "InactiveDim 35\n", .grip_width => "GripWidth 200\n", + .tab => "Tab 8\n", .theme, .font => unreachable, }; try std.testing.expect(std.mem.indexOf(u8, report, expected) != null); diff --git a/src/exec.zig b/src/exec.zig index 4bdb2584..1ee57520 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -953,7 +953,6 @@ pub const acme_words = [_]struct { acme: []const u8, pardes: ?[]const u8, hint: .{ .acme = "Load", .pardes = "Restore" }, .{ .acme = "ID", .pardes = null }, .{ .acme = "Send", .pardes = null }, - .{ .acme = "Tab", .pardes = null }, .{ .acme = "Indent", .pardes = null, .hint = ": Enter, o and O keep the indent always" }, .{ .acme = "Local", .pardes = null }, .{ .acme = "Abort", .pardes = null, .hint = ": a debugging word that crashes acme" }, @@ -1120,6 +1119,13 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] } if (!p.settings.apply(setting, want)) p.reportFailure(p.active, "Shell: takes " ++ comptime config.Runtime.takes(.shell).?); }, + // Bare, it says the width, as acme's Tab does. + .tab => if (arg == null) { + var said: [32]u8 = undefined; + return p.setMessage(p.active, std.fmt.bufPrint(&said, "Tab {d}", .{p.settings.tab}) catch "Tab"); + } else if (!p.settings.apply(setting, arg)) { + p.reportFailure(p.active, "Tab: takes " ++ comptime config.Runtime.takes(.tab).?); + }, // Said with what it takes: its words, its range. else => if (!p.settings.apply(setting, arg)) { var text: [160]u8 = undefined; @@ -1133,7 +1139,7 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] if (pane.file) |*file| file.syntax_dirty = true; } } - if (p.settings.tree_context_tag_style != previous_context_style) { + if (p.settings.tree_context_tag_style != previous_context_style or setting.action == .tab) { for (p.panes, 0..) |slot, id| { p.surface.body_layers[id].rows = 0; const pane = slot orelse continue; diff --git a/src/mini.zig b/src/mini.zig index a6aef15a..8af64201 100644 --- a/src/mini.zig +++ b/src/mini.zig @@ -239,9 +239,9 @@ test "Mini uses display cells for tabs combining text and wide characters" { } const tabs = try generate(gpa, "\tx\n", ""); defer tabs.deinit(gpa); - const spaces = config.tab_width / 2; + const spaces = config.tab_now / 2; for (tabs.content[0..spaces]) |byte| try std.testing.expectEqual(@as(u8, ' '), byte); - try std.testing.expectEqualStrings(if (config.tab_width % 2 == 0) "⠁\n" else "⠈\n", tabs.content[spaces..]); + try std.testing.expectEqualStrings(if (config.tab_now % 2 == 0) "⠁\n" else "⠈\n", tabs.content[spaces..]); } test "Mini chooses highlighted dots over plain ink with stable color ties" { diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index d0b1defb..188795de 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -409,7 +409,7 @@ pub fn paneText(p: *Pardes, pane: *Pane, buf: []u8) []const u8 { const f = pane_files.fileOf(pane); const undo = if (f) |file| file.history.undo_len > 0 else false; const redo = if (f) |file| file.history.redo_len > 0 else false; - w.print(" {d:>11} {d:>11} {d:>11} {s} ", .{ config.tab_width, @intFromBool(undo), @intFromBool(redo), if (current) "current" else "notcurrent" }) catch {}; + w.print(" {d:>11} {d:>11} {d:>11} {s} ", .{ config.tab_now, @intFromBool(undo), @intFromBool(redo), if (current) "current" else "notcurrent" }) catch {}; // A terminal bound as a REPL ends with its id, `python-a`. var idbuf: [48]u8 = undefined; const id = exec_line.replId(&idbuf, pane); @@ -632,6 +632,7 @@ pub fn writeSettingsOf(p: *Pardes, s: *const config.Runtime, w: *std.Io.Writer) .motion => try w.print("{s} {s}\n", .{ word, @tagName(s.motion) }), .inactive_dim => try w.print("{s} {d}\n", .{ word, s.inactive_dim }), .grip_width => try w.print("{s} {d}\n", .{ word, s.grip_width }), + .tab => try w.print("{s} {d}\n", .{ word, s.tab }), } } } @@ -1228,7 +1229,7 @@ test "pane ctl read is acme's fields -- index's five, width in cells, font, tab var want: std.ArrayList(u8) = .empty; defer want.deinit(gpa); try want.print(gpa, "{d:>11} {d:>11} {d:>11} {d:>11} {d:>11} {d:>11} {s} {d:>11} {d:>11} {d:>11} current ", .{ - pane.serial, pane_files.tagOf(p, pane).len, @as(usize, 2), 0, 0, pane.cols, "default", config.tab_width, 0, 0, + pane.serial, pane_files.tagOf(p, pane).len, @as(usize, 2), 0, 0, pane.cols, "default", config.tab_now, 0, 0, }); try testing.expectEqualStrings(want.items, a.bytes); try testing.expectEqual(@as(u64, a.bytes.len), call(p, .{ .tag = 1, .op = .getattr, .node = Node.of(pane.serial, .ctl) }).reply.attr.size); @@ -3210,7 +3211,7 @@ test "acme's words run as pardes's (Put is Save, Delete a Del that does not ask) const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const serial = serialOf(p); - for ([_][]const u8{ "Snarf\n", "Zerox\n", "Tab\n", "Indent\n", "Local\n", "Abort\n" }) |line| { + for ([_][]const u8{ "Snarf\n", "Zerox\n", "Indent\n", "Local\n", "Abort\n" }) |line| { for ([_]u64{ Node.of(serial, .ctl), Node.of(serial, .exec) }) |node| { const r = wr(p, node, line); try testing.expectEqual(E.INVAL, r.errno()); diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 10e91138..5b2a763e 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -1403,7 +1403,7 @@ test "a click in the body reports the offsets of the word it takes, so the recor const rect = p.rects[id]; const x0 = rect.x + config.GUTTER + config.PREFIX_W; const y0 = if (p.settings.tag_bottom) rect.y else rect.y + p.panes[id].?.tag_rows; - const tab: u16 = config.tab_width; + const tab: u16 = config.tab_now; const Click = struct { x: u16, y: u16, look: []const u8, exec: []const u8, scroll: i32 = 0 }; // Where the wrapped line's `qty` landed, as drawn. const surface = try p.render(frame.allocator()); diff --git a/src/pardes.zig b/src/pardes.zig index 36a37293..af2b80a2 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -3149,6 +3149,47 @@ test "Unicode display cells map back to body and tag byte cursors" { try std.testing.expectEqualStrings(before, tagline.curTail(pane)); } +test "Tab N draws every pane's tab N cells wide and clicks count past it; bare Tab says the width; the ctl read and a Dump keep it" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 12 }); + defer p.deinit(); + // The width is the process's: the next test starts from the default. + defer config.tab_now = config.tab_width; + const pane = try p.setTestFile("\tx = 1\n"); + try std.testing.expect(p.executeBuiltinLine(0, "Tab 8")); + try std.testing.expectEqual(@as(u16, 8), config.tab_now); + var frame = std.heap.ArenaAllocator.init(gpa); + defer frame.deinit(); + const surface = try p.render(frame.allocator()); + const rect = p.rects[0]; + const text_x = rect.x + config.GUTTER + config.PREFIX_W; + const body_y = rect.y + BOX_H; + try std.testing.expectEqualStrings("x", surface.at(text_x + 8, body_y).grapheme()); + // A click on the x is on its byte, past the tab. + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = text_x + 8, .row = body_y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = text_x + 8, .row = body_y } }); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); + // Bare, it says the width. + try std.testing.expect(p.executeBuiltinLine(0, "Tab")); + try std.testing.expectEqualStrings("Tab 8", pane.msg[0..pane.msg_len]); + // Out of range: refused, the width kept. + try std.testing.expect(p.executeBuiltinLine(0, "Tab 0")); + try std.testing.expectEqual(@as(u16, 8), config.tab_now); + // The ctl read's tab column, and a Dump's settings. + const ctl_text = pardes_ctlfs_ctlText(p, pane); + try std.testing.expect(std.mem.indexOf(u8, ctl_text, " 8 ") != null); + try dump.dumpState(p); + const restored = try dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); + defer restored.deinit(); + try std.testing.expectEqual(@as(u16, 8), restored.settings.tab); + try std.testing.expectEqual(@as(u16, 8), config.tab_now); +} + +fn pardes_ctlfs_ctlText(p: *Pardes, pane: *Pane) []const u8 { + const th = @import("ninep/testing.zig"); + return th.rd(p, ctlfs.Node.of(pane.serial, .ctl), 0, 4096).bytes; +} + test "tabbed file aligns syntax cursor and mouse at the nearest insertion gap" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 60, .rows = 12 }); @@ -4618,6 +4659,8 @@ pub const Pardes = struct { } pub fn init(gpa: std.mem.Allocator, opts: Options) !*Pardes { + // A new session draws a tab at the default until `Tab` says otherwise. + config.tab_now = config.tab_width; const p = try create(gpa, opts); errdefer p.deinit(); p.boot = Boot.of(opts); diff --git a/src/surface.zig b/src/surface.zig index a08d6831..f7cc6010 100644 --- a/src/surface.zig +++ b/src/surface.zig @@ -589,7 +589,7 @@ pub const Surface = struct { var cp = decoded orelse 0xFFFD; if (cp == '\r') continue; if (cp == '\t') { - const spaces = @min(config.tab_width, end - col); + const spaces = @min(config.tab_now, end - col); s.fill(col, y, spaces, 1, style); col += spaces; continue; @@ -714,7 +714,7 @@ test "the ASCII fast path in surface print paints what the general arm paints" { var cp = decoded orelse 0xFFFD; if (cp == '\r') continue; if (cp == '\t') { - const spaces = @min(config.tab_width, end - col); + const spaces = @min(config.tab_now, end - col); s.fill(col, y, spaces, 1, style); col += spaces; continue; -- cgit v1.3 From dce94f4453735a6f71385cc020ee79c7604609e7 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 19:50:32 -0300 Subject: Zerox opens a second pane on a file pane's buffer: one text, undo and unsaved state, a scroll and a cursor each; an edit in either is spliced into both at File.setContentSpan, O(the edit) more, and what a Save, a get, the disk watch or a rename changes on one is copied to the rest after each step Twins share the content buffer, the History and, while it is one, the line index; the other twin's cursor and scroll move past the splice as acme moves a clone's q0. Del of one twin asks nothing while another holds the text, Exit lists the text once, and a closed twin keeps a copy of its own until it is torn down. Both are in the index, each its serial, one name. An event reader on one hears no edit made through another (first cut). A dump keeps the twins as two panes on the file, not linked again. perf: edit-twin, typing beside a twin of the 50k-line file, gated within 3x of edit-char in the same run; the three baselines re-recorded for it. Co-Authored-By: Claude Opus 5.5 --- docs/typ/builtins-gui.json | 3 +- docs/typ/builtins-tty.json | 3 +- src/File.zig | 239 +++++++++++++++++++++++++++++++- src/builtins.zig | 28 ++++ src/config.zig | 1 + src/exec.zig | 1 - src/ninep/ctl.zig | 56 +++++++- src/pardes.zig | 11 ++ test/perf-baseline-gui-Debug.json | 2 +- test/perf-baseline-tty-Debug.json | 2 +- test/perf-baseline-tty-ReleaseFast.json | 2 +- test/perf.zig | 34 ++++- 12 files changed, 369 insertions(+), 13 deletions(-) (limited to 'src/File.zig') diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index 4833360e..95eeaa07 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -139,5 +139,6 @@ {"name": "WindowOpacity", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The window's opacity, a percentage."}, {"name": "Wrap", "leader": "SPC t w", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Long lines wrap onto the next row, on or off."}, {"name": "WsDiagnostics", "leader": "SPC l D", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the workspace's diagnostics from the language server."}, - {"name": "WsSymbols", "leader": "SPC l S", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Search the workspace's symbols for its argument."} + {"name": "WsSymbols", "leader": "SPC l S", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Search the workspace's symbols for its argument."}, + {"name": "Zerox", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "acme's Zerox: a second pane on this pane's file, the same text, undo and unsaved state, with a scroll and a cursor of its own (File.zerox)."} ] diff --git a/docs/typ/builtins-tty.json b/docs/typ/builtins-tty.json index fa0a44a1..887393ac 100644 --- a/docs/typ/builtins-tty.json +++ b/docs/typ/builtins-tty.json @@ -120,5 +120,6 @@ {"name": "Verbose", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A builtin says its own name on the message row as it runs, on or off."}, {"name": "Wrap", "leader": "SPC t w", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Long lines wrap onto the next row, on or off."}, {"name": "WsDiagnostics", "leader": "SPC l D", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the workspace's diagnostics from the language server."}, - {"name": "WsSymbols", "leader": "SPC l S", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Search the workspace's symbols for its argument."} + {"name": "WsSymbols", "leader": "SPC l S", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Search the workspace's symbols for its argument."}, + {"name": "Zerox", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "acme's Zerox: a second pane on this pane's file, the same text, undo and unsaved state, with a scroll and a cursor of its own (File.zerox)."} ] diff --git a/src/File.zig b/src/File.zig index 3ef1593d..522d4bd6 100644 --- a/src/File.zig +++ b/src/File.zig @@ -3,6 +3,7 @@ const panes = @import("panes.zig"); const std = @import("std"); const vaxis = @import("vaxis"); +const builtin = @import("builtin"); const pardes = @import("pardes.zig"); const config = @import("config.zig"); const Pardes = pardes.Pardes; @@ -107,6 +108,10 @@ pub const State = struct { /// to; gpa-owned ranges and the primary's index. node_history: std.ArrayList(NodeStep) = .empty, history: *History, + /// Zerox's group: the panes on one buffer share `content`, `history` + /// and (while it is the one index) `line_starts`, each with its own + /// scroll, cursor and syntax; 0, none. See `zerox`. + twin: u32 = 0, }; pub const NodeStep = struct { ranges: []modal.Selection, primary: usize }; @@ -992,11 +997,17 @@ pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { if (file.output == null) for (p.panes, 0..) |slot, id| { if (slot == pane) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); }; + // A twin's text, undo and shared index stay with the twins left. + var twins: [pardes.MAX_PANES]usize = undefined; + const ntwins = twinsOf(p, file, &twins); + const index_shared = for (twins[0..ntwins]) |id| { + if (p.panes[id].?.file.?.line_starts.ptr == file.line_starts.ptr) break true; + } else false; p.gpa.free(file.path); - p.gpa.free(file.content); + if (ntwins == 0) p.gpa.free(file.content); if (file.listing) |listing| p.gpa.free(listing.names); if (file.mini) |*mini| mini.deinit(p.gpa); - if (file.line_starts.len > 0) p.gpa.free(file.line_starts); + if (file.line_starts.len > 0 and !index_shared) p.gpa.free(file.line_starts); if (file.highlights.len > 0) p.tree_sitter_gpa.free(file.highlights); p.gpa.free(file.pager_spans); locations.freeRows(p.gpa, file.location_rows); @@ -1004,6 +1015,7 @@ pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { if (file.node_tree) |tree| syntax.freeTree(tree); for (file.node_history.items) |step| p.gpa.free(step.ranges); file.node_history.deinit(p.gpa); + if (ntwins > 0) return; for (file.history.undo[0..file.history.undo_len]) |snap| p.gpa.free(snap.content); for (file.history.redo[0..file.history.redo_len]) |snap| p.gpa.free(snap.content); p.gpa.destroy(file.history); @@ -1024,7 +1036,20 @@ pub fn setContent(p: *Pardes, f: *State, new: []u8) void { /// `setContent` for a splice that knows what it left alone at either end, /// so the line index is not found again by comparing the whole text. -pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span: ?Span) void { +pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void { + // Twins (Zerox) take the same splice: where it is, found once here when + // the caller did not say, is what the line index wants anyway. + var twins: [pardes.MAX_PANES]usize = undefined; + const ntwins = twinsOf(p, f, &twins); + const span: ?Span = span_in orelse if (ntwins > 0) spanOf(f.content, new) else null; + var moved: [pardes.MAX_PANES]struct { cursor: usize, scroll: usize } = undefined; + for (twins[0..ntwins], 0..) |id, i| { + const t = p.panes[id].?; + const tf = &t.file.?; + const at = lineStart(p.gpa, tf, @intCast(@max(0, t.body.cur_row))) + @as(usize, @intCast(@max(0, t.body.cur_col))); + moved[i] = .{ .cursor = spliced(@min(at, f.content.len), f.content.len, new.len, span.?), .scroll = spliced(lineStart(p.gpa, tf, tf.scroll), f.content.len, new.len, span.?) }; + } + const old_starts = f.line_starts.ptr; locations.freeRows(p.gpa, f.location_rows); f.location_rows = &.{}; p.gpa.free(f.pager_spans); @@ -1061,6 +1086,214 @@ pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span: ?Span) void { f.highlight_start = 0; f.syntax_dirty = true; if (std.mem.endsWith(u8, f.path, "/+Pager")) f.pager_diff = looksLikeDiff(new[0..@min(new.len, 64 * 1024)]); + for (twins[0..ntwins], 0..) |id, i| { + const t = p.panes[id].?; + const tf = &t.file.?; + // Its own index, built while the shared one was empty, goes; the + // shared one, freed above, is replaced. + if (tf.line_starts.len > 0 and tf.line_starts.ptr != old_starts) p.gpa.free(tf.line_starts); + tf.content = f.content; + tf.line_starts = f.line_starts; + tf.revision = f.revision; + tf.saved_revision = f.saved_revision; + tf.saved_hash = f.saved_hash; + tf.saved_len = f.saved_len; + tf.mtime = f.mtime; + if (tf.highlights.len > 0) p.tree_sitter_gpa.free(tf.highlights); + tf.highlights = &.{}; + tf.highlight_start = 0; + tf.syntax_dirty = true; + locations.freeRows(p.gpa, tf.location_rows); + tf.location_rows = &.{}; + if (tf.mini) |*mini| mini.deinit(p.gpa); + tf.mini = null; + for (0..t.sel.len) |button| { + t.clearPointerSelection(button); + t.sel[button].state = .none; + } + t.body.vsel.active = false; + t.body.msel.active = false; + t.body.nsel = 0; + const cursor = positionIn(p.gpa, tf, moved[i].cursor); + t.body.cur_row = @intCast(cursor.row); + t.body.cur_col = @intCast(cursor.col); + tf.scroll = positionIn(p.gpa, tf, moved[i].scroll).row; + } +} + +/// Where an offset into the old text is in the new, after the splice that +/// kept `span` at either end: past it, moved by what it added; inside it, +/// at its start, as acme moves a clone's q0 (textinsert, textdelete). +fn spliced(at: usize, old_len: usize, new_len: usize, span: Span) usize { + if (at <= span.head) return at; + if (at >= old_len - span.tail) return at - (old_len - span.tail) + (new_len - span.tail); + return span.head; +} + +/// What `old` and `new` agree on at either end. +fn spanOf(old: []const u8, new: []const u8) Span { + const n = @min(old.len, new.len); + const head = std.mem.indexOfDiff(u8, old[0..n], new[0..n]) orelse n; + var tail: usize = 0; + while (tail < n - head and old[old.len - 1 - tail] == new[new.len - 1 - tail]) tail += 1; + return .{ .head = head, .tail = tail }; +} + +fn positionIn(gpa: std.mem.Allocator, f: *State, at: usize) struct { row: usize, col: usize } { + const index = lineIndex(gpa, f) catch { + const c = modal.positionAt(f.content, at); + return .{ .row = c.row, .col = c.col }; + }; + const row = std.sort.upperBound(usize, index, at, struct { + fn order(key: usize, item: usize) std.math.Order { + return std.math.order(key, item); + } + }.order) -| 1; + return .{ .row = row, .col = at - index[row] }; +} + +/// The other panes on `f`'s buffer (Zerox), by id. +pub fn twinsOf(p: *Pardes, f: *const State, out: *[pardes.MAX_PANES]usize) usize { + if (f.twin == 0) return 0; + var n: usize = 0; + for (p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + const other = if (pane.file) |*file| file else continue; + if (other == f or other.twin != f.twin) continue; + out[n] = id; + n += 1; + } + return n; +} + +/// acme's Zerox: pane `to` made on `from`'s buffer, its text, undo and +/// dirty state shared, its scroll and cursor its own. An edit in either is +/// spliced into both (setContentSpan, O(the edit) more); what Save and the +/// disk watch change on one is copied to the others after each step +/// (syncTwins). An event reader on one hears no edit made in another. +pub fn zerox(p: *Pardes, from: usize, to: usize) !*Pane { + const src = p.panes[from].?; + const f = &src.file.?; + const path = try p.gpa.dupe(u8, f.path); + errdefer p.gpa.free(path); + if (f.twin == 0) { + const group = try p.gpa.dupe(u8, f.path); + errdefer p.gpa.free(group); + try p.twin_groups.append(p.gpa, .{ .id = p.next_twin, .saved_revision = f.saved_revision, .saved_hash = f.saved_hash, .saved_len = f.saved_len, .disk_newer = f.disk_newer, .disk_gone = f.disk_gone, .path = group }); + f.twin = p.next_twin; + p.next_twin +%= 1; + } + const pane = try p.newDocPane(to); + pane.file = .{ + .path = path, + .content = f.content, + .line_starts = f.line_starts, + .history = f.history, + .revision = f.revision, + .saved_revision = f.saved_revision, + .saved_hash = f.saved_hash, + .saved_len = f.saved_len, + .disk_newer = f.disk_newer, + .disk_gone = f.disk_gone, + .mtime = f.mtime, + .scroll = f.scroll, + .tree_context = f.tree_context, + .twin = f.twin, + }; + pane.body.cur_row = src.body.cur_row; + pane.body.cur_col = src.body.cur_col; + pane.body.cur_pinned = true; + if (filesystem.localPath(path) != null) p.emit(.{ .watch = .{ .pane = @intCast(to), .on = true } }); + return pane; +} + +/// A twin closed: it keeps a text of its own until it is torn down (a +/// retired pane is drawn going), and the twins keep the shared one, its +/// undo and its index. +pub fn leaveTwins(p: *Pardes, f: *State) void { + var twins: [pardes.MAX_PANES]usize = undefined; + const n = twinsOf(p, f, &twins); + f.twin = 0; + if (n == 0) return; + const shared_index = for (twins[0..n]) |id| { + if (p.panes[id].?.file.?.line_starts.ptr == f.line_starts.ptr) break true; + } else false; + if (shared_index) f.line_starts = &.{}; + f.content = p.gpa.dupe(u8, f.content) catch p.gpa.alloc(u8, 0) catch &.{}; + f.history = History.create(p.gpa) catch f.history; + // The one left is no twin now (syncTwins drops the group). + if (n == 1) p.panes[twins[0]].?.file.?.twin = 0; +} + +pub const TwinGroup = struct { + id: u32, + saved_revision: u32, + saved_hash: ?u64, + saved_len: ?usize, + disk_newer: ?u64, + disk_gone: bool, + path: []u8, +}; + +/// After each step: what a Save, a get, the disk watch or a rename changed +/// on one twin is copied to the others; a group down to one pane is no +/// group. O(panes) a step, and nothing at all with no twins. +pub fn syncTwins(p: *Pardes) void { + var g: usize = 0; + while (g < p.twin_groups.items.len) { + const group = &p.twin_groups.items[g]; + var members: [pardes.MAX_PANES]*State = undefined; + var n: usize = 0; + for (p.panes) |slot| { + const pane = slot orelse continue; + const f = if (pane.file) |*file| file else continue; + if (f.twin == group.id) { + members[n] = f; + n += 1; + } + } + if (n < 2) { + if (n == 1) members[0].twin = 0; + p.gpa.free(group.path); + _ = p.twin_groups.swapRemove(g); + continue; + } + for (members[0..n]) |f| { + if (f.saved_revision == group.saved_revision and f.saved_hash == group.saved_hash and f.saved_len == group.saved_len and + f.disk_newer == group.disk_newer and f.disk_gone == group.disk_gone and std.mem.eql(u8, f.path, group.path)) continue; + // This one changed: the group, and every other twin, take it. + if (!std.mem.eql(u8, f.path, group.path)) { + const path = p.gpa.dupe(u8, f.path) catch break; + p.gpa.free(group.path); + group.path = path; + } + group.saved_revision = f.saved_revision; + group.saved_hash = f.saved_hash; + group.saved_len = f.saved_len; + group.disk_newer = f.disk_newer; + group.disk_gone = f.disk_gone; + for (members[0..n]) |other| { + if (other == f) continue; + other.saved_revision = f.saved_revision; + other.saved_hash = f.saved_hash; + other.saved_len = f.saved_len; + other.disk_newer = f.disk_newer; + other.disk_gone = f.disk_gone; + if (!std.mem.eql(u8, other.path, f.path)) { + const path = p.gpa.dupe(u8, f.path) catch continue; + p.gpa.free(other.path); + other.path = path; + } + } + break; + } + // Tests hold the twins to one text, one revision, every step. + if (builtin.is_test) for (members[1..n]) |other| { + std.debug.assert(other.content.ptr == members[0].content.ptr and other.content.len == members[0].content.len); + std.debug.assert(other.revision == members[0].revision); + }; + g += 1; + } } /// Whether `head`, a text's first bytes, holds a diff: a `diff` header, or diff --git a/src/builtins.zig b/src/builtins.zig index 5fdabd87..da87ba37 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -575,6 +575,22 @@ fn warnModifiedIn(c: Ctx, asking: Pane.Discarding, which: Asked) bool { .column => |col| if ((layout.findPane(c.p, id) orelse continue).col != col) continue, } const f = pane.file orelse continue; + // Twins (Zerox) hold one text: closing one while another stays + // loses nothing, and the text is asked about once. + if (f.twin != 0) { + const asked_elsewhere = for (c.p.panes, 0..) |other_slot, other_id| { + const other = other_slot orelse continue; + const of = other.file orelse continue; + if (other_id == id or of.twin != f.twin) continue; + const closing = switch (which) { + .all => true, + .pane => |only| other_id == only, + .column => |col| if (layout.findPane(c.p, other_id)) |at| at.col == col else false, + }; + if (!closing or other_id < id) break true; + } else false; + if (asked_elsewhere) continue; + } // A +New scratch saves nowhere, but what is typed in it is as lost; // under 100 bytes it is not asked about, as acme's winclean does not // whine about a small unnamed window, nor about a command's output. @@ -1196,6 +1212,18 @@ pub const Incl = struct { } }; +/// acme's Zerox: a second pane on this pane's file, the same text, undo and +/// unsaved state, with a scroll and a cursor of its own (File.zerox). +pub const Zerox = struct { + pub fn run(c: Ctx) void { + const f = c.pane.file orelse return c.p.reportFailure(c.id, "Zerox: only a file pane takes it"); + if (f.output != null or f.listing != null or f.mini != null) return c.p.reportFailure(c.id, "Zerox: only a file pane takes it"); + const free = c.p.freeSlot() orelse return c.p.reportError(c.id, "Zerox", error.NoPaneSlots); + _ = panes.File.zerox(c.p, c.id, free) catch |err| return c.p.reportError(c.id, "Zerox", err); + exec.placeNew(c.p, c.id, c.id, free, .doc); + } +}; + /// Write the pane's text to its file, or to the file its argument names. pub const Save = struct { pub const takes_arg = true; diff --git a/src/config.zig b/src/config.zig index 89e5f813..26e1de2c 100644 --- a/src/config.zig +++ b/src/config.zig @@ -62,6 +62,7 @@ pub const leader_path = paths: { .Putall = null, .Incl = null, .Tab = null, + .Zerox = null, .ClipYank = "y", .ClipYankMain = "Y", .ClipPaste = "p", diff --git a/src/exec.zig b/src/exec.zig index 1ee57520..9aa8a8cb 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -948,7 +948,6 @@ pub const acme_words = [_]struct { acme: []const u8, pardes: ?[]const u8, hint: .{ .acme = "Snarf", .pardes = null, .hint = ": y yanks the selection" }, .{ .acme = "Cut", .pardes = null, .hint = ": d deletes the selection into a register" }, .{ .acme = "Paste", .pardes = null, .hint = ": p puts a register" }, - .{ .acme = "Zerox", .pardes = null }, .{ .acme = "Sort", .pardes = null }, .{ .acme = "Load", .pardes = "Restore" }, .{ .acme = "ID", .pardes = null }, diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 188795de..537ac4d0 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -1829,6 +1829,60 @@ test "Putall saves every pane with unsaved edits to a file, one each, and leaves try testing.expectEqual(@as(usize, 1), saves); } +test "Zerox makes a second pane on one buffer: one text, undo and dirty state, its own cursor; Save cleans both, Del of one asks nothing" { + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; + const p = try withFile(testing.allocator, "one\ntwo\nthree\n"); + defer p.deinit(); + const first = serialOf(p); + var name: [std.fs.max_path_bytes + 8]u8 = undefined; + _ = wr(p, Node.of(first, .name), try std.fmt.bufPrint(&name, "{s}/z.txt\n", .{dir})); + try testing.expect(p.executeBuiltinLine(0, "Zerox")); + const twin_id = for (p.panes, 0..) |slot, id| { + if (id != 0) if (slot) |pane| if (pane.file != null) break id; + } else return error.NoTwin; + const a = p.panes[0].?; + const b = p.panes[twin_id].?; + // Both in the index, each its serial, one name. + const index = rd(p, @intFromEnum(tree.TopFile.index), 0, 4096).bytes; + try testing.expectEqual(@as(usize, 2), std.mem.count(u8, index, "/z.txt")); + // b's cursor on `three`; a line written above it in a moves it down. + b.body.cur_row = 2; + b.body.cur_col = 1; + _ = wr(p, Node.of(first, .addr), "0"); + try testing.expectEqual(Status.ok, wr(p, Node.of(first, .data), "zero\n").reply.status); + try testing.expectEqualStrings("zero\none\ntwo\nthree\n", b.file.?.content); + try testing.expectEqual(a.file.?.content.ptr, b.file.?.content.ptr); + try testing.expectEqual(@as(i32, 3), b.body.cur_row); + try testing.expectEqual(@as(i32, 1), b.body.cur_col); + try testing.expect(pane_files.dirtyOf(a) and pane_files.dirtyOf(b)); + // A write through b is a's too; Undo in a takes it back from both. + try testing.expectEqual(Status.ok, wr(p, Node.of(b.serial, .body), "four\n").reply.status); + try testing.expectEqualStrings("zero\none\ntwo\nthree\nfour\n", a.file.?.content); + try testing.expect(p.executeBuiltinLine(0, "Undo")); + try testing.expectEqualStrings("zero\none\ntwo\nthree\n", b.file.?.content); + // Saved from b: both come clean. + try testing.expect(p.executeBuiltinLine(twin_id, "Save")); + while (p.nextEffect()) |e| p.perform(e); + try testing.expect(!pane_files.dirtyOf(a) and !pane_files.dirtyOf(b)); + try testing.expectEqualStrings("zero\none\ntwo\nthree\n", p.fallback.get(b.file.?.path).?); + // Edited again, Del of a asks nothing: b holds the text. + try testing.expectEqual(Status.ok, wr(p, Node.of(b.serial, .body), "five\n").reply.status); + const failures = p.fs.failures; + try testing.expect(p.executeBuiltinLine(0, "Del")); + p.sync(); + try testing.expectEqual(failures, p.fs.failures); + try testing.expect(p.paneBySerial(first) == null); + try testing.expect(pane_files.dirtyOf(b)); + try testing.expectEqualStrings("zero\none\ntwo\nthree\nfive\n", b.file.?.content); + // Alone now, it is no twin; Del asks about it as about any pane. + try testing.expectEqual(@as(u32, 0), b.file.?.twin); + try testing.expect(p.executeBuiltinLine(p.paneBySerial(b.serial).?, "Del")); + try testing.expect(p.fs.failures != failures); +} + test "a body write to a terminal is typed input, not a paste, even to a program that asked for bracketed paste" { const p = try Pardes.init(testing.allocator, .{ .cols = 90, .rows = 30 }); defer p.deinit(); @@ -3211,7 +3265,7 @@ test "acme's words run as pardes's (Put is Save, Delete a Del that does not ask) const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const serial = serialOf(p); - for ([_][]const u8{ "Snarf\n", "Zerox\n", "Indent\n", "Local\n", "Abort\n" }) |line| { + for ([_][]const u8{ "Snarf\n", "Indent\n", "Local\n", "Abort\n" }) |line| { for ([_]u64{ Node.of(serial, .ctl), Node.of(serial, .exec) }) |node| { const r = wr(p, node, line); try testing.expectEqual(E.INVAL, r.errno()); diff --git a/src/pardes.zig b/src/pardes.zig index af2b80a2..7ae73636 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -4369,6 +4369,10 @@ pub const Pardes = struct { /// (`stdio.h`, ``) is tried in, in order. The session's, seeded /// with C's (/usr/include, /usr/local/include), kept in a dump. incl: std.ArrayList([]u8) = .empty, + /// Zerox's groups of panes on one buffer (File.syncTwins), and the id + /// the next takes. + twin_groups: std.ArrayList(panes.File.TwinGroup) = .empty, + next_twin: u32 = 1, /// The kept list was read (or there was none): only then is it written, /// so a session never writes over one it did not read. recent_loaded: bool = false, @@ -4872,6 +4876,8 @@ pub const Pardes = struct { p.recent.deinit(p.recentGpa()); for (p.incl.items) |dir| p.gpa.free(dir); p.incl.deinit(p.gpa); + for (p.twin_groups.items) |group| p.gpa.free(group.path); + p.twin_groups.deinit(p.gpa); p.fs.batch.bytes.deinit(p.gpa); if (p.stand_in) |pane| p.teardownPane(pane); look.cancelLookHover(p); @@ -5006,6 +5012,7 @@ pub const Pardes = struct { // to it reopen it there. p.noteClosed(pane); panes.Output.dropUnsaved(p, pane); + if (pane.file) |*file| panes.File.leaveTwins(p, file); const watched = (if (pane.file) |f| f.output == null else false) or pane.hasPdf(); for (p.panes, 0..) |slot, id| if (slot == pane) { if (watched) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = false } }); @@ -5682,6 +5689,8 @@ pub const Pardes = struct { } pub fn perform(p: *Pardes, e: Effect) void { + // A Save performed on one twin is every twin's (File.syncTwins). + defer panes.File.syncTwins(p); const v = p.host.vtable; switch (e) { // The host reads the pane (its command, its shell) as it forks, @@ -5862,6 +5871,7 @@ pub const Pardes = struct { /// that changes a pane costs a frame, which is why a round trip on a /// local socket costs microseconds and not a vsync. pub fn serveFs(p: *Pardes, req: ctlfs.Req) ctlfs.Reply { + defer panes.File.syncTwins(p); if (!ctlfs.changesPane(p, req)) return ctlfs.handle(p, req); // An address, a limit or the mark flag is nothing drawn: a script's // addr write then its close costs no frame between them. @@ -5892,6 +5902,7 @@ pub const Pardes = struct { } pub fn update(p: *Pardes, ev: Event) void { + defer panes.File.syncTwins(p); defer p.reportFocus(); // A tick with nothing animating is the one event that cannot change // the screen. diff --git a/test/perf-baseline-gui-Debug.json b/test/perf-baseline-gui-Debug.json index ace9a967..39f5913c 100644 --- a/test/perf-baseline-gui-Debug.json +++ b/test/perf-baseline-gui-Debug.json @@ -1 +1 @@ -{"harness":"e63a8b27a0bcb261","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2100,"med_us":2437,"p90_us":2875,"max_us":3207},{"op":"render","fixture":"medium","min_us":82,"med_us":84,"p90_us":88,"max_us":89},{"op":"key-down","fixture":"medium","min_us":88,"med_us":95,"p90_us":102,"max_us":114},{"op":"key-right","fixture":"medium","min_us":84,"med_us":88,"p90_us":94,"max_us":105},{"op":"page-down","fixture":"medium","min_us":83,"med_us":86,"p90_us":88,"max_us":89},{"op":"wheel","fixture":"medium","min_us":82,"med_us":85,"p90_us":90,"max_us":99},{"op":"edit-char","fixture":"medium","min_us":1276,"med_us":1769,"p90_us":2239,"max_us":2754},{"op":"body-2m","fixture":"medium","min_us":5333,"med_us":9734,"p90_us":12257,"max_us":14666},{"op":"body-appends","fixture":"medium","min_us":135052,"med_us":262059,"p90_us":295829,"max_us":304576},{"op":"deep-sel","fixture":"medium","min_us":77,"med_us":79,"p90_us":83,"max_us":118}]} +{"harness":"303736f83a625e87","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1818,"med_us":2104,"p90_us":2287,"max_us":2293},{"op":"render","fixture":"medium","min_us":78,"med_us":82,"p90_us":87,"max_us":87},{"op":"key-down","fixture":"medium","min_us":79,"med_us":81,"p90_us":89,"max_us":109},{"op":"key-right","fixture":"medium","min_us":79,"med_us":84,"p90_us":85,"max_us":89},{"op":"page-down","fixture":"medium","min_us":79,"med_us":81,"p90_us":84,"max_us":87},{"op":"wheel","fixture":"medium","min_us":77,"med_us":78,"p90_us":82,"max_us":82},{"op":"edit-char","fixture":"medium","min_us":1019,"med_us":1349,"p90_us":1597,"max_us":1632},{"op":"edit-twin","fixture":"medium","min_us":2029,"med_us":2353,"p90_us":2455,"max_us":2676},{"op":"body-2m","fixture":"medium","min_us":5978,"med_us":9708,"p90_us":11361,"max_us":11666},{"op":"body-appends","fixture":"medium","min_us":117933,"med_us":211247,"p90_us":268014,"max_us":275006},{"op":"deep-sel","fixture":"medium","min_us":73,"med_us":75,"p90_us":80,"max_us":84}]} diff --git a/test/perf-baseline-tty-Debug.json b/test/perf-baseline-tty-Debug.json index 6b5c0bd5..9110398c 100644 --- a/test/perf-baseline-tty-Debug.json +++ b/test/perf-baseline-tty-Debug.json @@ -1 +1 @@ -{"harness":"e63a8b27a0bcb261","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1830,"med_us":2222,"p90_us":2264,"max_us":2287},{"op":"render","fixture":"medium","min_us":78,"med_us":83,"p90_us":86,"max_us":94},{"op":"key-down","fixture":"medium","min_us":80,"med_us":84,"p90_us":89,"max_us":98},{"op":"key-right","fixture":"medium","min_us":78,"med_us":81,"p90_us":88,"max_us":96},{"op":"page-down","fixture":"medium","min_us":78,"med_us":82,"p90_us":89,"max_us":95},{"op":"wheel","fixture":"medium","min_us":77,"med_us":85,"p90_us":96,"max_us":109},{"op":"edit-char","fixture":"medium","min_us":1125,"med_us":1307,"p90_us":1558,"max_us":1584},{"op":"body-2m","fixture":"medium","min_us":5189,"med_us":9224,"p90_us":10859,"max_us":14741},{"op":"body-appends","fixture":"medium","min_us":108477,"med_us":198709,"p90_us":227756,"max_us":252672},{"op":"deep-sel","fixture":"medium","min_us":73,"med_us":77,"p90_us":80,"max_us":91}]} +{"harness":"303736f83a625e87","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"Debug","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseSafe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1881,"med_us":2148,"p90_us":2324,"max_us":2644},{"op":"render","fixture":"medium","min_us":79,"med_us":87,"p90_us":90,"max_us":93},{"op":"key-down","fixture":"medium","min_us":81,"med_us":84,"p90_us":86,"max_us":90},{"op":"key-right","fixture":"medium","min_us":80,"med_us":85,"p90_us":89,"max_us":102},{"op":"page-down","fixture":"medium","min_us":85,"med_us":86,"p90_us":88,"max_us":88},{"op":"wheel","fixture":"medium","min_us":79,"med_us":85,"p90_us":90,"max_us":91},{"op":"edit-char","fixture":"medium","min_us":1037,"med_us":1300,"p90_us":1639,"max_us":1647},{"op":"edit-twin","fixture":"medium","min_us":2046,"med_us":2378,"p90_us":2529,"max_us":2585},{"op":"body-2m","fixture":"medium","min_us":5790,"med_us":9510,"p90_us":12226,"max_us":12462},{"op":"body-appends","fixture":"medium","min_us":132421,"med_us":224849,"p90_us":257368,"max_us":274890},{"op":"deep-sel","fixture":"medium","min_us":75,"med_us":80,"p90_us":84,"max_us":86}]} diff --git a/test/perf-baseline-tty-ReleaseFast.json b/test/perf-baseline-tty-ReleaseFast.json index 87a31754..4cbc8b95 100644 --- a/test/perf-baseline-tty-ReleaseFast.json +++ b/test/perf-baseline-tty-ReleaseFast.json @@ -1 +1 @@ -{"harness":"e63a8b27a0bcb261","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2042,"med_us":2280,"p90_us":2451,"max_us":2478},{"op":"render","fixture":"medium","min_us":82,"med_us":84,"p90_us":87,"max_us":104},{"op":"key-down","fixture":"medium","min_us":83,"med_us":86,"p90_us":90,"max_us":93},{"op":"key-right","fixture":"medium","min_us":84,"med_us":87,"p90_us":91,"max_us":104},{"op":"page-down","fixture":"medium","min_us":84,"med_us":87,"p90_us":93,"max_us":96},{"op":"wheel","fixture":"medium","min_us":81,"med_us":85,"p90_us":89,"max_us":89},{"op":"edit-char","fixture":"medium","min_us":1309,"med_us":1613,"p90_us":1840,"max_us":2128},{"op":"body-2m","fixture":"medium","min_us":5386,"med_us":11064,"p90_us":11706,"max_us":12374},{"op":"body-appends","fixture":"medium","min_us":144772,"med_us":232307,"p90_us":273586,"max_us":281169},{"op":"deep-sel","fixture":"medium","min_us":79,"med_us":83,"p90_us":87,"max_us":130}]} +{"harness":"303736f83a625e87","build":{"compiler":"0.16.0","target":"x86_64-linux.5.10...6.19-gnu.2.38","cpu":"x86_64","driver_optimize":"ReleaseFast","core_optimize":"ReleaseFast","c_optimize":"ReleaseFast","terminal_optimize":"ReleaseFast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1775,"med_us":1995,"p90_us":2092,"max_us":2094},{"op":"render","fixture":"medium","min_us":80,"med_us":86,"p90_us":89,"max_us":95},{"op":"key-down","fixture":"medium","min_us":81,"med_us":83,"p90_us":95,"max_us":101},{"op":"key-right","fixture":"medium","min_us":79,"med_us":84,"p90_us":85,"max_us":98},{"op":"page-down","fixture":"medium","min_us":80,"med_us":82,"p90_us":96,"max_us":97},{"op":"wheel","fixture":"medium","min_us":78,"med_us":80,"p90_us":87,"max_us":88},{"op":"edit-char","fixture":"medium","min_us":1036,"med_us":1377,"p90_us":1602,"max_us":1621},{"op":"edit-twin","fixture":"medium","min_us":2266,"med_us":2715,"p90_us":3695,"max_us":3927},{"op":"body-2m","fixture":"medium","min_us":4739,"med_us":8675,"p90_us":11518,"max_us":13657},{"op":"body-appends","fixture":"medium","min_us":111613,"med_us":214959,"p90_us":264859,"max_us":283506},{"op":"deep-sel","fixture":"medium","min_us":74,"med_us":76,"p90_us":89,"max_us":96}]} diff --git a/test/perf.zig b/test/perf.zig index 94076a25..c9235954 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -46,6 +46,9 @@ const Op = enum { page_down, wheel, edit_char, + /// edit_char with a Zerox twin open on the same file: the twin takes + /// the splice, not a copy of the text (File.setContentSpan). + edit_twin, /// 2 MB appended to the file through 9P, on one open, in 256 KB /// writes: linear, not a copy of the whole buffer per write. body_write, @@ -67,6 +70,7 @@ const Op = enum { .page_down => "page-down", .wheel => "wheel", .edit_char => "edit-char", + .edit_twin => "edit-twin", .body_write => "body-2m", .body_appends => "body-appends", .deep_selection => "deep-sel", @@ -511,6 +515,19 @@ fn gate(cells: *const [std.enums.values(Op).len][fixtures.len]Cell, base: *const failed = true; } }; + // Typing beside a twin costs about what typing alone does, whatever the + // baseline: the twin takes the splice, never a copy of the text. + const twin_op = @intFromEnum(Op.edit_twin); + const alone_op = @intFromEnum(Op.edit_char); + for (fixtures, 0..) |fx, fi| { + const twin = cells[twin_op][fi].min_us; + const alone = cells[alone_op][fi].min_us; + if (twin == 0 or alone == 0) continue; + if (@as(f64, @floatFromInt(twin)) > ratio * @as(f64, @floatFromInt(alone))) { + std.debug.print("perf gate: edit-twin on {s} took {d} us at best, over {d:.1}x edit-char's {d} us\n", .{ fx.name, twin, ratio, alone }); + failed = true; + } + } if (failed) return error.PerformanceRegression; std.debug.print("perf gate: every cell within {d:.1}x of the baseline\n", .{ratio}); } @@ -545,7 +562,13 @@ fn measure(op: Op, fx: Fixture, path: []const u8, expected_bytes: usize, reps: u core.active = id; const pane = core.panes[id].?; _ = try frame(core); - if (op == .edit_char) { + if (op == .edit_twin) { + if (!core.executeBuiltinLine(id, "Zerox")) return error.ZeroxRefused; + pump(core); + core.active = id; + _ = try frame(core); + } + if (op == .edit_char or op == .edit_twin) { core.update(.{ .key = .{ .cp = 'i', .text = "i" } }); pump(core); } @@ -572,7 +595,7 @@ fn measure(op: Op, fx: Fixture, path: []const u8, expected_bytes: usize, reps: u .key_right => core.update(.{ .key = .{ .cp = 'l', .text = "l" } }), .page_down => core.update(.{ .key = .{ .cp = pardes.Key.page_down } }), .wheel => core.update(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = wheel_col, .row = wheel_row } }), - .edit_char => core.update(.{ .key = .{ .cp = 'x', .text = "x" } }), + .edit_char, .edit_twin => core.update(.{ .key = .{ .cp = 'x', .text = "x" } }), .body_write => bodyWrite(core, pane.serial), .body_appends => bodyAppends(core, pane.serial), } @@ -591,11 +614,16 @@ fn measure(op: Op, fx: Fixture, path: []const u8, expected_bytes: usize, reps: u return error.PageDidNotScroll, .wheel => if (pane.scroll() <= before.scroll and before.scroll < @as(i32, @intCast(fx.lines)) - pane.rows) return error.WheelDidNotScroll, - .edit_char => { + .edit_char, .edit_twin => { if (pane.file.?.content.len != before.len + 1 or pane.body.cur_row != before.row or pane.body.cur_col != before.col + 1) return error.CharacterWasNotInserted; const line = pardes.panes.File.sourceLine(pane, before.row); if (line[@intCast(before.col)] != 'x') return error.CharacterWasNotInserted; + if (op == .edit_twin) for (core.panes, 0..) |slot, other| { + const twin = slot orelse continue; + if (other == id or twin.file == null or twin.file.?.twin != pane.file.?.twin) continue; + if (twin.file.?.content.ptr != pane.file.?.content.ptr) return error.TwinMissedTheEdit; + } else if (pane.file.?.twin == 0) return error.NoTwin; }, } if (n >= warmup) samples[n - warmup] = dt / 1000; -- cgit v1.3 From 081e1b9ab9d3bb8afaae8ea040c7767cb6e4f863 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 20:50:11 -0300 Subject: Undo after Get file or Edit's e puts the old name back with the old text and its clean state, so a Save or Putall after it writes nothing over the loaded file; a Get file that fails, or is asked about unsaved edits, renames nothing; Get file in a directory pane is refused with how to open it ctl.getFile is the one load-under-a-name path: it reads first, then makes one undo step (whose snapshot now keeps the name and its saved state), renames and loads, and leaves the pane clean. Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 86 ++++++++++++++++++++++++++++++++------------ src/builtins.zig | 20 +++++------ src/ninep/ctl.zig | 105 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 178 insertions(+), 33 deletions(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index 522d4bd6..0f1579b2 100644 --- a/src/File.zig +++ b/src/File.zig @@ -32,8 +32,58 @@ pub const Snapshot = struct { cur_row: i32, cur_col: i32, vsel: Text.CharSel, + /// The name the text had then (owned), and whether and as what it was + /// saved under it: an undo across a load into the pane under another + /// name (Get file, Edit's e) puts the name back with the text, and the + /// dirty state that went with them, as acme's undo does. + path: ?[]u8 = null, + clean: bool = false, + saved_hash: ?u64 = null, + saved_len: ?usize = null, + + fn deinit(s: Snapshot, gpa: std.mem.Allocator) void { + gpa.free(s.content); + if (s.path) |path| gpa.free(path); + } }; +/// The pane's text, place and name now, for an undo or redo step. +fn snapshotOf(gpa: std.mem.Allocator, pane: *const Pane, f: *const State) ?Snapshot { + const content = gpa.dupe(u8, f.content) catch return null; + const path = gpa.dupe(u8, f.path) catch { + gpa.free(content); + return null; + }; + return .{ + .content = content, + .cur_row = pane.body.cur_row, + .cur_col = pane.body.cur_col, + .vsel = pane.body.vsel, + .path = path, + .clean = f.revision == f.saved_revision, + .saved_hash = f.saved_hash, + .saved_len = f.saved_len, + }; +} + +/// After a step's text went in: if it was under another name, that name +/// back, and the step's saved state with it (Get file, Edit's e). +fn restoreName(p: *Pardes, pane: *Pane, f: *State, snap: Snapshot) void { + defer if (snap.path) |path| p.gpa.free(path); + const path = snap.path orelse return; + if (std.mem.eql(u8, path, f.path)) return; + const id = for (p.panes, 0..) |slot, i| { + if (slot == pane) break i; + } else return; + pardes.ctlfs.pane.nameBuffer(p, id, path, false) catch return; + f.saved_hash = snap.saved_hash; + f.saved_len = snap.saved_len; + f.saved_revision = if (snap.clean) f.revision else f.revision -% 1; + f.disk_newer = null; + f.disk_newer_warned = false; + if (filesystem.localPath(path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } }); +} + pub const History = struct { undo: [limits.undo_max]Snapshot = undefined, undo_len: usize = 0, @@ -1016,8 +1066,8 @@ pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { for (file.node_history.items) |step| p.gpa.free(step.ranges); file.node_history.deinit(p.gpa); if (ntwins > 0) return; - for (file.history.undo[0..file.history.undo_len]) |snap| p.gpa.free(snap.content); - for (file.history.redo[0..file.history.redo_len]) |snap| p.gpa.free(snap.content); + for (file.history.undo[0..file.history.undo_len]) |snap| snap.deinit(p.gpa); + for (file.history.redo[0..file.history.redo_len]) |snap| snap.deinit(p.gpa); p.gpa.destroy(file.history); } @@ -1340,7 +1390,7 @@ pub fn restoreSnap(pane: *Pane, f: *State, snap: Snapshot) void { fn pushHistory(gpa: std.mem.Allocator, slots: []Snapshot, len: *usize, snap: Snapshot) void { if (len.* == slots.len) { - gpa.free(slots[0].content); + slots[0].deinit(gpa); std.mem.copyForwards(Snapshot, slots[0 .. slots.len - 1], slots[1..]); len.* -= 1; } @@ -1351,15 +1401,13 @@ fn pushHistory(gpa: std.mem.Allocator, slots: []Snapshot, len: *usize, snap: Sna pub fn pushUndo(p: *Pardes, pane: *Pane) void { const f = if (pane.file) |*file| file else return; const history = f.history; - if (history.undo_len > 0 and std.mem.eql(u8, history.undo[history.undo_len - 1].content, f.content)) return; - const snap: Snapshot = .{ - .content = p.gpa.dupe(u8, f.content) catch return, - .cur_row = pane.body.cur_row, - .cur_col = pane.body.cur_col, - .vsel = pane.body.vsel, - }; + if (history.undo_len > 0) { + const last = history.undo[history.undo_len - 1]; + if (std.mem.eql(u8, last.content, f.content) and std.mem.eql(u8, last.path orelse f.path, f.path)) return; + } + const snap = snapshotOf(p.gpa, pane, f) orelse return; pushHistory(p.gpa, &history.undo, &history.undo_len, snap); - for (history.redo[0..history.redo_len]) |item| p.gpa.free(item.content); + for (history.redo[0..history.redo_len]) |item| item.deinit(p.gpa); history.redo_len = 0; } @@ -1367,16 +1415,12 @@ pub fn undo(p: *Pardes, pane: *Pane) void { const f = if (pane.file) |*file| file else return; const history = f.history; if (history.undo_len == 0) return; - const current: Snapshot = .{ - .content = p.gpa.dupe(u8, f.content) catch return, - .cur_row = pane.body.cur_row, - .cur_col = pane.body.cur_col, - .vsel = pane.body.vsel, - }; + const current = snapshotOf(p.gpa, pane, f) orelse return; pushHistory(p.gpa, &history.redo, &history.redo_len, current); history.undo_len -= 1; const previous = history.undo[history.undo_len]; setContent(p, f, previous.content); + restoreName(p, pane, f, previous); restoreSnap(pane, f, previous); } @@ -1384,16 +1428,12 @@ pub fn redo(p: *Pardes, pane: *Pane) void { const f = if (pane.file) |*file| file else return; const history = f.history; if (history.redo_len == 0) return; - const current: Snapshot = .{ - .content = p.gpa.dupe(u8, f.content) catch return, - .cur_row = pane.body.cur_row, - .cur_col = pane.body.cur_col, - .vsel = pane.body.vsel, - }; + const current = snapshotOf(p.gpa, pane, f) orelse return; pushHistory(p.gpa, &history.undo, &history.undo_len, current); history.redo_len -= 1; const next = history.redo[history.redo_len]; setContent(p, f, next.content); + restoreName(p, pane, f, next); restoreSnap(pane, f, next); } diff --git a/src/builtins.zig b/src/builtins.zig index ed6ac467..129dd659 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1142,21 +1142,21 @@ pub const Get = struct { pub fn run(c: Ctx) void { const ctl = @import("ninep/ctl.zig"); const f = if (c.pane.file) |*file| file else return c.p.reportFailure(c.id, "Get: only a file pane takes it"); + const typed = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); // A directory pane: the directory read again (Dir.zig), as acme's - // Get is in a directory window. - if (f.listing != null) return panes.Dir.show(c.p, c.id, c.id); + // Get is in a directory window; a file is a Look's from there. + if (f.listing != null) { + if (typed.len > 0) return c.p.reportFailure(c.id, "Get: a directory pane reads its directory; a Look at the file opens it"); + return panes.Dir.show(c.p, c.id, c.id); + } if (!panes.Output.fileTraits(f.output).saves) return c.p.reportFailure(c.id, "Get: only a file pane takes it"); if (ctl.getRefused(c.p, c.pane, "Get")) |said| return c.p.reportFailure(c.id, said); - const typed = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); - if (typed.len > 0) { - var home_buf: [4096]u8 = undefined; - const full = std.fs.path.resolvePosix(c.p.scratch.allocator(), &.{ Pardes.paneDir(c.pane), @import("fs.zig").expandHome(typed, &home_buf) }) catch return; - @import("ninep/pane.zig").nameBuffer(c.p, c.id, full, false) catch return c.p.reportFailure(c.id, "Get: invalid file name"); - } var failed: anyerror = error.Unexpected; - if (ctl.get(c.p, c.pane, &failed) != 0) { + var home_buf: [4096]u8 = undefined; + const path = if (typed.len == 0) c.pane.file.?.path else std.fs.path.resolvePosix(c.p.scratch.allocator(), &.{ Pardes.paneDir(c.pane), @import("fs.zig").expandHome(typed, &home_buf) }) catch return; + const errno = if (typed.len == 0) ctl.get(c.p, c.pane, &failed) else ctl.getFile(c.p, c.pane, path, &failed); + if (errno != 0) { var said: [320]u8 = undefined; - const path = c.pane.file.?.path; c.p.reportFailure(c.id, std.fmt.bufPrint(&said, "Get: {s}: {s}", .{ path[0..@min(path.len, 256)], if (failed == error.FileNotFound) "no such file" else "cannot be read" }) catch "Get: cannot be read"); } } diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index ac5d64d8..973f87e2 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -1159,6 +1159,38 @@ pub fn getRefused(p: *Pardes, pane: *Pane, word: []const u8) ?[]const u8 { return std.fmt.bufPrint(&p.fs.ename, "{s}: Modified ({s} again to discard)", .{ f.path, word }) catch "Modified (get again to discard)"; } +/// acme's `Get file`, and Edit's `e file`: the file at `path` (absolute) +/// loaded into the pane, which takes its name, in one undo step that puts +/// the old name back with the old text. Read first, so one that cannot be +/// read changes nothing; loaded, the pane is clean. Asking about unsaved +/// edits is the caller's (getRefused). Returns an errno, 0 when loaded. +pub fn getFile(p: *Pardes, pane: *Pane, path: []const u8, failed: *anyerror) u16 { + const f = pane_files.fileOf(pane) orelse return E.INVAL; + const id = p.paneBySerial(pane.serial) orelse return E.NOENT; + const bytes = fs.read(p, path) catch |err| { + failed.* = err; + return switch (err) { + error.FileNotFound => E.NOENT, + else => E.IO, + }; + }; + panes.File.pushUndo(p, pane); + pane_files.nameBuffer(p, id, path, false) catch |err| { + p.gpa.free(bytes); + failed.* = err; + return E.INVAL; + }; + panes.File.setContent(p, f, bytes); + f.saved_revision = f.revision; + f.saved_hash = std.hash.Wyhash.hash(0, f.content); + f.saved_len = f.content.len; + f.disk_newer = null; + f.disk_newer_warned = false; + f.disk_gone = false; + if (fs.localPath(path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } }); + return 0; +} + pub fn get(p: *Pardes, pane: *Pane, failed: *anyerror) u16 { const f = pane_files.fileOf(pane) orelse return 0; // A directory pane: the directory read again (Dir.zig). @@ -1890,6 +1922,79 @@ test "Zerox makes a second pane on one buffer: one text, undo and dirty state, i try testing.expect(p.fs.failures != failures); } +test "Undo after a load under another name (Get file, Edit e) puts the old name back with the old text and its clean state; Putall then writes nothing over the loaded file" { + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "other.txt", .data = "other\n" }); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "keep.txt", .data = "keep\n" }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; + var other_buf: [4200]u8 = undefined; + const other = try std.fmt.bufPrint(&other_buf, "{s}/other.txt", .{dir}); + var keep_buf: [4200]u8 = undefined; + const keep = try std.fmt.bufPrint(&keep_buf, "{s}/keep.txt", .{dir}); + for ([_][]const u8{ "Get keep.txt", "Edit e keep.txt" }) |load| { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + const serial = serialOf(p); + const pane = p.panes[0].?; + var name: [4300]u8 = undefined; + _ = wr(p, Node.of(serial, .name), try std.fmt.bufPrint(&name, "{s}\n", .{other})); + try testing.expect(p.executeBuiltinLine(0, "Get")); + try testing.expectEqualStrings("other\n", pane.file.?.content); + try testing.expect(!pane_files.dirtyOf(pane)); + // Loaded: keep.txt's text under its name. + try testing.expect(p.executeBuiltinLine(0, load)); + try testing.expectEqualStrings("keep\n", pane.file.?.content); + try testing.expectEqualStrings(keep, pane.file.?.path); + if (std.mem.startsWith(u8, load, "Get")) try testing.expect(!pane_files.dirtyOf(pane)); + // Undo: other.txt's text, other.txt's name, clean as it was. + try testing.expect(p.executeBuiltinLine(0, "Undo")); + try testing.expectEqualStrings("other\n", pane.file.?.content); + try testing.expectEqualStrings(other, pane.file.?.path); + try testing.expect(!pane_files.dirtyOf(pane)); + // Putall saves nothing, and nothing lands on keep.txt. + while (p.nextEffect()) |_| {} + try testing.expect(p.executeBuiltinLine(0, "Putall")); + while (p.nextEffect()) |e| try testing.expect(e != .save_file); + // Redo: keep.txt again. + try testing.expect(p.executeBuiltinLine(0, "Redo")); + try testing.expectEqualStrings(keep, pane.file.?.path); + try testing.expectEqualStrings("keep\n", pane.file.?.content); + } +} + +test "a Get file that fails changes nothing: no such file, a directory, or unsaved edits asked about once" { + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "here.txt", .data = "here\n" }); + try tmp.dir.createDirPath(testing.io, "sub"); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + const serial = serialOf(p); + const pane = p.panes[0].?; + var name: [4300]u8 = undefined; + const here = try std.fmt.bufPrint(&name, "{s}/here.txt\n", .{dir}); + _ = wr(p, Node.of(serial, .name), here); + try testing.expect(p.executeBuiltinLine(0, "Get")); + const undo_len = pane.file.?.history.undo_len; + for ([_][]const u8{ "Get nosuch.txt", "Get sub" }) |line| { + const failures = p.fs.failures; + try testing.expect(p.executeBuiltinLine(0, line)); + try testing.expect(p.fs.failures != failures); + try testing.expectEqualStrings(here[0 .. here.len - 1], pane.file.?.path); + try testing.expectEqualStrings("here\n", pane.file.?.content); + try testing.expectEqual(undo_len, pane.file.?.history.undo_len); + } + // Edited, the first Get asks and renames nothing. + _ = wr(p, Node.of(serial, .body), "more\n"); + try testing.expect(p.executeBuiltinLine(0, "Get other.txt")); + try testing.expectEqualStrings(here[0 .. here.len - 1], pane.file.?.path); + try testing.expectEqualStrings("here\nmore\n", pane.file.?.content); +} + test "a body write to a terminal is typed input, not a paste, even to a program that asked for bracketed paste" { const p = try Pardes.init(testing.allocator, .{ .cols = 90, .rows = 30 }); defer p.deinit(); -- cgit v1.3 From 778de441bc5645bf15ba8d3dff83766fbb70499e Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 20:53:19 -0300 Subject: Zerox twins survive a Dump and Restore: their text is dumped once, in the first, each other twin names it (twin_of), and Restore puts them back on one buffer with their dots Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 41 +++++++++++++++++++++++++++++++++++++++++ src/dump.zig | 26 +++++++++++++++++++++++++- src/ninep/ctl.zig | 30 ++++++++++++++++++++++++++++++ 3 files changed, 96 insertions(+), 1 deletion(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index 0f1579b2..e5805134 100644 --- a/src/File.zig +++ b/src/File.zig @@ -1275,6 +1275,47 @@ pub fn leaveTwins(p: *Pardes, f: *State) void { if (n == 1) p.panes[twins[0]].?.file.?.twin = 0; } +/// Restore's: pane `id`, restored on its own, back on pane `of`'s buffer +/// as the Zerox twin it was dumped as (dump.File.twin_of). Not a file pane +/// there (a dump edited by hand), it stays on its own. +pub fn relink(p: *Pardes, of: usize, id: usize, dot: ?[2]u32) void { + const src = p.panes[of] orelse return; + const pane = p.panes[id] orelse return; + const sf = if (src.file) |*file| file else return; + const f = if (pane.file) |*file| file else return; + if (sf.output != null or f.output != null or sf.mini != null) return; + if (sf.twin == 0) { + const group = p.gpa.dupe(u8, sf.path) catch return; + p.twin_groups.append(p.gpa, .{ .id = p.next_twin, .saved_revision = sf.saved_revision, .saved_hash = sf.saved_hash, .saved_len = sf.saved_len, .disk_newer = sf.disk_newer, .disk_gone = sf.disk_gone, .path = group }) catch return p.gpa.free(group); + sf.twin = p.next_twin; + p.next_twin +%= 1; + } + p.gpa.free(f.content); + if (f.line_starts.len > 0) p.gpa.free(f.line_starts); + for (f.history.undo[0..f.history.undo_len]) |snap| snap.deinit(p.gpa); + for (f.history.redo[0..f.history.redo_len]) |snap| snap.deinit(p.gpa); + p.gpa.destroy(f.history); + f.content = sf.content; + f.line_starts = sf.line_starts; + f.history = sf.history; + f.revision = sf.revision; + f.saved_revision = sf.saved_revision; + f.saved_hash = sf.saved_hash; + f.saved_len = sf.saved_len; + f.twin = sf.twin; + if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); + f.highlights = &.{}; + f.syntax_dirty = true; + // Its dot as dumped, read now that its text is back. + if (dot) |d| if (d[0] <= d[1] and d[1] <= f.content.len) { + const a = modal.positionAt(f.content, d[0]); + const h = modal.positionAt(f.content, if (d[1] > d[0]) modal.prevGrapheme(f.content, d[1]) else d[0]); + pane.body.vsel = .{ .active = d[1] > d[0], .row = @intCast(a.row), .col = @intCast(a.col), .explicit = true }; + pane.body.cur_row = @intCast(h.row); + pane.body.cur_col = @intCast(h.col); + }; +} + pub const TwinGroup = struct { id: u32, saved_revision: u32, diff --git a/src/dump.zig b/src/dump.zig index b64441d3..1ded9989 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -232,6 +232,9 @@ pub const File = struct { /// Its dot, q0 and q1 in bytes, as acme's dump keeps a window's; null /// in older dumps. dot: ?[2]u32 = null, + /// A Zerox twin: the index, in `panes`, of the earlier pane whose + /// buffer it shares, its text kept there once; null for none. + twin_of: ?u32 = null, }; pub const ImagePalette = enum { @@ -767,6 +770,22 @@ pub fn dumpState(p: *Pardes) !void { dump_panes[panes_len] = dp; panes_len += 1; } + // Zerox's twins: the text once, in the first; each other names it. + for (p.panes, 0..) |slot, id| { + const f = (slot orelse continue).file orelse continue; + if (f.twin == 0) continue; + const i = slot_to_pane[id] orelse continue; + for (p.panes[0..id], 0..) |earlier, j_id| { + const of = (earlier orelse continue).file orelse continue; + if (of.twin != f.twin) continue; + const j = slot_to_pane[j_id] orelse break; + if (dump_panes[i].file) |*df| { + df.twin_of = @intCast(j); + df.content_b64 = ""; + } + break; + } + } var columns: [MAX_COLS]Column = undefined; var columns_len: usize = 0; @@ -963,7 +982,12 @@ fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previo if (t.petscii and pardes.panes.terminal.petscii(restored) == false) pardes.panes.terminal.togglePetscii(restored); break :terminal restored; }, - .file => try pardes.panes.File.restore(p, i, src), + .file => file: { + const restored = try pardes.panes.File.restore(p, i, src); + // A twin: on the earlier pane's buffer again. + if (src.file.?.twin_of) |j| if (j < i) pardes.panes.File.relink(p, j, i, src.file.?.dot); + break :file restored; + }, .image => restore_image: { const im = src.image.?; if (pardes.panes.Pdf.isPath(im.path)) { diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 973f87e2..ae68ed91 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -1995,6 +1995,36 @@ test "a Get file that fails changes nothing: no such file, a directory, or unsav try testing.expectEqualStrings("here\nmore\n", pane.file.?.content); } +test "Zerox twins dump their text once and come back on one buffer from a Restore" { + const p = try withFile(testing.allocator, "one\ntwo\n"); + defer p.deinit(); + const first = serialOf(p); + _ = wr(p, Node.of(first, .name), "/tmp/pardes-zerox-dump.txt\n"); + _ = wr(p, Node.of(first, .body), "unsaved " ** 64 ++ "\n"); + try testing.expect(p.executeBuiltinLine(0, "Zerox")); + try testing.expect(p.executeBuiltinLine(0, "Zerox")); + try pardes.dump.dumpState(p); + const text = p.dump_out.?; + // The text is kept once though three panes show it. + const encoded = try pardes.dump.encodeBytes(p.scratch.allocator(), p.panes[0].?.file.?.content); + try testing.expectEqual(@as(usize, 1), std.mem.count(u8, text, encoded)); + const restored = try pardes.dump.restore(p, text, "/tmp/pardes.dump.zon"); + defer restored.deinit(); + var files: [3]*pardes.panes.File.State = undefined; + var n: usize = 0; + for (restored.panes) |slot| if (slot) |pane| if (pane.file) |*f| if (std.mem.eql(u8, f.path, "/tmp/pardes-zerox-dump.txt")) { + files[n] = f; + n += 1; + }; + try testing.expectEqual(@as(usize, 3), n); + for (files[1..]) |f| { + try testing.expectEqual(files[0].content.ptr, f.content.ptr); + try testing.expectEqual(files[0].history, f.history); + try testing.expect(f.twin != 0 and f.twin == files[0].twin); + } + try testing.expect(std.mem.startsWith(u8, files[0].content, "one\ntwo\nunsaved ")); +} + test "a body write to a terminal is typed input, not a paste, even to a program that asked for bracketed paste" { const p = try Pardes.init(testing.allocator, .{ .cols = 90, .rows = 30 }); defer p.deinit(); -- cgit v1.3 From b55cb01d2777760ed79b545dfca7115837591577 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 21:55:57 -0300 Subject: An undo step keeps no copy of the name: History keeps each name once, at the rename that ends it, and a step its generation, so typing allocates a snapshot and nothing more (follows prwqwwxt); a rename of one Zerox twin is logged for each twin Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 81 +++++++++++++++++++++++++++++++++++++----------------- src/ninep/pane.zig | 3 +- 2 files changed, 58 insertions(+), 26 deletions(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index e5805134..0d62e09b 100644 --- a/src/File.zig +++ b/src/File.zig @@ -32,50 +32,66 @@ pub const Snapshot = struct { cur_row: i32, cur_col: i32, vsel: Text.CharSel, - /// The name the text had then (owned), and whether and as what it was - /// saved under it: an undo across a load into the pane under another - /// name (Get file, Edit's e) puts the name back with the text, and the - /// dirty state that went with them, as acme's undo does. - path: ?[]u8 = null, + /// The pane's name then, as History.gen counts its renames, and whether + /// and as what the text was saved under it: an undo across a load into + /// the pane under another name (Get file, Edit's e) puts the name back + /// with the text, and the dirty state that went with them, as acme's + /// undo does. No allocation a step: a name is kept once, at its rename. + gen: u32 = 0, clean: bool = false, saved_hash: ?u64 = null, saved_len: ?usize = null, fn deinit(s: Snapshot, gpa: std.mem.Allocator) void { gpa.free(s.content); - if (s.path) |path| gpa.free(path); } }; /// The pane's text, place and name now, for an undo or redo step. fn snapshotOf(gpa: std.mem.Allocator, pane: *const Pane, f: *const State) ?Snapshot { - const content = gpa.dupe(u8, f.content) catch return null; - const path = gpa.dupe(u8, f.path) catch { - gpa.free(content); - return null; - }; return .{ - .content = content, + .content = gpa.dupe(u8, f.content) catch return null, .cur_row = pane.body.cur_row, .cur_col = pane.body.cur_col, .vsel = pane.body.vsel, - .path = path, + .gen = f.history.gen, .clean = f.revision == f.saved_revision, .saved_hash = f.saved_hash, .saved_len = f.saved_len, }; } +/// A rename (ninep/pane.zig nameBuffer): the name it ends, kept for an undo +/// back across it; `old` is the History's from here (owned), freed if it +/// cannot be kept. +pub fn noteRenamed(gpa: std.mem.Allocator, history: *History, old: []u8) void { + history.names.append(gpa, .{ .gen = history.gen, .path = old }) catch gpa.free(old); + history.gen +%= 1; +} + /// After a step's text went in: if it was under another name, that name /// back, and the step's saved state with it (Get file, Edit's e). fn restoreName(p: *Pardes, pane: *Pane, f: *State, snap: Snapshot) void { - defer if (snap.path) |path| p.gpa.free(path); - const path = snap.path orelse return; - if (std.mem.eql(u8, path, f.path)) return; + const history = f.history; + if (snap.gen == history.gen) return; + // The latest name kept for that generation. + var at = history.names.items.len; + const path = while (at > 0) { + at -= 1; + if (history.names.items[at].gen == snap.gen) break history.names.items[at].path; + } else return; + if (std.mem.eql(u8, path, f.path)) { + history.gen = snap.gen; + return; + } const id = for (p.panes, 0..) |slot, i| { if (slot == pane) break i; } else return; - pardes.ctlfs.pane.nameBuffer(p, id, path, false) catch return; + // nameBuffer frees nothing of `path`: it keeps the name it ends. + const back = p.gpa.dupe(u8, path) catch return; + defer p.gpa.free(back); + pardes.ctlfs.pane.nameBuffer(p, id, back, false) catch return; + history.gen = snap.gen; f.saved_hash = snap.saved_hash; f.saved_len = snap.saved_len; f.saved_revision = if (snap.clean) f.revision else f.revision -% 1; @@ -90,12 +106,27 @@ pub const History = struct { redo: [limits.undo_max]Snapshot = undefined, redo_len: usize = 0, + /// The names the file had, each with the rename generation it ended + /// (Snapshot.gen), and the generation now. + names: std.ArrayList(struct { gen: u32, path: []u8 }) = .empty, + gen: u32 = 0, + pub fn create(gpa: std.mem.Allocator) !*History { const history = try gpa.create(History); history.undo_len = 0; history.redo_len = 0; + history.names = .empty; + history.gen = 0; return history; } + + pub fn destroy(history: *History, gpa: std.mem.Allocator) void { + for (history.undo[0..history.undo_len]) |snap| snap.deinit(gpa); + for (history.redo[0..history.redo_len]) |snap| snap.deinit(gpa); + for (history.names.items) |name| gpa.free(name.path); + history.names.deinit(gpa); + gpa.destroy(history); + } }; /// A file pane's backing: owned content, its derived caches, and undo history. @@ -1066,9 +1097,7 @@ pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { for (file.node_history.items) |step| p.gpa.free(step.ranges); file.node_history.deinit(p.gpa); if (ntwins > 0) return; - for (file.history.undo[0..file.history.undo_len]) |snap| snap.deinit(p.gpa); - for (file.history.redo[0..file.history.redo_len]) |snap| snap.deinit(p.gpa); - p.gpa.destroy(file.history); + file.history.destroy(p.gpa); } fn reportEdit(p: *Pardes, f: *State, new: []const u8) void { @@ -1292,9 +1321,7 @@ pub fn relink(p: *Pardes, of: usize, id: usize, dot: ?[2]u32) void { } p.gpa.free(f.content); if (f.line_starts.len > 0) p.gpa.free(f.line_starts); - for (f.history.undo[0..f.history.undo_len]) |snap| snap.deinit(p.gpa); - for (f.history.redo[0..f.history.redo_len]) |snap| snap.deinit(p.gpa); - p.gpa.destroy(f.history); + f.history.destroy(p.gpa); f.content = sf.content; f.line_starts = sf.line_starts; f.history = sf.history; @@ -1334,12 +1361,14 @@ pub fn syncTwins(p: *Pardes) void { while (g < p.twin_groups.items.len) { const group = &p.twin_groups.items[g]; var members: [pardes.MAX_PANES]*State = undefined; + var member_panes: [pardes.MAX_PANES]*Pane = undefined; var n: usize = 0; for (p.panes) |slot| { const pane = slot orelse continue; const f = if (pane.file) |*file| file else continue; if (f.twin == group.id) { members[n] = f; + member_panes[n] = pane; n += 1; } } @@ -1363,7 +1392,7 @@ pub fn syncTwins(p: *Pardes) void { group.saved_len = f.saved_len; group.disk_newer = f.disk_newer; group.disk_gone = f.disk_gone; - for (members[0..n]) |other| { + for (members[0..n], member_panes[0..n]) |other, other_pane| { if (other == f) continue; other.saved_revision = f.saved_revision; other.saved_hash = f.saved_hash; @@ -1374,6 +1403,8 @@ pub fn syncTwins(p: *Pardes) void { const path = p.gpa.dupe(u8, f.path) catch continue; p.gpa.free(other.path); other.path = path; + // Renamed, each twin says so, as the one renamed did. + pardes.ctlfs.events.noteLog(p, .rename, other_pane); } } break; @@ -1444,7 +1475,7 @@ pub fn pushUndo(p: *Pardes, pane: *Pane) void { const history = f.history; if (history.undo_len > 0) { const last = history.undo[history.undo_len - 1]; - if (std.mem.eql(u8, last.content, f.content) and std.mem.eql(u8, last.path orelse f.path, f.path)) return; + if (std.mem.eql(u8, last.content, f.content) and last.gen == history.gen) return; } const snap = snapshotOf(p.gpa, pane, f) orelse return; pushHistory(p.gpa, &history.undo, &history.undo_len, snap); diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 981c2b0e..3b70d62f 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -982,7 +982,8 @@ pub fn nameBuffer(p: *Pardes, id: usize, full: []const u8, preserve_tag: bool) ! if (std.mem.indexOfAny(u8, full, "\x00\n") != null) return error.InvalidName; if (std.mem.eql(u8, f.path, full)) return; const copy = try p.gpa.dupe(u8, full); - p.gpa.free(f.path); + // The name it ends is kept for an undo back across this rename. + panes.File.noteRenamed(p.gpa, f.history, f.path); f.path = copy; if (panes.Output.fileTraits(f.output).saves) { f.output = null; -- cgit v1.3 From dc4dd3bc25b11721ab3ad3fccbaea1de54b9fb90 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 1 Oct 2026 22:52:51 -0300 Subject: A file whose disk text is what its unsaved pane was read or saved as is no change on disk: an Undo back across Get file or Edit's e to unsaved edits no longer says the file changed, and Save writes it Co-Authored-By: Claude Opus 5.5 --- src/File.zig | 3 +++ src/ninep/ctl.zig | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index 0d62e09b..875d0f46 100644 --- a/src/File.zig +++ b/src/File.zig @@ -1538,6 +1538,9 @@ pub fn changed(p: *Pardes, id: u8, bytes: []const u8) void { if (std.mem.eql(u8, f.content, bytes)) return; if (f.saved_hash) |saved| if (f.revision != f.saved_revision and std.hash.Wyhash.hash(0, f.content) != saved) { const disk = std.hash.Wyhash.hash(0, bytes); + // The disk holds what the text was read or saved as: no news, only + // a watch looking again (an undo back to this name, a restart). + if (disk == saved) return; if (f.disk_newer == disk) return; f.disk_newer = disk; f.disk_newer_warned = false; diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 917c9c39..c6b76d51 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -2073,6 +2073,39 @@ test "a bad Tab width and a bad Incl directory are refused invalid, changing not try testing.expect(th.logHas(p, try std.fmt.bufPrint(&rec, "rename {d} /tmp/pardes-twin-renamed.txt\n", .{twin}))); } +test "Undo to unsaved text under its old name says nothing changed on disk when nothing did, and Save then writes" { + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "e.txt", .data = "e\n" }); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "b.txt", .data = "b\n" }); + var dir_buf: [4096]u8 = undefined; + const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; + for ([_][]const u8{ "Get b.txt", "Edit e b.txt" }) |load| { + const p = try withFile(testing.allocator, "x\n"); + defer p.deinit(); + const serial = serialOf(p); + const pane = p.panes[0].?; + var name: [4300]u8 = undefined; + _ = wr(p, Node.of(serial, .name), try std.fmt.bufPrint(&name, "{s}/e.txt\n", .{dir})); + try testing.expect(p.executeBuiltinLine(0, "Get")); + _ = wr(p, Node.of(serial, .body), "appended\n"); + // Asked once, then loaded. + try testing.expect(p.executeBuiltinLine(0, load)); + try testing.expect(p.executeBuiltinLine(0, load)); + try testing.expectEqualStrings("b\n", pane.file.?.content); + try testing.expect(p.executeBuiltinLine(0, "Undo")); + try testing.expectEqualStrings("e\nappended\n", pane.file.?.content); + try testing.expect(pane_files.dirtyOf(pane)); + // The watch looks again at e.txt, as it was all along. + pardes.panes.File.changed(p, 0, "e\n"); + try testing.expectEqual(@as(?u64, null), pane.file.?.disk_newer); + try testing.expect(!th.logHas(p, "changed on disk")); + // A change there is still news. + pardes.panes.File.changed(p, 0, "someone else\n"); + try testing.expect(pane.file.?.disk_newer != null); + } +} + test "a body write to a terminal is typed input, not a paste, even to a program that asked for bracketed paste" { const p = try Pardes.init(testing.allocator, .{ .cols = 90, .rows = 30 }); defer p.deinit(); -- cgit v1.3 From 046979b877f02a91cf52cc86b84c5619cb9363d3 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 6 Oct 2026 19:06:32 -0300 Subject: Def and Refs in a language-served file's tag, a diff viewer's tinted word edits, context rows that hold still under a scroll, and the pardes skill Def and Refs (gd, gr, Ctrl-click; chorded 2-1 at the selection) for a file a language server speaks for; hunks.zig stacks a unified diff as a diff viewer does, its changed words on a tinted ground as delta's do; the tree-sitter context rows stay put while the body glides under a scroll; .agents/skills gains the pardes skill beside pardes-9p. --- .agents/skills/pardes-9p/SKILL.md | 110 +++-- .agents/skills/pardes/SKILL.md | 131 ++++++ docs/typ/builtins-gui.json | 6 +- docs/typ/builtins-tty.json | 6 +- docs/typ/guide.typ | 15 +- docs/typ/reference.typ | 27 +- docs/typ/setup.typ | 2 +- src/CHANGELOG.md | 6 + src/File.zig | 69 ++- src/Output.zig | 90 +++- src/builtins.zig | 49 +- src/config.zig | 27 +- src/edit_cmd.zig | 2 + src/gui/gui.zig | 69 ++- src/hunks.zig | 808 +++++++++++++++++++++++++++++++++ src/locations.zig | 4 +- src/look.zig | 12 + src/main.zig | 2 +- src/mouse.zig | 2 +- src/ninep/ctl.zig | 41 +- src/ninep/tree.zig | 2 +- src/normal.zig | 17 +- src/pardes.zig | 115 ++++- src/syntax.zig | 17 +- src/tagline.zig | 18 +- src/terminal.zig | 42 +- test/snapshots/diffview.golden | 6 +- test/snapshots/lsp-client-edit.golden | 8 +- test/snapshots/lsp-client.golden | 4 +- test/snapshots/lsp-rename-files.golden | 4 +- test/snapshots/lsp-rename.golden | 6 +- test/snapshots/lsp.golden | 4 +- test/snapshots/lspcomplete.golden | 10 +- test/snapshots/lspcompletemoved.golden | 2 +- test/snapshots/lspdebug.golden | 2 +- test/snapshots/lsprelpath.golden | 8 +- test/snapshots/ninep.golden | 18 +- test/snapshots/pagercolor.golden | 35 +- test/snapshots/selregex.golden | 6 +- test/snapshots/syntax.golden | 30 +- 40 files changed, 1625 insertions(+), 207 deletions(-) create mode 100644 .agents/skills/pardes/SKILL.md create mode 100644 src/hunks.zig (limited to 'src/File.zig') diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index 06edbdf2..2b80c975 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -1,54 +1,104 @@ --- name: pardes-9p -description: Inspect and drive a running Pardes editor through its virtual filesystem (served over 9P), or exercise its panes, builtins, terminal input and rendered output in an isolated session. Use for Pardes interaction, plugin development and end-to-end debugging. +description: Script and drive a running pardes session through its virtual filesystem (served over 9P), or exercise its panes, builtins, terminals, events and rendered screen in an isolated session. Use for reading or editing panes, opening files at places, running commands and reading their output, event helpers and tag words, plugin development and end-to-end debugging. For what pardes is and its keys, use the pardes skill. --- -# Pardes over 9P +# pardes over 9P -Pardes is files: `cat`, `echo >`, `ls` and shell scripts are the whole -interface. The recipes are in the Scripting chapter -([docs/typ/scripting.typ](../../../docs/typ/scripting.typ)), every file's -semantics in the Reference chapter -([docs/typ/reference.typ](../../../docs/typ/reference.typ)), and a running -session serves a summary at `$m/README`. Paths are relative to the -repository root. +pardes is files: `cat`, `echo >`, `ls` and shell scripts are the whole +interface. The recipes and traps are the Scripting chapter +(`docs/typ/scripting.typ`), every file's semantics, refusals and limits the +Reference chapter (`docs/typ/reference.typ`; its "The tree" lists every +file), and a running session serves a one-screen summary at `$m/README`. +Paths are relative to the pardes source tree, the repository this skill +lives in (`readlink -f` this skill's directory if it is reached through a +symlink). ## Find the session +First check that you run inside a live session (the pardes skill's "Am I +in a pardes session?"); a session merely listed under `$NINE_MOUNT/pardes/` +is someone's, not yours to script. + ```sh m=${PARDES_MOUNT:-} [ -n "$m" ] || echo 'no mount: use 9p -a "unix!$PARDES_9P" read index' -cat "$m/index" +cat "$m/index" # serial kind(text|term|cmd|pdf|image) dirty name column ``` Under `9ns --mntgen` every pane gets `$PARDES_MOUNT`, its session as a -directory (also in a `Tty9p` shell). `$PARDES_9P` is the session socket of -the pane you run in, `$PARDES_PANE` that pane's serial. A dead session's -entry answers `Input/output error`: name the session, never glob. Without a -mount, plan9port's `9p -a "unix!$PARDES_9P"` works, and `test/ninep.py` in the source tree (Reference, "Other ways in"). +directory (also in a `Tty9p` shell). `$PARDES_9P` is the session socket, +`$PARDES_PANE` the serial of the pane the shell runs in, `$winid` the pane +a command was clicked in. Without a mount, `cat $m/x` is +`9p -a "unix!$PARDES_9P" read x` (its `write` truncates: on `body` it +replaces the text), and `test/ninep.py` is a Python client for holding a +fid open (Reference, "Other ways in"). A dead session's registry entry +answers `Input/output error`: name the session, never glob. + +## Recipes + +Work through a pane of your own, its own `look` and `exec`: + +```sh +n=$(cat $m/pane/new); p=$m/pane/$n # read pane/new once: each open makes a pane +exec 3<>$p/look; echo "$PWD/main.zig:120" >&3; cat <&3; exec 3<&- # open at a place; read: its pane +printf 'hello\n' > $p/body; echo "$PWD/x.txt" > $p/name; echo Save > $p/ctl +echo 'Msg hello' > $p/exec # a builtin, or else a shell line +echo 'Edit ,x/foo/c/bar/' > $p/ctl # sam's Edit, one undo step +echo /old/ > $p/addr && printf new > $p/data # replace the next match +t=$(awk '$2=="term"{print $1; exit}' $m/index) # a shell (bash or fish) +exec 3<>$m/pane/$t/pty/run; echo make >&3; cat <&3; exec 3<&- # exit N, then output +exec 3<>$m/log; echo 'follow new' >&3; timeout 30 cat <&3; exec 3<&- +rmdir $p # close it +``` + +The Scripting chapter has the rest: a command pane's output, typing into +a terminal, the language server, a tag word on `PATH` (`Fmt`), and event +helpers that own clicks through `pane//event`. ## Traps - A refused write says only `Invalid argument` or `Input/output error`; `grep '^err' $m/log | tail -1` says why. Not the log's last line: after - a refused Del, Exit or Restore that may be `+Unsaved`'s `new`. -- Work through a pane of your own (`n=$(cat $m/pane/new)`) and its own - `look` and `exec`: the root's act at the pane with the keyboard, which another - client, an idle shell or an event helper may own. -- `head` on `index`, `layout`, `log` or `recent` through 9ns says `Illegal - seek`: use `sed -n 1p`. In `index`, `term` is a shell, `cmd` a command's - pane. + a refused Del, Exit or Restore that may be `+Unsaved`'s `new`. A write + that succeeds logs nothing. +- The root `look` and `exec` act at the pane with the keyboard, which + another client, an idle shell or an event helper may own: use a pane's. +- Read `look`, `exec` or `pager` on the open you wrote (`exec 3<>…`): a + fresh open reads the session's last answer, from whichever client. +- A command pane your `exec` open was answered is yours while that open + stays open: read its `body` before you close it. - `addr` is the pane's and moves on: each `/re/` searches from the last address, and a `data` write leaves it just past the text. Write `addr` before each replacement; a failed address leaves none. - An Edit `x` that matches nothing succeeds: check the text afterwards. -- Each open of `pane/new` makes a pane: read it once. -- Through a mount, `printf 'a\nb\n' > ctl` arrives one write per line: send - a block as one write (`cat block > $p/ctl`), ending in a newline. +- Through a mount, `printf 'a\nb\n' > ctl` arrives one write per line: + send a block as one write, ending in a newline (a last line without one + runs after the close, its failure only in the log). +- Read `event` on a descriptor your shell owns (`exec 3<>$p/event`), + never `cat $p/event | while read`: the `cat` outlives the loop and + swallows the next click. +- The session has 64 open records shared by every client (held reads, + write opens of command files, snapshots): close what you open. +- `head` on `index`, `layout`, `log` or `recent` through 9ns says `Illegal + seek`: use `sed -n 1p`. - Pane words (`Save`, `Undo`, `Del`) go to `pane//ctl`, settings and - session words to `$m/ctl`. -- `Exit`, `Restore`, `Del` and `get` refuse once over unsaved text. -- Never experiment on a session someone is using: strip every `PARDES_*` - variable and start your own (Scripting, "An isolated session"); build - with `-Dplatform=tty`, since a bare `zig build` installs over - `~/.local/bin`. + session words to `$m/ctl`. `Exit`, `Restore`, `Del` and `get` refuse once + over unsaved text; the same word again discards. + +## An isolated session + +Never experiment on a session someone is using. Under `9ns --mntgen`: + +```sh +env -i PATH="$PATH" HOME="$(mktemp -d)" XDG_RUNTIME_DIR="$XDG_RUNTIME_DIR" SHELL=/usr/bin/bash pardes --detach=try & +m=$NINE_MOUNT/pardes/try; cat $m/index +echo Exit > $m/exec +``` + +Keep `SHELL` (bash or fish): without it the terminals run `/bin/sh`, +which gets no OSC 133 prompt marks, and `pty/run` answers `error no +prompt marks`. + +To test a change, build with `-Dplatform=tty` (it installs into +`zig-out`): a bare `zig build` installs over `~/.local/bin`. diff --git a/.agents/skills/pardes/SKILL.md b/.agents/skills/pardes/SKILL.md new file mode 100644 index 00000000..d49f8e50 --- /dev/null +++ b/.agents/skills/pardes/SKILL.md @@ -0,0 +1,131 @@ +--- +name: pardes +description: What the pardes editor is and how to use it, with a small cheatsheet (mouse, modes, keys, Look addresses, tags, sessions, config) and a map of its book. Use whenever the user mentions pardes, asks how to do something in it, wants a file opened or text paged in the editor, and to check whether you are running inside a pardes session ($PARDES_PID, $PARDES_9P, $PARDES_PANE, $PARDES_MOUNT) before acting on the user's editor. For scripting or driving a session through its 9P files, use pardes-9p. +--- + +# pardes + +pardes is acme's idea (text is the interface: any word can be looked at or +run) with helix's modal keys, VT terminals and PDFs in panes. Two builtins +carry it: Look (right-click, B3, or Enter in normal mode) opens what the +text names (a file, `file:line`, a directory, a URL), else finds the word's +next place; Exec (middle-click, B2, or Tab) runs the builtin a word names, +else runs it as a shell line. Every session is also a virtual filesystem +served over 9P, so any program that opens files can script it (pardes-9p). + +Paths below are relative to the pardes source tree, the repository this +skill lives in (`readlink -f` this skill's directory if it is reached +through a symlink). + +## Am I in a pardes session? + +Check this first: it decides whether "open it", "show me" or "run it" +can mean the user's editor. Every shell and command pane pardes starts +gets these, and every program started from it (an agent too) inherits them: + +| Variable | | +|---|---| +| `PARDES_PID` | the session's pid (what `status` says) | +| `PARDES_9P` | the session's 9P socket | +| `PARDES_PANE` | the serial of the pane this shell runs in | +| `PARDES_MOUNT` | the session as a directory, only under `9ns --mntgen` or in a `Tty9p` shell | +| `winid` | the pane a command was clicked in (command panes only) | + +A variable can outlive its session (a `--detach` session quit, a shell +moved under tmux), so check that it is live, not just set: + +```sh +if [ -n "${PARDES_9P:-}" ] && [ -S "$PARDES_9P" ] && kill -0 "${PARDES_PID:-}" 2>/dev/null; then + echo "in pardes: session $PARDES_PID, pane $PARDES_PANE, mount ${PARDES_MOUNT:-none}" +else + echo "not in pardes" +fi +``` + +With a mount, `sed -n 1p "$PARDES_MOUNT/status"` answers `pid +$PARDES_PID`. Sessions listed under `$NINE_MOUNT/pardes/` are not proof: +that lists every running session, the user's included, whether or not you +run inside one. Not in a session: say so, and touch no session you merely +found there. + +## Words + +- **tag**: the editable line of words above the workspace, each column and + each pane. A pane's starts with its path. Any word runs from any tag. +- **serial**: a pane's number, never reused (`@p3:12`, `pane/3/`). +- **command pane**: a terminal running one command line; its tag ends in + `running`, then `exit N`. +- **`+` names**: panes pardes makes: `+New` (scratch), `+Search`, `+Pager`, + `+Errors`, `+Unsaved`, `+Diff`. +- **active column**: where the next new pane goes. + +## Cheatsheet + +| Mouse | | +|---|---| +| B1 | select; give the pane the keyboard | +| B2 | Exec the word or sweep | +| B3 | Look at the word or sweep | +| B1+B2 / B1+B3 / B1+B2+B3 | cut / paste / copy (chords) | +| B2+B1 | Exec with the B1 selection as argument | +| Alt-click / Super-click | B2 / B3 for one button | + +| Modes (the box left of a tag) | | +|---|---| +| ` ` normal | helix keys: motions select, edits act on the selection | +| `^` insert | `i a o`…; Esc back to normal | +| `$` raw, terminals | keys go to the program; Ctrl-b toggles raw/normal | +| Esc in normal | back to the previous pane (unlike helix) | + +| Keys pardes adds or changes | | +|---|---| +| `SPC ?` | Help: every builtin, its leader path and keys | +| `:` | to the pane's tag and back | +| `Ctrl-w h/j/k/l` | focus a neighbour | +| `Ctrl-o` / `Ctrl-i` | jump list back / forward | +| `Alt-n` / `Alt-c` | new terminal below / pane to a new column | +| `SPC f s`, `SPC d`, `SPC q` | Save, Del, Exit | +| `SPC f f`, `SPC f g`, `SPC f r` | Find, Grep, Recent | +| `12G`, `n` in a command pane | line 12; next `file:line` error | + +| Look addresses (B3 or Enter) | | +|---|---| +| `file:12`, `file:12:5` | line, byte column | +| `file:/re/`, `file:0/re/` | next match, first match | +| `:40` | line 40 of the pane looked from | +| `@p3:12` | pane 3 by serial | +| `src/` | a directory pane | + +Addresses are sam's (`#n /re/ ?re? $ a,b`). + +| Common words | | +|---|---| +| `Save` `Del` `Get` `Undo` `Edit` | pane; Del/Exit/Restore refuse once over unsaved text, again discards | +| `New` `Tty` `Tty+bash` `Newcol` `Delcol` | panes and columns | +| `Find name` `Grep text` `Recent` | listings in a `+Search` | +| `Kill make` `Repl python` `Filter` `Mode` | terminals and commands | +| `Dump` `Restore` `Config` `DumpConfig` `Theme x` | workspace and settings | + +## From a shell inside pardes + +```sh +pardes notes.txt # open it in this session, return at once +pardes --wait notes.txt # return when its pane closes (EDITOR='pardes --wait') +git log | pardes - # page text into a +Pager +pardes --detach=work & # a session with no screen; --attach=work shows it +``` + +These act on the user's session: do them when asked. Anything more (read +panes, run commands, react to clicks) is the pardes-9p skill. Config is +`~/.config/pardes/init`, a builtin a line; keys are compiled in +(`src/config.zig`). `$NINE_MOUNT/agents`, where present, is cloud9's +read-only view of running coding agents. + +## The book + +`docs/typ/` holds it, one file a chapter, in reading order: `guide.typ` +(day to day), `setup.typ` (9ns, EDITOR, pager, language servers), +`cheatsheet.typ`, `scripting.typ`, `reference.typ` (every 9P file), +`themes.typ`, `building.typ`. `docs/typ/README` says how they build into +the A4 cheatsheet, the book and the website. In the editor: `Help` +(`SPC ?`) and `Tutor` (`SPC h t`). diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index b42f9c72..83a410dc 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -20,12 +20,15 @@ {"name": "Crt", "leader": "SPC t r", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off, 0-3", "doc": "The bundled CRT post pass over the window, on or off."}, {"name": "CursorBlink", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "The cursor blinks, solid while typing, on or off."}, {"name": "Debug", "leader": "SPC t d", "also": ["topbar"], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A small box of frame statistics at the top right, on or off."}, + {"name": "Def", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Go to the definition of the symbol under the cursor; with an argument (a 2-1 chord's selection), of that symbol, where it is nearest."}, {"name": "Del", "leader": "SPC d", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane."}, {"name": "DelAbove", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane above it."}, {"name": "DelBelow", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane below it."}, {"name": "Delcol", "leader": "SPC c d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close this column and its panes, refusing once over unsaved text."}, {"name": "Detach", "leader": "SPC s D", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Detach this pardes from its terminal, leaving the session running."}, {"name": "Diagnostics", "leader": "SPC l d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the file's diagnostics from the language server."}, + {"name": "Diff", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text."}, + {"name": "DiffLook", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "hunks, text", "doc": "A .diff or .patch looked at: hunks, a +Diff stacking its hunks, or text, the file itself; Diff goes from one to the other."}, {"name": "DirLook", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "pane, terminal", "doc": "A directory looked at: pane, a pane listing it as acme's directory window, or terminal, ls in a terminal there."}, {"name": "Down", "leader": "SPC w j", "also": ["C-w j", "C-w down"], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane below, off a tag onto the pane under it."}, {"name": "Dump", "leader": "SPC s d", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Write the session's panes and layout to a dump file, for Restore."}, @@ -36,7 +39,7 @@ {"name": "EffectCode", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Open the source of a panel transition or post shader, by name."}, {"name": "Exec", "leader": null, "also": ["tab", "middle-click"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Execute its argument as a middle click on it would, a builtin or a shell command."}, {"name": "Exit", "leader": "SPC q", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Quit the editor, refusing once while a pane holds unsaved text: an Exit with nothing edited since discards it."}, - {"name": "Filter", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Recolour a terminal's program colours to the theme, or show them as sent, flipping between them."}, + {"name": "Filter", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Recolour a terminal's or a +Pager's program colours to the theme, or show them as sent, flipping between them."}, {"name": "Find", "leader": "SPC f f", "also": ["topbar"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "List the files below this pane's directory whose names hold its argument, in a +Search."}, {"name": "FocusTint", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "The focused pane's and column's tags are tinted, on or off."}, {"name": "Font", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The body font, by name or path, and its size."}, @@ -103,6 +106,7 @@ {"name": "Putall", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "acme's Putall: every pane holding unsaved edits to a file is saved, each as its own Save; one that is refused (changed on disk since, a write that fails) says so and the rest are saved all the same."}, {"name": "Recent", "leader": "SPC f r", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "List the files opened lately, closed ones too, each a place to open again."}, {"name": "Redo", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Redo the last undone edit."}, + {"name": "Refs", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "List the references to the symbol under the cursor; with an argument (a 2-1 chord's selection), to that symbol, where it is nearest."}, {"name": "Rename", "leader": "SPC l r", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Rename the symbol under the cursor everywhere, to its argument."}, {"name": "Repl", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Binds this terminal as a language's REPL, so an exec on that language's files is typed into it instead of run."}, {"name": "Restore", "leader": "SPC s r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Replace every pane with those of a dump file, the last one Dump wrote when bare."}, diff --git a/docs/typ/builtins-tty.json b/docs/typ/builtins-tty.json index 53bcf033..35e12875 100644 --- a/docs/typ/builtins-tty.json +++ b/docs/typ/builtins-tty.json @@ -17,12 +17,15 @@ {"name": "Colors", "leader": "SPC t c", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Syntax colours in text panes, on or off."}, {"name": "Config", "leader": "SPC f c", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the startup file, `init`, in a pane: its pane when it is open, else the file, else a pane of that name for Save to make it and its directory."}, {"name": "Debug", "leader": "SPC t d", "also": ["topbar"], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A small box of frame statistics at the top right, on or off."}, + {"name": "Def", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Go to the definition of the symbol under the cursor; with an argument (a 2-1 chord's selection), of that symbol, where it is nearest."}, {"name": "Del", "leader": "SPC d", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane."}, {"name": "DelAbove", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane above it."}, {"name": "DelBelow", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close the pane, giving its rows to the pane below it."}, {"name": "Delcol", "leader": "SPC c d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Close this column and its panes, refusing once over unsaved text."}, {"name": "Detach", "leader": "SPC s D", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Detach this pardes from its terminal, leaving the session running."}, {"name": "Diagnostics", "leader": "SPC l d", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the file's diagnostics from the language server."}, + {"name": "Diff", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text."}, + {"name": "DiffLook", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "hunks, text", "doc": "A .diff or .patch looked at: hunks, a +Diff stacking its hunks, or text, the file itself; Diff goes from one to the other."}, {"name": "DirLook", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "pane, terminal", "doc": "A directory looked at: pane, a pane listing it as acme's directory window, or terminal, ls in a terminal there."}, {"name": "Down", "leader": "SPC w j", "also": ["C-w j", "C-w down"], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane below, off a tag onto the pane under it."}, {"name": "Dump", "leader": "SPC s d", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Write the session's panes and layout to a dump file, for Restore."}, @@ -33,7 +36,7 @@ {"name": "EffectCode", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Open the source of a panel transition or post shader, by name."}, {"name": "Exec", "leader": null, "also": ["tab", "middle-click"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Execute its argument as a middle click on it would, a builtin or a shell command."}, {"name": "Exit", "leader": "SPC q", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Quit the editor, refusing once while a pane holds unsaved text: an Exit with nothing edited since discards it."}, - {"name": "Filter", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Recolour a terminal's program colours to the theme, or show them as sent, flipping between them."}, + {"name": "Filter", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Recolour a terminal's or a +Pager's program colours to the theme, or show them as sent, flipping between them."}, {"name": "Find", "leader": "SPC f f", "also": ["topbar"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "List the files below this pane's directory whose names hold its argument, in a +Search."}, {"name": "FocusTint", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "The focused pane's and column's tags are tinted, on or off."}, {"name": "Forward", "leader": "SPC j i", "also": ["C-i"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Ctrl-i: one step forward again, up to wherever Back started."}, @@ -90,6 +93,7 @@ {"name": "Putall", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "acme's Putall: every pane holding unsaved edits to a file is saved, each as its own Save; one that is refused (changed on disk since, a write that fails) says so and the rest are saved all the same."}, {"name": "Recent", "leader": "SPC f r", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "List the files opened lately, closed ones too, each a place to open again."}, {"name": "Redo", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Redo the last undone edit."}, + {"name": "Refs", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "List the references to the symbol under the cursor; with an argument (a 2-1 chord's selection), to that symbol, where it is nearest."}, {"name": "Rename", "leader": "SPC l r", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Rename the symbol under the cursor everywhere, to its argument."}, {"name": "Repl", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Binds this terminal as a language's REPL, so an exec on that language's files is typed into it instead of run."}, {"name": "Restore", "leader": "SPC s r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Replace every pane with those of a dump file, the last one Dump wrote when bare."}, diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index 90e72303..89323766 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -202,8 +202,8 @@ takes the rows: #key("k") above, #key("j") below. = Reviewing diffs -`git diff` run as a command, or a `.diff` or `.patch` opened, is drawn as -a diff, each hunk in its file's language. #btn("B3") on: +`git diff` run as a command, or a `.diff` or `.patch` shown as text (below), +is drawn as a diff, each hunk in its file's language. #btn("B3") on: #pairs( [`diff --git`, `---`, `+++`], [the file], @@ -211,6 +211,17 @@ a diff, each hunk in its file's language. #btn("B3") on: [a line's `+`, `-` or space], [that line in the new file], ) +A `.diff` or `.patch` looked at, and a diff paged (`git show`), opens as +a `+Diff`, stacked as delta shows one: each hunk under its `path:line` +(`n`/`N` step through them, #btn("B3") opens it) and the declarations +around it, a `+`/`-` before each line, the words a changed line changed +tinted and a line added or removed whole faintly. A mailed patch keeps its +message and diffstat above. The files are found from the diff's directory +or one above it. #word("Diff") on a `+Diff` shows the diff itself as +text (a paged one's `+Pager` is folded under it), and on the text stacks +it again; #word("DiffLook") `text` in the startup file opens the text +first. + = `pardes FILE` and `--wait` In a pane's shell: diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index ed88905a..909c1e1a 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -22,7 +22,7 @@ index a line per pane: serial kind dirty name column @ru status pid, version, panes @other-files look write a line: a #word("Look") at the pane with the keyboard; read: the serials touched @look-and-exec exec write a line: an #word("Exec") there; read: the serials touched @look-and-exec -pager write a directory: its one +Pager, made or emptied; read: its serial @pardes-stdin +pager write a directory: a new +Pager there; read: its serial @pardes-stdin log the event log; write follow to wait for more @log screen the rendered screen as JSON @on-screen listeners dial addresses @other-files @@ -252,7 +252,9 @@ A line written to #file("exec") is #word("Exec"): silently, here and in every ctl. - The language server's words ask about a file pane's text at its cursor (set it with #file("addr") and `dot=addr` first): #word("Hover") fills - `+Hover`; #word("Rename") `new` renames the symbol in the file and says how many + `+Hover`; #word("Def") and #word("Refs"), in the tag of a file a server + speaks for, are `gd` and `gr`, and given a symbol (a 2-1 chord's + selection) ask at its occurrence nearest the cursor; #word("Rename") `new` renames the symbol in the file and says how many ranges it changed (on the message row, and so in the log) without listing them, and fails when there is nothing to rename. One that reaches other files applies nothing: it opens a `+Search` preview of the edits, which @@ -457,7 +459,7 @@ may lower the contrast of text, the selection or a focus indicator. build embeds them. Resting the pointer on text for about 32 ms (`look_preview_delay_frames`, -2 frames, in `src/config.zig`; `null` turns it off) tints what #word("Look") would take, with no other effect. A terminal's +2 frames, in `src/config.zig`; `null` turns it off) tints what #word("Look") would take, with no other effect. A terminal's or a `+Pager`'s #word("Filter") keeps each foreground at least `tty_filter_min_contrast` (WCAG 1.5, `src/config.zig`) against its background. @@ -889,10 +891,10 @@ at 200, ending in `…`. Control characters become spaces. line is the session's; one not there is refused ENOENT, a relative one EINVAL, one you may not write `permission denied`, a regular file `not a directory`, ENOTDIR), one line; what follows that line, on the same open, is the text to - page, escapes and all. A read of that open answers the serial of the - directory's one `+Pager`, made or emptied for it, once the text is in. This is what - `pardes -` uses; from a directory you may not write, it pages into the - session's `+Pager`. + page, escapes and all. A read of that open answers the serial of a new + `+Pager` in the directory, once the text is in. This is what + `pardes -` uses; from a directory you may not write, it pages into a + `+Pager` of the session's. - #file("/listeners"): the session's dial addresses, a line each (#doc("building", section: "listeners")). - #file("/os/"): existing regular files take read, write and truncation to @@ -993,12 +995,13 @@ it was. = pardes - -`pardes -` reads stdin to its end and shows it in the directory's one -`+Pager` pane, made or emptied for it and left clean, opening at its top; -the next paged text refills it. The session parses the text with +`pardes -` reads stdin to its end and shows it in a new `+Pager` pane of +the directory, left clean, opening at its top, with no line numbers; a +`+Pager` already there keeps its page. The session parses the text with ghostty-vt: SGR colours become the `+Pager`'s own display, never part of -its body or any read (#word("PagerColor") `off` pages plain), and every other -escape is dropped; a carriage return keeps a progress line's last state, +its body or any read (#word("PagerColor") `off` pages plain), mapped +through the theme as a terminal's are until its #word("Filter") shows them +as sent; every other escape is dropped; a carriage return keeps a progress line's last state, and CRLF becomes LF. Empty stdin shows nothing. Inside a pardes pane it returns at once; a text the session cannot take is printed to stderr with why, and the exit is 1. From a directory whose name holds a newline or control byte, the pane is the session diff --git a/docs/typ/setup.typ b/docs/typ/setup.typ index df99a45f..f49c9075 100644 --- a/docs/typ/setup.typ +++ b/docs/typ/setup.typ @@ -59,7 +59,7 @@ fi = A pager -#cmd("ls --color=always | pardes - # into the directory's +Pager, colours kept") +#cmd("ls --color=always | pardes - # into a new +Pager there, colours kept") With #word("Pager") `pardes` (the default) a terminal's shell gets `PAGER`, `GIT_PAGER` and `SYSTEMD_PAGER` set to it (and diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index 6be39c7a..ce2cedc8 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,12 @@ ## 0.23 +- A file a language server speaks for (by its extension) has `Def` and + `Refs` in its tag: the definition and the references of the symbol at + the cursor, which `gd`, `gr` and a Ctrl-click run too. Chorded 2-1, they + ask at the selected symbol instead, its occurrence nearest the cursor. +- A scroll in the window never moves the tree-sitter context rows: the + body glides under them. - A look at a directory opens a pane listing it, as acme's directory window does: its entries in columns, a directory's marked `/`. A look at an entry opens it from there, and `Get` or a look at it again reads it diff --git a/src/File.zig b/src/File.zig index 875d0f46..31392ebd 100644 --- a/src/File.zig +++ b/src/File.zig @@ -154,8 +154,11 @@ pub const State = struct { /// Its file was deleted on disk: said once (`deleted`) until it is /// written or found again. disk_gone: bool = false, - /// A +Pager pane (`pardes -`) whose text is a diff (`git diff`, `show`, - /// `log -p`): drawn and looked at as a diff (Pane.colorAlgo). + /// A +Pager pane (`pardes -`): no line numbers, its program's colours + /// through Filter until it is toggled off. + pager: bool = false, + /// A +Pager whose text is a diff (`git diff`, `show`, `log -p`): drawn + /// and looked at as a diff (Pane.colorAlgo). pager_diff: bool = false, /// A +Pager's colours, as its program printed them (pager.zig): drawn /// over its text by recolorSyntax, never read over 9P. ponytail: any @@ -562,6 +565,10 @@ pub fn byteAtRowDisplay(pane: *const Pane, row: i32, from_raw: i32, display_col: pub fn gutterWidth(pane: *const Pane) u16 { if (pane.file == null) return 0; const file = &pane.file.?; + // A +Pager, and a +Diff (hunks.zig), show no line numbers, as a + // pager and delta show none. + if (file.pager) return 0; + if (file.output) |o| if (std.meta.eql(o.from, Output.Origin{ .cmd = .Diff })) return 0; var lines = if (file.line_starts.len > 0) file.line_starts.len else lineCount(file.content); var digits: u16 = 1; while (lines >= 10) : (lines /= 10) digits += 1; @@ -1164,7 +1171,7 @@ pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void { f.highlights = &.{}; f.highlight_start = 0; f.syntax_dirty = true; - if (std.mem.endsWith(u8, f.path, "/+Pager")) f.pager_diff = looksLikeDiff(new[0..@min(new.len, 64 * 1024)]); + if (f.pager) f.pager_diff = looksLikeDiff(new[0..@min(new.len, 64 * 1024)]); for (twins[0..ntwins], 0..) |id, i| { const t = p.panes[id].?; const tf = &t.file.?; @@ -1434,6 +1441,7 @@ test "a +Pager pane holding a diff is drawn and looked at as one; holding other const f = &pane.file.?; p.gpa.free(f.path); f.path = try p.gpa.dupe(u8, "/tmp/+Pager"); + f.pager = true; setContent(p, f, try p.gpa.dupe(u8, "commit abc\n\ndiff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n-a\n+b\n")); try std.testing.expect(pane.colorAlgo() == .diff); try std.testing.expect(pardes.look.diffLines(p, pane) != null); @@ -1715,7 +1723,7 @@ fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) var lbuf: [@max(config.PREFIX_W, 32)]u8 = undefined; const prefix = lbuf[0..prefix_width]; @memset(prefix, ' '); - if (at == 0) { + if (at == 0 and prefix.len > 0) { var lineno = row + 1; var digit: usize = prefix.len - 1; while (true) { @@ -1790,6 +1798,12 @@ const SynStyle = struct { fg: [3]u8, bold: bool }; pub const DiffTints = struct { added_bg: [3]u8, removed_bg: [3]u8, + /// The words a changed line changed (hunks.zig), on a stronger ground. + added_emph_bg: [3]u8, + removed_emph_bg: [3]u8, + /// A +Diff line added or removed whole: a faint ground. + added_line_bg: [3]u8, + removed_line_bg: [3]u8, added_fg: [3]u8, removed_fg: [3]u8, @@ -1804,6 +1818,10 @@ pub const DiffTints = struct { return .{ .added_bg = added_bg, .removed_bg = removed_bg, + .added_emph_bg = Colors.mixOklab(page, green, 0.28), + .removed_emph_bg = Colors.mixOklab(page, red, 0.28), + .added_line_bg = Colors.mixOklab(page, green, 0.07), + .removed_line_bg = Colors.mixOklab(page, red, 0.07), .added_fg = legible(green, ink, added_bg), .removed_fg = legible(red, ink, removed_bg), }; @@ -1818,9 +1836,9 @@ pub const DiffTints = struct { /// The row ground and prefix ink for a line's style byte, if it is an /// added or removed line. - pub fn forStyle(t: *const DiffTints, style: u8) ?struct { bg: [3]u8, fg: [3]u8 } { - if (style & syntax.diff_added != 0) return .{ .bg = t.added_bg, .fg = t.added_fg }; - if (style & syntax.diff_removed != 0) return .{ .bg = t.removed_bg, .fg = t.removed_fg }; + pub fn forStyle(t: *const DiffTints, style: u8) ?struct { bg: [3]u8, fg: [3]u8, emph_bg: [3]u8, line_bg: [3]u8 } { + if (style & syntax.diff_added != 0) return .{ .bg = t.added_bg, .fg = t.added_fg, .emph_bg = t.added_emph_bg, .line_bg = t.added_line_bg }; + if (style & syntax.diff_removed != 0) return .{ .bg = t.removed_bg, .fg = t.removed_fg, .emph_bg = t.removed_emph_bg, .line_bg = t.removed_line_bg }; return null; } }; @@ -1855,7 +1873,17 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. const prefix_width = gutterWidth(pane); const tz_recolor = tracy.zone(@src(), "synRecolor"); defer tz_recolor.end(); - const tints: ?DiffTints = if (pane.colorAlgo() == .diff and highlights.len > 0) DiffTints.of(p) else null; + // A diff's rows, and a +Diff's (hunks.zig): their markers coloured. + // A diff's whole row is tinted; a +Diff tints only the words a + // changed line changed. + const algo = pane.colorAlgo(); + const tints: ?DiffTints = if ((algo == .diff or algo == .locations) and highlights.len > 0) DiffTints.of(p) else null; + const row_tint = algo == .diff; + var filtered_storage: terminal.FilteredColors = undefined; + const filtered: ?*terminal.FilteredColors = if (comptime terminal.enabled) (if (pane.tty_filter and spans.len > 0) blk: { + filtered_storage = .init(p, null); + break :blk &filtered_storage; + } else null) else null; // indexed start, same as bodyText — an empty tail simply paints nothing var flines = std.mem.splitScalar(u8, f.content[lineStart(p.gpa, f, f.scroll)..], '\n'); const total = nlines(p.gpa, f); @@ -1893,7 +1921,11 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. t.forStyle(highlights[base - highlight_start]) else null else null; - if (tint) |t| if (prefix_width < tw) tintRow(s, tx + @as(u16, @intCast(prefix_width)), body_y + vr, tx + tw, t.bg); + if (tint) |t| if (prefix_width < tw) { + // A +Diff line added or removed whole: faintly (hunks.zig). + const whole = highlights[base - highlight_start] & syntax.diff_whole != 0; + if (row_tint or whole) tintRow(s, tx + @as(u16, @intCast(prefix_width)), body_y + vr, tx + tw, if (row_tint) t.bg else t.line_bg); + }; // A +Pager's own colours (pager.zig) on every row but one the diff // look tints: an added or removed line is drawn as pardes draws a // diff, and git's red and green on it would only fight the tint. @@ -1924,6 +1956,11 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. cell.style.bold = ss.bold; } } + if (tint) |t| if (highlights[hidx] & syntax.diff_emph != 0) { + var fill: usize = 0; + while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) + s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr).style.bg = .{ .rgb = t.emph_bg }; + }; } } // Results keep their exact live text. Only the location, @@ -1945,10 +1982,16 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) { const cell = s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr); if (cell.default) continue; - // A palette colour through the theme's sixteen, as a - // terminal pane's cell; truecolor as it is. - if (st.fg != .default) cell.style.fg = if (st.fg == .index) terminal.palColor(p, st.fg.index) else st.fg; - if (st.bg != .default) cell.style.bg = if (st.bg == .index) terminal.palColor(p, st.bg.index) else st.bg; + // As a terminal pane's cell: through Filter, or a + // palette colour through the theme's sixteen and + // truecolor as it is. + if (filtered) |colors| { + if (st.fg != .default) cell.style.fg = colors.spanColor(st.fg, false); + if (st.bg != .default) cell.style.bg = colors.spanColor(st.bg, true); + } else { + if (st.fg != .default) cell.style.fg = if (st.fg == .index) terminal.palColor(p, st.fg.index) else st.fg; + if (st.bg != .default) cell.style.bg = if (st.bg == .index) terminal.palColor(p, st.bg.index) else st.bg; + } cell.style.bold = cell.style.bold or st.bold; cell.style.dim = st.dim; cell.style.italic = st.italic; diff --git a/src/Output.zig b/src/Output.zig index 3bae9ecf..9e194615 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -15,6 +15,8 @@ const build_options = @import("pardes_config"); const lsp = @import("lsp/lsp.zig"); const look = @import("look.zig"); const locations = @import("locations.zig"); +const layout = @import("layout.zig"); +const hunks = @import("hunks.zig"); const Pane = panes.Pane; const File = panes.File; @@ -538,6 +540,17 @@ pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: [] result_rows = formatted.rows; anchor = formatted.anchor; } + _ = try fillRows(p, id, dir, from, arg, result_content, result_rows, anchor); +} + +/// Rows already laid out (`content`, `rows` its metadata, both taken +/// when it succeeds, the caller's still when it fails) into the pane they +/// belong in: the one a run of `from` with `arg` in `dir` showed last, +/// refilled, else a new one placed by pane `id`. Its id. +pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []const u8, result_content: []u8, result_rows: []locations.Row, anchor: ?usize) !usize { + const pane = p.panes[id] orelse return error.MissingPane; + if (arg.len > max_arg) return error.ArgumentTooLong; + const by_arg = std.meta.activeTag(from) != .query; for (p.panes, 0..) |slot, i| { const rp = slot orelse continue; const rf = if (rp.file) |*f| f else continue; @@ -578,7 +591,7 @@ pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: [] pane.search_row = anchor; look.armLookWalk(p, i); } - return; + return i; } const free = p.freeSlot() orelse return error.NoPaneSlots; const np = try open(p, free, dir, from, arg, result_content); @@ -590,6 +603,57 @@ pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: [] pane.search_row = anchor; look.armLookWalk(p, free); } + return free; +} + +/// Diff: `content`, the diff at `path` (a file, a +Pager), stacked as a +/// diff viewer shows it (hunks.zig), in a +Diff where its files are found +/// (hunks.sourceRoot), placed by pane `id`, refilled when it is there. Its +/// arg names the diff (its base name, or its whole path when the +Diff +/// stands elsewhere), for Diff to go back to it. The +Diff's id; +/// NoHunks when there is none in it. +pub fn openDiff(p: *Pardes, id: usize, path: []const u8, content: []const u8) !usize { + const dir = std.fs.path.dirname(path) orelse p.sessionDir(); + const root = hunks.sourceRoot(p, dir, content); + const result = try hunks.format(p, root, content); + errdefer { + p.gpa.free(result.content); + locations.freeRows(p.gpa, result.rows); + } + var has_hunk = false; + for (result.rows) |row| has_hunk = has_hunk or row.kind == .match; + if (!has_hunk) return error.NoHunks; + const arg = if (std.mem.eql(u8, root, dir) or path.len > max_arg) std.fs.path.basename(path) else path; + return fillRows(p, id, root, .{ .cmd = .Diff }, arg, result.content, result.rows, null); +} + +/// Diff on a +Diff: the diff it stacks, as text. A pane holding it +/// already (the newest: a +Pager folded under its +Diff unfolds) is +/// shown; else the file is opened as text, whatever DiffLook says. +pub fn showDiffText(p: *Pardes, id: usize, source: []const u8) void { + var newest: ?usize = null; + for (p.panes, 0..) |slot, i| { + const f = (slot orelse continue).file orelse continue; + if (!std.mem.eql(u8, f.path, source)) continue; + if (newest == null or p.panes[newest.?].?.serial < slot.?.serial) newest = i; + } + if (newest) |i| { + if (p.panes[i].?.collapsed) layout.toggleCollapse(p, i); + p.active = i; + return; + } + p.look_text = true; + defer p.look_text = false; + look.lookAt(p, id, source); +} + +/// The diff a +Diff stacks (openDiff's arg): its path. +pub fn diffSource(p: *Pardes, f: *const File.State) ?[]const u8 { + const o = f.output orelse return null; + if (!std.meta.eql(o.from, Origin{ .cmd = .Diff })) return null; + const arg = o.arg(); + if (arg.len > 0 and arg[0] == '/') return arg; + return std.fs.path.join(p.scratch.allocator(), &.{ std.fs.path.dirname(f.path) orelse "", arg }) catch null; } pub fn openJumps(p: *Pardes, id: usize) !void { @@ -685,25 +749,15 @@ pub fn openUnsaved(p: *Pardes, id: usize, content: []u8) void { p.active = id; } -/// `pardes -`'s pane: the one `/+Pager`, emptied for the next paged -/// text when it is there (a directory's paged commands refill it, as its -/// command pane is reused), else made, named so before it is announced, -/// and placed wherever there is room without taking the keyboard. `dir` -/// empty (or not absolute): the session's directory. Its id; NoPaneRoom -/// or NoPaneSlots when it has no room at all. +/// `pardes -`'s pane: a new `/+Pager` for each paged text, as each +/// run of a pager is its own (one already there keeps its page), named so +/// before it is announced, its colours through Filter, and placed wherever +/// there is room without taking the keyboard. `dir` empty (or not +/// absolute): the session's directory. Its id; NoPaneRoom or NoPaneSlots +/// when it has no room at all. pub fn openPager(p: *Pardes, from: usize, dir_arg: []const u8) !usize { const dir = if (dir_arg.len > 0 and dir_arg[0] == '/') dir_arg else p.sessionDir(); const path = try std.fs.path.join(p.gpa, &.{ dir, "+Pager" }); - for (p.panes, 0..) |slot, i| { - const pane = slot orelse continue; - const f = if (pane.file) |*file| file else continue; - if (!std.mem.eql(u8, f.path, path)) continue; - p.gpa.free(path); - File.setContent(p, f, try p.gpa.alloc(u8, 0)); - resetBody(p, pane); - f.saved_revision = f.revision; - return i; - } const free = p.freeSlot() orelse { p.gpa.free(path); return error.NoPaneSlots; @@ -719,6 +773,8 @@ pub fn openPager(p: *Pardes, from: usize, dir_arg: []const u8) !usize { // The pane owns the name from here. p.gpa.free(pane.file.?.path); pane.file.?.path = path; + pane.file.?.pager = true; + pane.tty_filter = true; const keyboard = p.active; exec.placeNew(p, from, null, free, .fs); if (p.unplaced.isSet(free)) return error.NoPaneRoom; diff --git a/src/builtins.zig b/src/builtins.zig index 77e1169d..c1424b2f 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -46,6 +46,10 @@ pub const PaneKind = enum { /// An image pane, or a terminal, whose program's kitty graphics are /// pictures too. picture, + /// A terminal, or a +Pager: a program's colours. + program_colors, + /// A text pane showing a diff: a .diff, a .patch, a +Pager holding one. + diff, pub fn has(kind: PaneKind, pane: *const panes.Pane) bool { return switch (kind) { @@ -53,6 +57,9 @@ pub const PaneKind = enum { .pdf => pane.hasPdf(), .image => pane.image != null, .picture => pane.image != null or pane.isTerminal(), + .program_colors => pane.isTerminal() or (pane.file != null and pane.file.?.pager), + .diff => if (pane.file) |f| pane.colorAlgo() == .diff or + (f.output != null and std.meta.eql(f.output.?.from, panes.Output.Origin{ .cmd = .Diff })) else false, }; } @@ -62,6 +69,8 @@ pub const PaneKind = enum { .pdf => "a PDF", .image => "an image", .picture => "an image or a terminal", + .program_colors => "a terminal or a +Pager", + .diff => "a diff or a +Diff", }; } }; @@ -1336,14 +1345,28 @@ pub const Del = struct { } }; -/// Recolour a terminal's program colours to the theme, or show them as sent, flipping between them. +/// Recolour a terminal's or a +Pager's program colours to the theme, or show them as sent, flipping between them. pub const Filter = struct { - pub const needs: PaneKind = .terminal; + pub const needs: PaneKind = .program_colors; pub fn run(c: Ctx) void { c.pane.tty_filter = !c.pane.tty_filter; } }; +/// Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text. +pub const Diff = struct { + pub const needs: PaneKind = .diff; + pub const output: OutputTraits = .{ .name = config.diff_buffer, .steps = true, .locations = true }; + pub fn run(c: Ctx) void { + const f = &c.pane.file.?; + if (panes.Output.diffSource(c.p, f)) |source| return panes.Output.showDiffText(c.p, c.id, source); + _ = panes.Output.openDiff(c.p, c.id, f.path, f.content) catch |err| switch (err) { + error.NoHunks => c.p.reportFailure(c.id, "Diff: no hunk in it"), + else => c.p.reportError(c.id, "hunks", err), + }; + } +}; + /// Cycle the pane's input modes: terminals add raw tty mode to normal/insert. pub const Mode = struct { pub fn run(c: Ctx) void { @@ -1851,6 +1874,28 @@ pub const Jumplist = struct { // ---- the language group ---- +/// Go to the definition of the symbol under the cursor; with an argument +/// (a 2-1 chord's selection), of that symbol, where it is nearest. +pub const Def = struct { + pub const takes_arg = true; + /// Its answer says what it found, a jump or a list or why not; its + /// name would only stack above it, as gd never did. + pub const quiet = true; + pub fn run(c: Ctx) void { + c.p.lspRequest(c.id, .definition, std.mem.trim(u8, c.arg orelse "", " \t\r\n")); + } +}; + +/// List the references to the symbol under the cursor; with an argument +/// (a 2-1 chord's selection), to that symbol, where it is nearest. +pub const Refs = struct { + pub const takes_arg = true; + pub const quiet = true; // as Def + pub fn run(c: Ctx) void { + c.p.lspRequest(c.id, .references, std.mem.trim(u8, c.arg orelse "", " \t\r\n")); + } +}; + /// Ask the language server about the symbol under the cursor. pub const Hover = struct { pub fn run(c: Ctx) void { diff --git a/src/config.zig b/src/config.zig index d6ea7358..c2f51b36 100644 --- a/src/config.zig +++ b/src/config.zig @@ -32,6 +32,8 @@ pub const leader_path = paths: { var table = std.EnumArray(Builtin, ?[]const u8).initDefault(@as(?[]const u8, undecided), .{ .Help = &[_]u8{leader_help}, .Hover = "lk", + .Def = null, // gd + .Refs = null, // gr .Rename = "lr", .CodeAction = "la", .SelectRefs = "lh", @@ -49,6 +51,7 @@ pub const leader_path = paths: { .DelAbove = null, .DelBelow = null, .Filter = null, + .Diff = null, .Mode = null, .Togglettymode = null, .Collapse = null, @@ -87,6 +90,7 @@ pub const leader_path = paths: { .BootShell = null, .LookWord = null, .DirLook = null, + .DiffLook = null, .Pager = null, .PagerColor = null, .TermImages = null, @@ -301,6 +305,16 @@ pub const topbar_str = "Newcol Joincol Find Grep Help Changelog Tutor Dump Theme pub const pane_builtins_str = "Tty Collapse Del"; pub const pdf_pane_builtins_str = "Tty PdfSections PdfTint Collapse Del"; pub const file_pane_builtins_str = "Save Tty Collapse Del"; +/// After a file's, on one a language server speaks for. +pub const lsp_pane_builtins_str = "Def Refs"; +/// A diff's (a .diff, a .patch, a +Pager holding one): Diff. +pub const diff_pane_builtins_str = "Save Tty Diff Collapse Del"; +/// A +Pager's (`pardes -`): Filter, as a terminal's. +pub const pager_pane_builtins_str = "Save Tty Filter Collapse Del"; +/// A +Pager holding a diff (`git show`): Diff too. +pub const pager_diff_pane_builtins_str = "Save Tty Filter Diff Collapse Del"; +/// A +Diff's: Diff again, the diff it stacks as text. +pub const diff_view_builtins_str = "Save Tty Diff Collapse Del"; pub const terminal_pane_builtins_str = "Tty Save Mode Filter Collapse Del"; pub const command_pane_builtins_str = "Kill Save Collapse Del"; /// A directory pane's (Dir.zig): Get reads it again, as acme's does. @@ -500,6 +514,7 @@ pub const unsaved_buffer = "+Unsaved"; pub const themes_buffer = "+Themes"; pub const fonts_buffer = "+Fonts"; pub const pdf_sections_buffer = "+PdfSections"; +pub const diff_buffer = "+Diff"; pub const pdf_links_buffer = "+Links"; pub const hover_buffer = "+Hover"; pub const lsp_buffer = "+Lsp"; @@ -794,6 +809,10 @@ pub const Runtime = struct { /// A directory looked at: `pane`, acme's, a pane listing it (Dir.zig); /// `terminal`, what pardes did before, `ls` in a terminal there. dir_look: DirLook = .pane, + /// A .diff or .patch looked at (a look, `pardes FILE`, `--wait`): + /// `hunks`, a +Diff stacking its hunks (hunks.zig); `text`, the file + /// itself, as pardes showed it before. Diff goes from one to the other. + diff_look: DiffLook = .hunks, /// What a terminal's shell pages through (host_io.ChildEnv): `pardes`, /// PAGER and GIT_PAGER set to `pardes -`, a +Pager pane, where the /// user's environment set neither; `off`, the environment as it is. @@ -818,11 +837,12 @@ pub const Runtime = struct { pub const BootShell = enum { keep, replace }; pub const LookWord = enum { search, list }; pub const DirLook = enum { pane, terminal }; + pub const DiffLook = enum { hunks, text }; pub const Pager = enum { pardes, off }; pub const TermImages = enum { real, petscii }; pub const JumpScope = enum { file, all }; /// A setting that is one of a few words, each an enum field of Runtime. - pub const Choice = enum { placement, boot_shell, look_word, dir_look, pager, term_images, jump_scope }; + pub const Choice = enum { placement, boot_shell, look_word, dir_look, diff_look, pager, term_images, jump_scope }; /// shadow: a soft drop shadow. rim: a light hairline along the top of /// the focused pane's tag rows. auto: a shadow on a light page; on a @@ -1088,6 +1108,7 @@ pub const Runtime = struct { .{ .word = "Placement", .action = .{ .choice = .placement }, .doc = "Where a new pane goes: acme, as makenewwindow does, or pardes, the older rules." }, .{ .word = "BootShell", .action = .{ .choice = .boot_shell }, .doc = "A document dropped where a lone untouched shell stands: keep the shell, or replace it." }, .{ .word = "LookWord", .action = .{ .choice = .look_word }, .doc = "A plain word looked at: search selects its next place in the pane, list lists every place in a +Search." }, + .{ .word = "DiffLook", .action = .{ .choice = .diff_look }, .doc = "A .diff or .patch looked at: hunks, a +Diff stacking its hunks, or text, the file itself; Diff goes from one to the other." }, .{ .word = "DirLook", .action = .{ .choice = .dir_look }, .doc = "A directory looked at: pane, a pane listing it as acme's directory window, or terminal, ls in a terminal there." }, .{ .word = "Pager", .action = .{ .choice = .pager }, .doc = "What a terminal's commands page through: pardes, a +Pager pane (pardes -), or off, the environment's own; for terminals started after it." }, .{ .word = "PagerColor", .action = .{ .toggle = .pager_color }, .doc = "A +Pager keeps its program's colours, on or off; for the next text paged." }, @@ -1787,6 +1808,7 @@ pub const Runtime = struct { .boot_shell => "replace", .look_word => "list", .dir_look => "terminal", + .diff_look => "text", .pager => "off", .term_images => "petscii", .jump_scope => "all", @@ -1862,6 +1884,7 @@ pub const Runtime = struct { .boot_shell => "BootShell replace\n", .look_word => "LookWord list\n", .dir_look => "DirLook terminal\n", + .diff_look => "DiffLook text\n", .pager => "Pager off\n", .term_images => "TermImages petscii\n", .jump_scope => "JumpScope all\n", @@ -2235,7 +2258,7 @@ const doc_typ = struct { if (w.end > 0) w.writeByte(' ') catch return false; w.writeAll(x[0 .. std.mem.indexOfScalar(u8, x, '+') orelse x.len]) catch return false; } - const tags = [_][]const u8{ topbar_str, @import("tagline.zig").column_tag_default, pane_builtins_str, pdf_pane_builtins_str, file_pane_builtins_str, terminal_pane_builtins_str, command_pane_builtins_str, dir_pane_builtins_str }; + const tags = [_][]const u8{ topbar_str, @import("tagline.zig").column_tag_default, pane_builtins_str, pdf_pane_builtins_str, file_pane_builtins_str, diff_pane_builtins_str, pager_pane_builtins_str, pager_diff_pane_builtins_str, diff_view_builtins_str, terminal_pane_builtins_str, command_pane_builtins_str, dir_pane_builtins_str }; for (tags) |d| if (std.mem.eql(u8, d, w.buffered())) return true; return false; } diff --git a/src/edit_cmd.zig b/src/edit_cmd.zig index ebeae223..d3377e09 100644 --- a/src/edit_cmd.zig +++ b/src/edit_cmd.zig @@ -97,7 +97,9 @@ const World = struct { // A look opens it, or finds it open, where a look would; the // keyboard stays where the Edit ran. const was = p.active; + p.look_text = true; look.lookAt(p, w.from, path); + p.look_text = false; if (p.panes[was] != null) p.active = was; for (p.panes, 0..) |slot, id| { const pane = slot orelse continue; diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 65b3f926..5a026664 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1873,6 +1873,7 @@ const Gui = struct { scroll_rect: pardes.Rect = .{ .x = 0, .y = 0, .w = 0, .h = 0 }, scroll_body_y: u16 = 0, // that rect's first BODY row (Tagbottom moves it) scroll_body_h: u16 = 0, // and its BODY rows, which a taller tag leaves fewer of + scroll_held_px: f32 = 0, // its tree-sitter context band, which never moves scroll_col: u16 = 0, // where the wheel turned: crossed rows are delivered scroll_row: u16 = 0, // THERE, not wherever the pointer has drifted to since scroll_delta: f32 = 0, // finite raw distance waiting for the render batch @@ -5367,7 +5368,7 @@ fn stepGlide(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { /// The glide's picture: the pane's body rows moved by the offset, and in /// the gap it opens the rows that left, as `emitScrollRows` draws a /// touchpad's fraction. -fn emitGlideRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32, page: Ground) u32 { +fn emitGlideRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32, page: Ground, held: u16) u32 { const glide = &g.glide; for (surface.panelTracks()) |track| if (track.active() and track.pane == glide.pane) return 0; @@ -5383,10 +5384,12 @@ fn emitGlideRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *parde g.scroll_body_h = bh; var shifted = layout; shifted.y_off -= glide.offset * layout.h; + const kept = holdContext(g, surface, glide.pane, held, bh, layout); + shifted.y_off += kept.lift; const cursor_idx: u32 = if (surface.cursor) |cu| @as(u32, cu.y) * surface.cols + cu.x else std.math.maxInt(u32); const cursor_bar = if (surface.cursor) |cu| cu.bar else false; var n: u32 = 0; - var row = y0; + var row = y0 + kept.rows; while (row < y0 + bh) : (row += 1) { const line = surface.cells[@as(usize, row) * surface.cols ..][0..surface.cols]; const row_cursor: ?usize = if (surface.cursor) |cu| if (cu.y == row) cu.x else null else null; @@ -5400,9 +5403,9 @@ fn emitGlideRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *parde // The gap: rows past the top while the picture lags a move down, past // the bottom for one up; as many as it opens. const gap: u16 = @intFromFloat(@min(@ceil(@abs(glide.offset)), @as(f32, @floatFromInt(bh)))); - const kept = if (glide.offset < 0) glide.nabove else glide.nbelow; + const nkept = if (glide.offset < 0) glide.nabove else glide.nbelow; const rows = if (glide.offset < 0) glide.above else glide.below; - for (0..@min(gap, kept)) |i| { + for (0..@min(gap, nkept)) |i| { const cells = rows[i * bw ..][0..bw]; // Row -1 - i above the body, or bh + i below it, in grid rows. const at_row: i32 = if (glide.offset < 0) @as(i32, y0) - 1 - @as(i32, @intCast(i)) else @as(i32, y0) + bh + @as(i32, @intCast(i)); @@ -5560,8 +5563,9 @@ fn stepScroll(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { if (g.scroll_lag == 0) resetScroll(g); } -fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32, page: Ground) u32 { - if (g.glide.offset != 0) return emitGlideRows(g, instances, base, surface, layout, win_w, win_h, page); +fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pardes.Surface, layout: CellLayout, win_w: f32, win_h: f32, page: Ground, held: u16) u32 { + g.scroll_held_px = 0; + if (g.glide.offset != 0) return emitGlideRows(g, instances, base, surface, layout, win_w, win_h, page, held); const scroll_pane = g.scroll_pane orelse return 0; if (g.scroll_lag == 0) return 0; for (surface.panelTracks()) |track| @@ -5575,10 +5579,12 @@ fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pard if (x0 + bw > surface.cols or y0 + bh > surface.rows) return 0; // resized under us var shifted = layout; shifted.y_off -= g.scroll_lag * layout.h; + const kept = holdContext(g, surface, scroll_pane, held, bh, layout); + shifted.y_off += kept.lift; const cursor_idx: u32 = if (surface.cursor) |cu| @as(u32, cu.y) * surface.cols + cu.x else std.math.maxInt(u32); const cursor_bar = if (surface.cursor) |cu| cu.bar else false; var n: u32 = 0; - var row = y0; + var row = y0 + kept.rows; while (row < y0 + bh) : (row += 1) { const line = surface.cells[@as(usize, row) * surface.cols ..][0..surface.cols]; const row_cursor: ?usize = if (surface.cursor) |cu| if (cu.y == row) cu.x else null else null; @@ -5600,12 +5606,52 @@ fn emitScrollRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *pard return n; } +/// A scrolling body's tree-sitter context rows hold still: the shifted +/// rows start under them and are clipped below their band, and where a +/// body layer stacks them at the tagline's height (TreeContextTagStyle) +/// the rows under them are drawn up to meet them, where the layer has them. +fn holdContext(g: *Gui, surface: *const pardes.Surface, id: usize, held: u16, bh: u16, layout: CellLayout) struct { rows: u16, lift: f32 } { + const rows = @min(held, bh); + const layered = id < surface.body_layers.len and surface.body_layers[id].rows != 0 and surface.body_layers[id].context_rows != 0; + const row_px = if (layered) std.math.clamp(@as(f32, @floatFromInt(g.tagline_height)), 1, @max(1, layout.h)) else layout.h; + g.scroll_held_px = @as(f32, @floatFromInt(rows)) * row_px; + return .{ .rows = rows, .lift = @as(f32, @floatFromInt(rows)) * (row_px - layout.h) }; +} + +test "a scroll's shifted rows start under the context rows, and its scissor below their band" { + var surface: pardes.Surface = .{}; + var g: Gui = undefined; + g.tagline_height = 12; + g.scroll_rect = .{ .x = 0, .y = 0, .w = 40, .h = 20 }; + g.scroll_body_y = 1; + g.scroll_body_h = 19; + const layout: CellLayout = .{ .w = 10, .h = 20, .x_off = 0, .y_off = 0 }; + // On the grid, three body-high rows are held, and nothing moves up. + const grid = holdContext(&g, &surface, 0, 3, 19, layout); + try std.testing.expectEqual(@as(u16, 3), grid.rows); + try std.testing.expectEqual(@as(f32, 0), grid.lift); + const clip = scrollScissor(&g, layout, 400, 400); + try std.testing.expectEqual(@as(c_int, 20 + 3 * 20), clip.y); + try std.testing.expectEqual(@as(c_int, 16 * 20), clip.h); + // In a body layer they are tagline-high: the rows under them move up + // by what each is shorter, to where the layer draws them. + surface.body_layers[0].rows = 30; + surface.body_layers[0].context_rows = 3; + const layered = holdContext(&g, &surface, 0, 3, 19, layout); + try std.testing.expectEqual(@as(f32, 3 * (12 - 20)), layered.lift); + try std.testing.expectEqual(@as(c_int, 20 + 3 * 12), scrollScissor(&g, layout, 400, 400).y); + // None held: the whole body moves. + surface.body_layers[0].rows = 0; + try std.testing.expectEqual(@as(u16, 0), holdContext(&g, &surface, 0, 0, 19, layout).rows); + try std.testing.expectEqual(@as(c_int, 20), scrollScissor(&g, layout, 400, 400).y); +} + fn scrollScissor(g: *const Gui, layout: CellLayout, sw: u32, sh: u32) c.SDL_Rect { const r = g.scroll_rect; const px = layout.x_off + @as(f32, @floatFromInt(r.x + config.GUTTER)) * layout.w; - const py = layout.y_off + @as(f32, @floatFromInt(g.scroll_body_y)) * layout.h; + const py = layout.y_off + @as(f32, @floatFromInt(g.scroll_body_y)) * layout.h + g.scroll_held_px; const pw = @as(f32, @floatFromInt(r.w - config.GUTTER)) * layout.w; - const ph = @as(f32, @floatFromInt(g.scroll_body_h)) * layout.h; + const ph = @max(0, @as(f32, @floatFromInt(g.scroll_body_h)) * layout.h - g.scroll_held_px); const x0 = std.math.clamp(@as(i32, @intFromFloat(@floor(px))), 0, @as(i32, @intCast(sw))); const y0 = std.math.clamp(@as(i32, @intFromFloat(@floor(py))), 0, @as(i32, @intCast(sh))); const x1 = std.math.clamp(@as(i32, @intFromFloat(@ceil(px + pw))), x0, @as(i32, @intCast(sw))); @@ -6426,7 +6472,10 @@ fn renderFrame( } for (groups.items[0..groups.len], 0..) |group, index| std.debug.assert(cell_next[index] == group.cell_start + group.cell_count); - shifted = emitScrollRows(g, instances, cell_total, surface, layout, win_w, win_h, page); + // The body's context rows, which its scroll leaves where they are. + const scrolling: ?usize = if (g.glide.offset != 0) g.glide.pane else g.scroll_pane; + const held: u16 = if (core) |p| if (scrolling) |id| if (p.panes[id]) |pane| pane.context_rows else 0 else 0 else 0; + shifted = emitScrollRows(g, instances, cell_total, surface, layout, win_w, win_h, page, held); // Over a theme's plaques a see-through cell with no ink blends to // the plaque under it, so it draws nothing: its quad goes, and the // cells are drawn unblended (a third of the GPU's frame at 4K) diff --git a/src/hunks.zig b/src/hunks.zig new file mode 100644 index 00000000..73c0654a --- /dev/null +++ b/src/hunks.zig @@ -0,0 +1,808 @@ +//! A unified diff (`.diff`, `.patch`, a paged `git show`) stacked as a +//! diff viewer shows it (Diff): each hunk under its `path:line`, the +//! declarations around it from tree-sitter as a result's context +//! (locations.zig), its lines behind their `+`/`-` markers drawn red and +//! green, coloured as their file, and the words a changed line changed on +//! a tinted ground as delta emphasises them (its edits.rs and align.rs, here as `inferEdits` +//! and `Alignment`). +const std = @import("std"); +const pardes = @import("pardes.zig"); +const diff = @import("diff.zig"); +const syntax = @import("syntax.zig"); +const locations = @import("locations.zig"); + +const Pardes = pardes.Pardes; +const Row = locations.Row; + +/// The rows `content`, a diff, stacks to, for a pane in `dir`, with each +/// row's metadata (Output.fillRows). Text and rows are `p.gpa`'s; all else +/// is the step's scratch. +pub fn format(p: *Pardes, dir: []const u8, content: []const u8) !locations.Result { + const arena = p.scratch.allocator(); + const styles = try syntax.highlightDiff(arena, content, 0, content.len); + var out: Out = .{ .p = p, .text = .init(p.gpa) }; + errdefer out.deinit(); + var walk: diff.Walk = .{}; + var hunk: Hunk = .{}; + var source: SourceMemo = .{}; + var at: usize = 0; + // The empty text after a last newline is no line. + while (at < content.len) { + const nl = std.mem.indexOfScalarPos(u8, content, at, '\n') orelse content.len; + const raw = content[at..nl]; + const got = walk.step(raw); + const line = std.mem.trimEnd(u8, raw, "\r"); + switch (got.kind) { + .context, .added, .removed => { + const skip = @intFromBool(line.len > 0 and std.mem.indexOfScalar(u8, " +-", line[0]) != null); + try hunk.lines.append(arena, .{ + .kind = got.kind, + .code = line[skip..], + .styles = styles[at + skip ..][0 .. line.len - skip], + .old = got.old, + .new = got.new, + }); + }, + // A `\ No newline` belongs to the line above, as delta shows it. + .no_newline => {}, + else => { + try flush(&out, &hunk, &source, dir); + switch (got.kind) { + .hunk => hunk = .{ + .path = walk.path(), + .deleted = walk.deleted(), + .old_start = got.old, + .new_start = got.new, + .header = gitContext(line), + }, + // What is said around the hunks, a mailed patch's + // headers, message and diffstat, as it was written. + .other => try out.row(line, "", .{ .kind = .context, .at = .{} }), + // A section's own words (a new file's mode, a rename, + // `Binary files ... differ`), muted; its `diff` and + // `index` lines say nothing the labels do not. + .meta => if (!std.mem.startsWith(u8, line, "diff ") and !std.mem.startsWith(u8, line, "index ")) + try out.row(line, "", .{ .kind = .context, .declaration = true, .at = .{} }), + else => {}, + } + }, + } + at = nl + 1; + } + try flush(&out, &hunk, &source, dir); + const rows = try out.rows.toOwnedSlice(p.gpa); + errdefer locations.freeRows(p.gpa, rows); + return .{ .content = try out.text.toOwnedSlice(), .rows = rows, .anchor = null }; +} + +const HunkLine = struct { + kind: diff.Kind, + code: []const u8, + /// Its code's style bytes, as the diff pane paints them (syntax.zig + /// highlightDiff), the emphasis bit added by `inferEdits`. + styles: []u8, + old: usize, + new: usize, + /// Paired with a line it changed (inferEdits): its words show that; + /// unpaired, the whole line was added or removed. + paired: bool = false, +}; + +const Hunk = struct { + path: []const u8 = "", + deleted: bool = false, + old_start: usize = 0, + new_start: usize = 0, + /// What git wrote after the `@@`'s second marker (its function line). + header: []const u8 = "", + lines: std.ArrayList(HunkLine) = .empty, +}; + +/// `@@ -a,b +c,d @@ fn foo()`: `fn foo()`. +fn gitContext(line: []const u8) []const u8 { + const close = std.mem.indexOfPos(u8, line, 2, "@@") orelse return ""; + return std.mem.trim(u8, line[close + 2 ..], " \t"); +} + +const Out = struct { + p: *Pardes, + text: std.Io.Writer.Allocating, + rows: std.ArrayList(Row) = .empty, + + fn deinit(out: *Out) void { + out.text.deinit(); + for (out.rows.items) |r| { + out.p.gpa.free(r.path); + out.p.gpa.free(r.colors); + } + out.rows.deinit(out.p.gpa); + } + + const Meta = struct { + kind: @FieldType(Row, "kind"), + declaration: bool = false, + at: @FieldType(Row, "at"), + location_end: usize = 0, + code_start: usize = 0, + colors: []const u8 = &.{}, + }; + + /// One row: its text, a newline, and its metadata. + fn row(out: *Out, text: []const u8, path: []const u8, meta: Meta) !void { + const gpa = out.p.gpa; + try out.text.writer.writeAll(text); + try out.text.writer.writeByte('\n'); + const owned_path = try gpa.dupe(u8, path); + errdefer gpa.free(owned_path); + const colors = try gpa.dupe(u8, meta.colors); + errdefer gpa.free(colors); + try out.rows.append(gpa, .{ + .kind = meta.kind, + .declaration = meta.declaration, + .path = owned_path, + .at = meta.at, + .location_end = meta.location_end, + .code_start = meta.code_start, + .colors = colors, + }); + } +}; + +/// The file a diff section names, as found from the pane's directory or +/// one above it (a patch kept in a subdirectory of its repository). +const SourceMemo = struct { + path: []const u8 = "", + /// The name a look from the pane's directory resolves; null when the + /// file is nowhere to be found. + shown: ?[]const u8 = null, + lines: []const []const u8 = &.{}, + declarations: []const syntax.ContextDeclaration = &.{}, +}; + +/// Where a +Diff of `content`, a diff in `dir`, stands: the directory its +/// first file is found from (`dir` or one above it, as `findSource` looks), +/// so its rows name their files as the diff does; `dir` when none is found. +pub fn sourceRoot(p: *Pardes, dir: []const u8, content: []const u8) []const u8 { + var walk: diff.Walk = .{}; + var lines = std.mem.splitScalar(u8, content, '\n'); + const path = while (lines.next()) |line| { + if (walk.step(line).kind == .hunk and walk.path().len > 0) break walk.path(); + } else return dir; + var base: []const u8 = dir; + for (0..8) |_| { + if (locations.sourceText(p, p.scratch.allocator(), base, path) != null) return base; + base = std.fs.path.dirname(base) orelse return dir; + } + return dir; +} + +fn findSource(p: *Pardes, memo: *SourceMemo, dir: []const u8, path: []const u8) !void { + if (std.mem.eql(u8, memo.path, path)) return; + const arena = p.scratch.allocator(); + memo.* = .{ .path = path }; + // ponytail: eight directories up; a repository deeper than that under + // its patch is looked for from the patch's own directory only. + var base: []const u8 = dir; + for (0..8) |_| { + if (locations.sourceText(p, arena, base, path)) |text| { + memo.shown = if (base.ptr == dir.ptr) path else try std.fs.path.relativePosix(arena, "/", dir, text.path); + var lines: std.ArrayList([]const u8) = .empty; + var split = std.mem.splitScalar(u8, text.bytes, '\n'); + while (split.next()) |line| try lines.append(arena, std.mem.trimEnd(u8, line, "\r")); + memo.lines = lines.items; + var hit = p.locations_cache.get(p.tree_sitter_gpa, text.path, text.bytes, true, false) catch + locations.Cache.Hit{ .analysis = syntax.analyzeSource(arena, text.path, text.bytes, true, false) catch .{} }; + defer hit.deinit(p.tree_sitter_gpa); + // The cache's may go at its next use: kept for the section. + memo.declarations = try arena.dupe(syntax.ContextDeclaration, hit.analysis.declarations); + return; + } + base = std.fs.path.dirname(base) orelse return; + } +} + +/// Which side of the hunk the file on disk holds, the new one (the patch +/// applied) or the old one, and how far the file has moved it from where +/// the hunk says (`shift`, lines), as patch finds a hunk in a file edited +/// since. A file edited inside the hunk too still holds most of its lines: +/// the place holding the most of them wins (the nearer on a tie) if it +/// holds at least half. Only some, at the nearest place, could be a sibling +/// with the same lines (two functions with one signature's tail). The rows +/// are counted on that side, so moved. +const Side = enum { new, old, neither }; +const OnDisk = struct { side: Side, shift: i64 = 0 }; + +/// ponytail: a hunk moved more than this many lines is not looked for; +/// each try compares the hunk's lines, so a wider search costs that more. +const max_shift = 200; + +fn sideOnDisk(memo: *const SourceMemo, hunk: *const Hunk) OnDisk { + if (memo.shown == null) return .{ .side = .neither }; + var best: OnDisk = .{ .side = .neither }; + var best_held: usize = 0; + var best_of: usize = 1; + var shift: i64 = 0; + while (shift <= max_shift) : (shift += 1) { + for ([2]i64{ shift, -shift }) |by| { + inline for (.{ Side.new, Side.old }) |side| { + const start: i64 = @as(i64, @intCast((if (side == .new) hunk.new_start else hunk.old_start) -| 1)) + by; + if (start >= 0) { + const got = heldAt(memo, hunk, side, @intCast(start)); + if (got.held == got.of) return .{ .side = side, .shift = by }; + // A larger share only: the nearer keeps a tie. + if (got.held * best_of > best_held * got.of) { + best = .{ .side = side, .shift = by }; + best_held = got.held; + best_of = got.of; + } + } + } + if (shift == 0) break; + } + } + return if (best_held > 0 and best_held * 2 >= best_of) best else .{ .side = .neither }; +} + +/// How many of the hunk's `side` lines the file holds from row `start` on, +/// of how many: blank lines, which match anywhere, count for neither. +fn heldAt(memo: *const SourceMemo, hunk: *const Hunk, comptime side: Side, start: usize) struct { held: usize, of: usize } { + var row = start; + var held: usize = 0; + var of: usize = 0; + for (hunk.lines.items) |line| { + const skipped = if (side == .new) line.kind == .removed else line.kind == .added; + if (skipped) continue; + defer row += 1; + if (std.mem.trim(u8, line.code, " \t").len == 0) continue; + of += 1; + if (row < memo.lines.len and std.mem.eql(u8, memo.lines[row], line.code)) held += 1; + } + return .{ .held = held, .of = @max(of, 1) }; +} + +fn flush(out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []const u8) !void { + defer hunk.* = .{}; + if (hunk.path.len == 0 or hunk.lines.items.len == 0) return; + const p = out.p; + const arena = p.scratch.allocator(); + try findSource(p, memo, dir, hunk.path); + const disk = sideOnDisk(memo, hunk); + const side = disk.side; + // A line number of the hunk's, where the file has it now. + const moved = struct { + fn by(n: usize, shift: i64) usize { + return @intCast(@max(0, @as(i64, @intCast(n)) + shift)); + } + }.by; + const shown = if (side == .neither) hunk.path else memo.shown.?; + const lines = hunk.lines.items; + + // Where the hunk changes something, on the side its rows count: the + // place its label opens. + const first_change = for (lines) |line| { + if (line.kind != .context) break line; + } else lines[0]; + const on_old = side == .old or (side == .neither and hunk.deleted); + const start_row = moved(if (on_old) hunk.old_start else hunk.new_start, disk.shift) -| 1; + const change_row = moved(if (on_old) first_change.old else first_change.new, disk.shift) -| 1; + + // The declarations it stands in, outermost first, as a result's + // tree-sitter context: each one's header rows above the hunk. + var depth: usize = 0; + if (side != .neither) for (memo.declarations) |declaration| { + if (declaration.start_line >= start_row) break; + if (declaration.end_line < change_row) continue; + depth += 1; + var row = declaration.start_line; + while (row <= declaration.header_end_line and row < start_row) : (row += 1) { + const at: @FieldType(Row, "at") = .{ .line = row + 1 }; + if (row == declaration.start_line and p.locations_config.tslocations) { + const label = try std.fmt.allocPrint(arena, "{s}:{d}", .{ shown, row + 1 }); + try out.row(label, shown, .{ .kind = .context, .declaration = true, .at = at, .location_end = label.len, .code_start = label.len }); + } + // A blank where a hunk line has its marker: the code aligns. + try out.row(try std.fmt.allocPrint(arena, " {s}", .{memo.lines[row]}), shown, .{ .kind = .context, .declaration = true, .at = at }); + } + }; + + // The hunk's label: a step for n and N, and a look's place. + const line_no = change_row + 1; + var label: std.Io.Writer.Allocating = .init(arena); + try label.writer.print("{s}:{d}", .{ shown, line_no }); + const location_end = label.written().len; + if (depth > 0) { + try label.writer.writeByte(' '); + try label.writer.splatByteAll('*', depth); + } + try out.row(label.written(), shown, .{ .kind = .match, .at = .{ .line = line_no }, .location_end = location_end, .code_start = label.written().len }); + // No file to read declarations from: git's own function line, muted + // the same way. With one, git's guess (the last line before the hunk + // that looked like a function) would only contradict it. + if (side == .neither and hunk.header.len > 0) + try out.row(try std.fmt.allocPrint(arena, " {s}", .{hunk.header}), shown, .{ .kind = .context, .declaration = true, .at = .{ .line = line_no } }); + + // Each run of removed lines and the added lines after it: the words + // they changed. + var i: usize = 0; + while (i < lines.len) { + if (lines[i].kind == .context) { + i += 1; + continue; + } + const minus_start = i; + while (i < lines.len and lines[i].kind == .removed) i += 1; + const plus_start = i; + while (i < lines.len and lines[i].kind == .added) i += 1; + try inferEdits(arena, lines[minus_start..plus_start], lines[plus_start..i]); + } + + // Each line behind its marker, `+`, `-` or a blank, as the diff + // has it: the marker coloured, the line as its file's. + for (lines) |line| { + const flag: u8 = switch (line.kind) { + .added => syntax.diff_added, + .removed => syntax.diff_removed, + else => 0, + } | @as(u8, if (line.kind != .context and !line.paired) syntax.diff_whole else 0); + const text = try std.fmt.allocPrint(arena, "{c}{s}", .{ @as(u8, switch (line.kind) { + .added => '+', + .removed => '-', + else => ' ', + }), line.code }); + const colors = try arena.alloc(u8, text.len); + colors[0] = flag; + @memcpy(colors[1..], line.styles); + const on = moved(if (on_old) line.old else line.new, disk.shift); + try out.row(text, shown, .{ .kind = .preview, .at = .{ .line = @max(1, on) }, .colors = colors }); + } +} + +// ---- the words a changed line changed (delta's edits.rs) ---- + +/// delta's `max-line-distance`: a removed and an added line further apart +/// than this are not one line changed, and neither is emphasised. +const max_line_distance = 0.6; + +/// ponytail: a run of more removed or added lines than this, or a pair +/// whose token table is bigger than `max_cells`, is shown unemphasised +/// rather than aligned at a quadratic cost (delta aligns them all). +const max_run = 256; +const max_cells = 1 << 16; + +/// Pair each removed line with the first added line after the last one +/// paired that is near enough to it, in order, and emphasise in both the +/// tokens one has and the other has not. +fn inferEdits(arena: std.mem.Allocator, minus: []HunkLine, plus: []HunkLine) !void { + if (minus.len == 0 or plus.len == 0 or minus.len > max_run or plus.len > max_run) return; + var plus_index: usize = 0; + for (minus) |*m| { + const m_tokens = try tokenize(arena, m.code); + var j = plus_index; + while (j < plus.len) : (j += 1) { + const p_tokens = try tokenize(arena, plus[j].code); + if ((m_tokens.len + 1) * (p_tokens.len + 1) > max_cells) continue; + var alignment = try Alignment.init(arena, m_tokens, p_tokens); + const marks = try annotate(arena, &alignment, m.code, plus[j].code); + if (marks.distance > max_line_distance) continue; + for (marks.minus) |r| for (m.styles[r[0]..r[1]]) |*b| { + b.* |= syntax.diff_emph; + }; + for (marks.plus) |r| for (plus[j].styles[r[0]..r[1]]) |*b| { + b.* |= syntax.diff_emph; + }; + m.paired = true; + plus[j].paired = true; + plus_index = j + 1; + break; + } + } +} + +/// delta's tokenize with its default `\w+`: a leading empty token, each +/// run of word characters one token, and every other character one. A +/// line starting with no word gets a second empty token, as delta's does. +/// ponytail: any byte past ASCII counts as a word character, close to +/// Unicode `\w` for letters; a non-ASCII punctuation mark joins a word. +fn tokenize(arena: std.mem.Allocator, line: []const u8) ![]const []const u8 { + var tokens: std.ArrayList([]const u8) = .empty; + try tokens.append(arena, ""); + if (line.len > 0 and !isWord(line[0])) try tokens.append(arena, ""); + var at: usize = 0; + while (at < line.len) { + var end = at + 1; + // A byte past ASCII is a word's, so what is left is one byte. + if (isWord(line[at])) while (end < line.len and isWord(line[end])) { + end += 1; + }; + try tokens.append(arena, line[at..end]); + at = end; + } + return tokens.items; +} + +fn isWord(c: u8) bool { + return std.ascii.isAlphanumeric(c) or c == '_' or c >= 0x80; +} + +const Op = enum(u2) { noop, deletion, insertion }; + +/// delta's align.rs: a Needleman-Wunsch table over two token lists, a +/// change costing more where it starts a new run, so changes group. +const Alignment = struct { + x: []const []const u8, + y: []const []const u8, + cells: []Cell, + width: usize, + + const Cell = struct { parent: u32, op: Op, cost: u32 }; + const deletion_cost = 2; + const insertion_cost = 2; + const initial_mismatch_penalty = 1; + const never = std.math.maxInt(u32); + + fn init(arena: std.mem.Allocator, x: []const []const u8, y: []const []const u8) !Alignment { + const width = x.len + 1; + const cells = try arena.alloc(Cell, width * (y.len + 1)); + @memset(cells, .{ .parent = 0, .op = .noop, .cost = 0 }); + var a: Alignment = .{ .x = x, .y = y, .cells = cells, .width = width }; + for (1..width) |i| cells[i] = .{ .parent = 0, .op = .deletion, .cost = @intCast(i * deletion_cost + initial_mismatch_penalty) }; + for (1..y.len + 1) |j| cells[j * width] = .{ .parent = 0, .op = .insertion, .cost = @intCast(j * insertion_cost + initial_mismatch_penalty) }; + for (x, 0..) |x_i, i| for (y, 0..) |y_j, j| { + const left = a.index(i, j + 1); + const diag = a.index(i, j); + const up = a.index(i + 1, j); + // Ties go to the first: an insertion, then a deletion, then a + // match, so a moved token reads as removed then added. + const candidates = [3]Cell{ + .{ .parent = @intCast(up), .op = .insertion, .cost = a.mismatchCost(up, insertion_cost) }, + .{ .parent = @intCast(left), .op = .deletion, .cost = a.mismatchCost(left, deletion_cost) }, + .{ .parent = @intCast(diag), .op = .noop, .cost = if (std.mem.eql(u8, x_i, y_j)) cells[diag].cost else never }, + }; + var best = candidates[0]; + for (candidates[1..]) |c| if (c.cost < best.cost) { + best = c; + }; + cells[a.index(i + 1, j + 1)] = best; + }; + return a; + } + + fn mismatchCost(a: *const Alignment, parent: usize, basic: u32) u32 { + const cell = a.cells[parent]; + return cell.cost +| basic +| @as(u32, if (cell.op == .noop) initial_mismatch_penalty else 0); + } + + fn index(a: *const Alignment, i: usize, j: usize) usize { + return j * a.width + i; + } + + /// The operations read back from the table's far corner, in order, + /// each run as one (op, count). + fn coalesced(a: *const Alignment, arena: std.mem.Allocator) ![]const struct { Op, usize } { + var ops: std.ArrayList(Op) = .empty; + var cell = a.cells[a.index(a.x.len, a.y.len)]; + while (true) { + try ops.append(arena, cell.op); + if (cell.parent == 0) break; + cell = a.cells[cell.parent]; + } + std.mem.reverse(Op, ops.items); + var runs: std.ArrayList(struct { Op, usize }) = .empty; + for (ops.items) |op| { + if (runs.items.len > 0 and runs.items[runs.items.len - 1][0] == op) { + runs.items[runs.items.len - 1][1] += 1; + } else try runs.append(arena, .{ op, 1 }); + } + return runs.items; + } +}; + +const Marks = struct { + /// Byte ranges of the removed and the added line to emphasise. + minus: []const [2]usize, + plus: []const [2]usize, + distance: f64, +}; + +/// delta's annotate: walk the alignment's runs over both lines, marking +/// what each deleted and inserted, and a run of blanks between two changes +/// with them; the distance is the changed width over the whole width (a +/// kept section counting on both lines). +fn annotate(arena: std.mem.Allocator, a: *const Alignment, minus_line: []const u8, plus_line: []const u8) !Marks { + var minus: std.ArrayList([2]usize) = .empty; + var plus: std.ArrayList([2]usize) = .empty; + var x_off: usize = 0; + var y_off: usize = 0; + var m_byte: usize = 0; + var p_byte: usize = 0; + var numer: usize = 0; + var denom: usize = 0; + var minus_prev: Op = .noop; + var plus_prev: Op = .noop; + const Take = struct { + fn section(tokens: []const []const u8, off: *usize, byte: *usize, n: usize, line: []const u8) [2]usize { + const start = byte.*; + const end_tok = @min(tokens.len, off.* + n); + for (tokens[@min(off.*, end_tok)..end_tok]) |t| byte.* += t.len; + off.* = end_tok; + byte.* = @min(byte.*, line.len); + return .{ start, byte.* }; + } + }; + for (try a.coalesced(arena)) |run| { + const op, const n = run; + switch (op) { + .deletion => { + const r = Take.section(a.x, &x_off, &m_byte, n, minus_line); + const w = trimmedWidth(minus_line[r[0]..r[1]]); + numer += w; + denom += w; + try minus.append(arena, r); + minus_prev = .deletion; + }, + .noop => { + const r = Take.section(a.x, &x_off, &m_byte, n, minus_line); + const section = minus_line[r[0]..r[1]]; + denom += 2 * trimmedWidth(section); + const is_space = std.mem.trim(u8, section, " \t").len == 0; + const coalesce = is_space and + ((minus_prev == .deletion and plus_prev == .insertion and + (x_off < a.x.len -| 1 or y_off < a.y.len -| 1)) or + (minus_prev == .noop and plus_prev == .noop)); + if (coalesce and minus_prev == .deletion) try minus.append(arena, r); + const pr = Take.section(a.y, &y_off, &p_byte, n, plus_line); + if (coalesce and plus_prev == .insertion) try plus.append(arena, pr); + minus_prev = .noop; + plus_prev = .noop; + }, + .insertion => { + const r = Take.section(a.y, &y_off, &p_byte, n, plus_line); + const w = trimmedWidth(plus_line[r[0]..r[1]]); + numer += w; + denom += w; + try plus.append(arena, r); + plus_prev = .insertion; + }, + } + } + const distance: f64 = if (denom > 0) @as(f64, @floatFromInt(numer)) / @as(f64, @floatFromInt(denom)) else 0; + return .{ .minus = minus.items, .plus = plus.items, .distance = distance }; +} + +fn trimmedWidth(section: []const u8) usize { + return pardes.panes.File.displayWidth(std.mem.trim(u8, section, " \t")); +} + +// ---- tests ---- + +const testing = std.testing; + +fn emphasised(line: HunkLine) ![]const u8 { + var out: std.ArrayList(u8) = .empty; + for (line.code, line.styles) |c, s| try out.append(testing.allocator, if (s & syntax.diff_emph != 0) c else '.'); + return out.toOwnedSlice(testing.allocator); +} + +fn expectEmphasis(minus: []const u8, plus: []const u8, want_minus: []const u8, want_plus: []const u8) !void { + var arena_state: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + var m = [_]HunkLine{.{ .kind = .removed, .code = minus, .styles = try arena.alloc(u8, minus.len), .old = 1, .new = 1 }}; + var p = [_]HunkLine{.{ .kind = .added, .code = plus, .styles = try arena.alloc(u8, plus.len), .old = 2, .new = 1 }}; + @memset(m[0].styles, 0); + @memset(p[0].styles, 0); + try inferEdits(arena, &m, &p); + const got_minus = try emphasised(m[0]); + defer testing.allocator.free(got_minus); + const got_plus = try emphasised(p[0]); + defer testing.allocator.free(got_plus); + try testing.expectEqualStrings(want_minus, got_minus); + try testing.expectEqualStrings(want_plus, got_plus); +} + +test "delta's emphasis: the word a line changed, in both lines" { + try expectEmphasis(" let x = foo(1);", " let x = bar(1);", "............foo....", "............bar...."); + try expectEmphasis("a b c", "a x c", "..b..", "..x.."); +} + +test "delta's emphasis: lines too far apart are no change of one another" { + try expectEmphasis("completely different text", "nothing alike here at all", ".........................", "........................."); +} + +test "delta's emphasis: a word added keeps the rest plain" { + try expectEmphasis("fn run(a: u32)", "fn run(a: u32, b: u32)", "..............", "............., b: u32."); +} + +test "delta's alignment: kitten to sitting, as align.rs has it" { + var arena_state: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + // One token a letter, as delta's test splits them, behind the empty one. + const x = [_][]const u8{ "", "k", "i", "t", "t", "e", "n" }; + const y = [_][]const u8{ "", "s", "i", "t", "t", "i", "n", "g" }; + const a = try Alignment.init(arena, &x, &y); + var ops: std.ArrayList(Op) = .empty; + for (try a.coalesced(arena)) |run| for (0..run[1]) |_| try ops.append(arena, run[0]); + try testing.expectEqualSlices(Op, &.{ .noop, .deletion, .insertion, .noop, .noop, .noop, .deletion, .insertion, .noop, .insertion }, ops.items); +} + +test "a diff stacks to a label a hunk and its lines, markers gone, tinted and stepped" { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const patch = + \\diff --git a/nowhere/x.txt b/nowhere/x.txt + \\--- a/nowhere/x.txt + \\+++ b/nowhere/x.txt + \\@@ -1,3 +1,3 @@ section one + \\ keep + \\-old value + \\+new value + \\ tail + \\ + ; + const result = try format(p, "/pardes-surely-missing-dir", patch); + defer p.gpa.free(result.content); + defer locations.freeRows(p.gpa, result.rows); + try testing.expectEqualStrings("nowhere/x.txt:2\n section one\n keep\n-old value\n+new value\n tail\n", result.content); + try testing.expectEqual(@as(usize, 6), result.rows.len); + try testing.expectEqual(.match, result.rows[0].kind); + try testing.expectEqual(@as(usize, "nowhere/x.txt:2".len), result.rows[0].location_end); + try testing.expect(result.rows[1].declaration); + const removed = result.rows[3]; + try testing.expect(removed.colors[0] & syntax.diff_removed != 0); + // Paired with the line it changed: no whole-line tint. + try testing.expect(removed.colors[0] & syntax.diff_whole == 0); + try testing.expect(removed.colors[1] & syntax.diff_emph != 0); + try testing.expect(removed.colors[5] & syntax.diff_emph == 0); + try testing.expect(result.rows[4].colors[0] & syntax.diff_added != 0); + try testing.expect(result.rows[2].colors[0] & (syntax.diff_added | syntax.diff_removed) == 0); +} + +test "a hunk the file has moved since is found where it went, inside its declaration" { + if (!syntax.supportsPath("a.zig")) return error.SkipZigTest; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + // Two lines more above it than the patch knows of. + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = "// one\n// two\nconst S = struct {\n fn f() void {\n a();\n b();\n }\n};\n" }); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = buf[0..try tmp.dir.realPath(testing.io, &buf)]; + const patch = + \\--- a.zig + \\+++ a.zig + \\@@ -3,3 +3,3 @@ git's guess + \\ fn f() void { + \\- c(); + \\+ a(); + \\ b(); + \\ + ; + const result = try format(p, dir, patch); + defer p.gpa.free(result.content); + defer locations.freeRows(p.gpa, result.rows); + try testing.expect(std.mem.indexOf(u8, result.content, "a.zig:3\n const S = struct {\na.zig:5 *\n") != null); + try testing.expect(std.mem.indexOf(u8, result.content, "git's guess") == null); +} + +test "a mailed patch keeps its headers, message and diffstat above its hunks" { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const patch = + \\From 0123 Mon Sep 17 00:00:00 2001 + \\Subject: [PATCH] change x + \\ + \\Why it changed. + \\--- + \\ x.txt | 2 +- + \\ + \\diff --git a/x.txt b/x.txt + \\index 1..2 100644 + \\--- a/x.txt + \\+++ b/x.txt + \\@@ -1 +1 @@ + \\-a + \\+b + \\ + ; + const result = try format(p, "/pardes-surely-missing-dir", patch); + defer p.gpa.free(result.content); + defer locations.freeRows(p.gpa, result.rows); + try testing.expectEqualStrings("From 0123 Mon Sep 17 00:00:00 2001\nSubject: [PATCH] change x\n\nWhy it changed.\n---\n x.txt | 2 +-\n\nx.txt:1\n-a\n+b\n", result.content); +} + +test "DiffLook hunks: a .patch looked at opens its +Diff; Diff goes to the text and back; DiffLook text opens the text" { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "x.txt", .data = "b\n" }); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "c.patch", .data = "--- x.txt\n+++ x.txt\n@@ -1 +1 @@\n-a\n+b\n" }); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = buf[0..try tmp.dir.realPath(testing.io, &buf)]; + const patch = try std.fs.path.join(testing.allocator, &.{ dir, "c.patch" }); + defer testing.allocator.free(patch); + const hunks_path = try std.fs.path.join(testing.allocator, &.{ dir, "+Diff" }); + defer testing.allocator.free(hunks_path); + const Count = struct { + fn of(pp: *Pardes, path: []const u8) usize { + var n: usize = 0; + for (pp.panes) |slot| if (slot) |pane| if (pane.file) |f| { + n += @intFromBool(std.mem.eql(u8, f.path, path)); + }; + return n; + } + }; + try testing.expectEqual(pardes.config.Runtime.DiffLook.hunks, p.settings.diff_look); + pardes.look.lookAt(p, 0, patch); + try testing.expectEqual(@as(usize, 1), Count.of(p, hunks_path)); + try testing.expectEqual(@as(usize, 0), Count.of(p, patch)); + const hid = p.active; + try testing.expectEqualStrings(hunks_path, p.panes[hid].?.file.?.path); + try testing.expectEqualStrings("x.txt:1\n-a\n+b\n", p.panes[hid].?.file.?.content); + // Diff on it: the patch as text. + try testing.expect(p.executeBuiltinLine(hid, "Diff")); + try testing.expectEqual(@as(usize, 1), Count.of(p, patch)); + const raw = p.active; + try testing.expectEqualStrings(patch, p.panes[raw].?.file.?.path); + // Diff on the text: the +Diff again, refilled, not another. + try testing.expect(p.executeBuiltinLine(raw, "Diff")); + try testing.expectEqual(@as(usize, 1), Count.of(p, hunks_path)); + // DiffLook text: a look opens the text (here the pane already open). + try testing.expect(p.executeBuiltinLine(0, "DiffLook text")); + try p.removePane(raw, null); + pardes.look.lookAt(p, 0, patch); + try testing.expectEqual(@as(usize, 1), Count.of(p, patch)); +} + +test "a hunk edited since, beside siblings with its signature's tail, is found in its own function" { + if (!syntax.supportsPath("a.rs")) return error.SkipZigTest; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + // Three functions ending in one signature's tail; the patch is for the + // third, which has moved down a line and had a line inside it edited. + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.rs", .data = + \\// moved + \\fn one( + \\ limit: usize, + \\) -> u32 { + \\ 1 + \\} + \\fn two( + \\ limit: usize, + \\) -> u32 { + \\ 2 + \\} + \\fn three( + \\ limit: usize, + \\) -> u32 { + \\ let guard = enter(); + \\ let a = 3; + \\ let b = a + 1; + \\ let c = b * 2; // edited since + \\ c + \\} + \\ + }); + var buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = buf[0..try tmp.dir.realPath(testing.io, &buf)]; + const patch = + \\--- a.rs + \\+++ a.rs + \\@@ -12,7 +12,8 @@ git's guess + \\ limit: usize, + \\ ) -> u32 { + \\+ let guard = enter(); + \\ let a = 3; + \\ let b = a + 1; + \\ let c = b * 2; + \\ c + \\ + ; + const result = try format(p, dir, patch); + defer p.gpa.free(result.content); + defer locations.freeRows(p.gpa, result.rows); + try testing.expect(std.mem.indexOf(u8, result.content, "a.rs:12\n fn three(\na.rs:15 *\n") != null); +} diff --git a/src/locations.zig b/src/locations.zig index 6a604907..7755f6fd 100644 --- a/src/locations.zig +++ b/src/locations.zig @@ -159,7 +159,9 @@ const Pending = struct { const Source = struct { path: []const u8, bytes: []const u8 }; -fn sourceText(p: *pardes.Pardes, arena: std.mem.Allocator, dir: []const u8, path: []const u8) ?Source { +/// A file's text as a look from `dir` finds it: an open pane's, unsaved +/// edits and all, else the disk's. Null for a PDF or one not there. +pub fn sourceText(p: *pardes.Pardes, arena: std.mem.Allocator, dir: []const u8, path: []const u8) ?Source { if (std.ascii.eqlIgnoreCase(std.fs.path.extension(path), ".pdf")) return null; const lexical = std.fs.path.resolvePosix(arena, &.{ dir, path }) catch return null; var pathbuf: [4096]u8 = undefined; diff --git a/src/look.zig b/src/look.zig index 41cfdc0c..6ba6a8d0 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1869,6 +1869,18 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { const before = p.active; var opened: ?usize = null; if (!focusPaneByPath(p, target.path, target.at)) { + // A .diff or .patch looked at bare: its hunks stacked in a + // +Diff (DiffLook hunks), which takes the keyboard as the + // file would; one with none in it opens as text. + if (p.settings.diff_look == .hunks and !p.look_text and target.at.line == 0 and + (std.mem.endsWith(u8, target.path, ".diff") or std.mem.endsWith(u8, target.path, ".patch"))) + if (filesystem.read(p, target.path)) |bytes| { + defer p.gpa.free(bytes); + if (panes.Output.openDiff(p, id, target.path, bytes)) |hid| { + p.active = hid; + return; + } else |_| {} + } else |_| {}; const free = p.freeSlot() orelse return p.reportError(id, "look", error.NoPaneSlots); const nt = panes.File.open(p, free, target.path, target.at.line) catch |err| return lookOpenFailed(p, id, target.path, err); diff --git a/src/main.zig b/src/main.zig index ed70b624..26259b43 100644 --- a/src/main.zig +++ b/src/main.zig @@ -102,7 +102,7 @@ const help_text = ; /// `pardes -` inside a session: `text`, stdin as it came, escapes and all, -/// into the directory's one +Pager (/pager, refilled when it is there): +/// into a new +Pager of the directory (/pager): /// written after the directory on that one open, the session parses it /// (pager.zig) and puts it in as one undo step, left clean. A text the /// session would not take is never lost: it goes to stderr, a terminal, diff --git a/src/mouse.zig b/src/mouse.zig index 8020fda8..733479dd 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -1288,7 +1288,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { pane.sel[sel_slot].state = .none; pane.body.vsel = .{ .active = true, .row = @intCast(a.row), .col = @intCast(a.col), .explicit = true }; }; - if (s.ctrl) p.lspRequest(s.id, .definition, ""); + if (s.ctrl) exec.runBuiltin(p, .Def, s.id, "", null); } } else { const clk = pane.sel[b]; diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index c9ce41e1..e6e738a5 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -682,7 +682,7 @@ pub fn readRoot(p: *Pardes, req: Req) Reply { } /// /pager, `pardes -`'s: the directory written (empty, or not absolute: the -/// session's) gets its one +Pager, made or emptied; the serial is what a +/// session's) gets a new +Pager; the serial is what a /// read of this same open answers, never another client's. What the open /// writes after that line is the text, held by tree.zig for `fillPager`. pub fn writePager(p: *Pardes, req: Req) Reply { @@ -742,6 +742,16 @@ pub fn fillPager(p: *Pardes, serial: u32, held: *std.ArrayList(u8)) error{OutOfM panes.File.setContent(p, f, page.text); f.pager_spans = page.spans; f.saved_revision = f.revision; + // A diff paged (`git show`, difftui's patches): its hunks stacked in a + // +Diff (DiffLook hunks), the +Pager folded to its tag under it for + // Diff to bring back. The keyboard stays where it was, as a page's. + if (f.pager_diff and p.settings.diff_look == .hunks) { + const keyboard = p.active; + if (panes.Output.openDiff(p, id, f.path, f.content)) |_| { + if (!pane.collapsed) pardes.layout.toggleCollapse(p, id); + } else |_| {} + if (p.panes[keyboard] != null) p.active = keyboard; + } } /// The editor's step: the text of /pager opens closed unread goes in. @@ -2258,7 +2268,8 @@ test "a builtin for one kind of pane is refused on another, and still acts on it .{ "Petscii\n", "Petscii: only an image or a terminal pane takes it" }, .{ "Palette\n", "Palette: only an image pane takes it" }, .{ "Ascii\n", "Ascii: only an image pane takes it" }, - .{ "Filter\n", "Filter: only a terminal pane takes it" }, + .{ "Filter\n", "Filter: only a terminal or a +Pager pane takes it" }, + .{ "Diff\n", "Diff: only a diff or a +Diff pane takes it" }, .{ "Togglettymode\n", "Togglettymode: only a terminal pane takes it" }, }; for (cases) |case| { @@ -4607,10 +4618,15 @@ test "pager answers its +Pager on the open that asked, whatever another client e try testing.expectEqual(E.INVAL, call(p, .{ .tag = 8, .op = .write, .node = pager, .handle = refused, .data = "relative\n" }).errno()); try testing.expectEqualStrings("", call(p, .{ .tag = 9, .op = .read, .node = pager, .handle = refused, .size = 64 }).bytes); _ = call(p, .{ .tag = 10, .op = .release, .node = pager, .handle = refused, .opened = true }); - // Resolved: `/tmp/../tmp/.` is /tmp's +Pager, the one made above. + // Resolved: `/tmp/../tmp/.` is /tmp, a +Pager of its own beside the + // one made above, which keeps its page. const resolved = call(p, .{ .tag = 11, .op = .open, .node = pager, .omode = 2 }).reply.handle; try testing.expectEqual(Status.ok, call(p, .{ .tag = 12, .op = .write, .node = pager, .handle = resolved, .data = "/tmp/../tmp/.\n" }).reply.status); - try testing.expectEqualStrings(want, call(p, .{ .tag = 13, .op = .read, .node = pager, .handle = resolved, .size = 64 }).bytes); + const second = call(p, .{ .tag = 13, .op = .read, .node = pager, .handle = resolved, .size = 64 }).bytes; + try testing.expect(!std.mem.eql(u8, want, second)); + const second_pane = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trim(u8, second, "\n"), 10)).?].?; + try testing.expectEqualStrings("/tmp/+Pager", second_pane.file.?.path); + try testing.expect(p.paneBySerial(paged) != null); _ = call(p, .{ .tag = 14, .op = .release, .node = pager, .handle = resolved, .opened = true }); // One that may not be written is refused, permission denied. try testing.expectEqual(E.PERM, wr(p, pager, "/proc/1\n").errno()); @@ -4667,15 +4683,24 @@ test "what a /pager open writes after its directory is the text: plain in the bo // PagerColor off, and an open closed with no read: the same text, plain, // in at the editor's next step (a close through a mount never waits). p.settings.pager_color = false; + const kept = try testing.allocator.dupe(u8, f.content); + defer testing.allocator.free(kept); const shut = call(p, .{ .tag = 7, .op = .open, .node = pager, .omode = 1 }).reply.handle; try testing.expectEqual(Status.ok, call(p, .{ .tag = 8, .op = .write, .node = pager, .handle = shut, .data = "/tmp\n" }).reply.status); try testing.expectEqual(Status.ok, call(p, .{ .tag = 9, .op = .write, .node = pager, .handle = shut, .data = "\x1b[1;32mgreen\x1b[m\n" }).reply.status); _ = call(p, .{ .tag = 10, .op = .release, .node = pager, .handle = shut, .opened = true }); - try testing.expectEqualStrings("", f.content); + // A new +Pager: the first keeps its page. + try testing.expectEqualStrings(kept, f.content); + const next = for (p.panes) |slot| { + const other = slot orelse continue; + if (other == pn) continue; + if (other.file) |*of| if (std.mem.eql(u8, of.path, "/tmp/+Pager")) break of; + } else return error.NoPager; + try testing.expectEqualStrings("", next.content); fillClosedPagers(p); - try testing.expectEqualStrings("green\n", f.content); - try testing.expectEqual(@as(usize, 0), f.pager_spans.len); - try testing.expectEqual(f.revision, f.saved_revision); + try testing.expectEqualStrings("green\n", next.content); + try testing.expectEqual(@as(usize, 0), next.pager_spans.len); + try testing.expectEqual(next.revision, next.saved_revision); } test "a command pane an exec open was answered is leased to it while it stays open: another client's command gets a pane of its own" { diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index c78a1aa2..eedab43b 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -258,7 +258,7 @@ pub const TopFile = enum(u5) { /// The files opened lately, closed ones too, a line each: /// `open|closed `, most recent first. recent, - /// `pardes -`'s: a directory written, its +Pager made or emptied; a + /// `pardes -`'s: a directory written, a new +Pager made there; a /// read of the same open answers its serial. pager, diff --git a/src/normal.zig b/src/normal.zig index 93487e88..aec6b983 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -743,14 +743,15 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void .undo => return edit.doUndo(p, t), .redo => return edit.doRedo(p, t), }, - .lsp => |request| return p.lspRequest(p.active, switch (request) { - .definition => .definition, - .declaration => .declaration, - .type_definition => .type_definition, - .implementation => .implementation, - .references => .references, - .format => .format, - }, ""), + // gd and gr are the Def and Refs a tag shows, run as a click runs them. + .lsp => |request| return switch (request) { + .definition => exec.runBuiltin(p, .Def, p.active, "", null), + .references => exec.runBuiltin(p, .Refs, p.active, "", null), + .declaration => p.lspRequest(p.active, .declaration, ""), + .type_definition => p.lspRequest(p.active, .type_definition, ""), + .implementation => p.lspRequest(p.active, .implementation, ""), + .format => p.lspRequest(p.active, .format, ""), + }, .adjust_number => |delta| return edit.normalAdjustNumber(p, t, delta), .leader => if (p.macro.replaying == 0) { p.leader_on = true; diff --git a/src/pardes.zig b/src/pardes.zig index 2a74e441..29192c33 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -480,6 +480,7 @@ pub const Loc = struct { test { _ = @import("tagline.zig"); + _ = @import("hunks.zig"); _ = @import("builtins_json.zig"); _ = @import("exec.zig"); _ = @import("look.zig"); @@ -864,7 +865,7 @@ test "TreeContext command and custom tag survive a workspace round trip" { p.gpa.free(pane.file.?.path); pane.file.?.path = path; if (!panes.File.supportsContext(pane)) return error.SkipZigTest; - try std.testing.expectEqualStrings(tagline.context_pane_tail, tagline.curTail(pane)); + try std.testing.expectEqualStrings(if (lsp.speaks("/test.zig")) tagline.lsp_context_pane_tail else tagline.context_pane_tail, tagline.curTail(pane)); try std.testing.expect(!pane.file.?.tree_context); try std.testing.expect(p.executeBuiltinLine(0, "TreeContext on")); try std.testing.expect(pane.file.?.tree_context); @@ -920,7 +921,7 @@ test "Togglettymode builtin and keyboard chord share mode transitions including try std.testing.expectEqualStrings("unchanged\n", file.file.?.content); } -test "Filter is ordered after Del and toggles only its terminal pane" { +test "Filter is ordered after Del and toggles only its terminal or +Pager pane" { const testing = std.testing; const del = std.meta.stringToEnum(Builtin, "Del") orelse return error.MissingDelBuiltin; const filter = std.meta.stringToEnum(Builtin, "Filter") orelse return error.MissingFilterBuiltin; @@ -954,6 +955,17 @@ test "Filter is ordered after Del and toggles only its terminal pane" { try testing.expect(p.executeBuiltinLine(0, "Filter")); try testing.expect(first.tty_filter); try testing.expect(!second.tty_filter); + + // A +Pager opens filtered, with Filter on its tag and no line numbers; + // a second is a pane of its own. + const pager_id = try panes.Output.openPager(p, 0, "/tmp"); + const pager_pane = p.panes[pager_id].?; + try testing.expect(pager_pane.tty_filter); + try testing.expectEqualStrings(tagline.pager_pane_tail, tagline.curTail(pager_pane)); + try testing.expectEqual(@as(u16, 0), panes.File.gutterWidth(pager_pane)); + try testing.expect(p.executeBuiltinLine(pager_id, "Filter")); + try testing.expect(!pager_pane.tty_filter); + try testing.expect(try panes.Output.openPager(p, 0, "/tmp") != pager_id); } test "compact tag commands stay beside their own prefix across layout changes" { @@ -1194,6 +1206,73 @@ test "Lspwhy after a Hover asks to explain that hover, in its file at its place, try std.testing.expect(seen); } +test "Def and Refs are a speaking file's tag words; gd, gr and a 2-1 chord all run them" { + if (!lsp.supports.contains(.definition)) return error.SkipZigTest; + const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 24, .tty_only = true }); + defer p.deinit(); + const pane = try p.setTestFile("const alpha = 1;\nconst beta = alpha;\n"); + // A .txt has no server: no Def, no Refs. + try std.testing.expect(std.mem.indexOf(u8, tagline.curTail(pane), "Def") == null); + const f = &pane.file.?; + p.gpa.free(f.path); + f.path = try p.gpa.dupe(u8, "/tmp/x.zig"); + try std.testing.expect(std.mem.endsWith(u8, tagline.curTail(pane), " Def Refs")); + p.sync(); + while (p.nextEffect()) |_| {} + const Asked = struct { + fn one(q: *Pardes, kind: lsp.Kind) !u32 { + var at: ?u32 = null; + while (q.nextEffect()) |e| if (e == .lsp) { + try std.testing.expectEqual(kind, e.lsp.kind); + try std.testing.expectEqualStrings("", e.lsp.arg.slice()); + try std.testing.expect(at == null); + at = e.lsp.offset; + }; + q.lsp_wait = null; + return at orelse error.NothingAsked; + } + }; + // gd and gr: at the cursor, on `alpha`'s declaration. + pane.body.cur_row = 0; + pane.body.cur_col = 8; + p.update(.{ .key = .{ .cp = 'g' } }); + p.update(.{ .key = .{ .cp = 'd' } }); + try std.testing.expectEqual(@as(u32, 8), try Asked.one(p, .definition)); + p.update(.{ .key = .{ .cp = 'g' } }); + p.update(.{ .key = .{ .cp = 'r' } }); + try std.testing.expectEqual(@as(u32, 8), try Asked.one(p, .references)); + + const r = p.rects[0]; + const x0 = r.x + config.GUTTER + panes.File.gutterWidth(pane); + const use_y = p.bodyTop(pane, r) + 1; + const tag = try tagline.tagText(p, p.scratch.allocator(), pane); + for ([_]struct { word: []const u8, kind: lsp.Kind }{ .{ .word = " Def ", .kind = .definition }, .{ .word = " Refs", .kind = .references } }) |w| { + // B1 sweeps the use of `alpha` on the second line (bytes 30..35), + // leaving the cursor at its far end. + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = x0 + 13, .row = use_y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .drag, .col = x0 + 17, .row = use_y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = x0 + 17, .row = use_y } }); + // B2 on the tag word, B1 clicked while it is held: the sweep is its + // argument, and it asks at the start of `alpha`, not at the cursor. + const wx = r.x + TAG_TEXT_INSET + @as(u16, @intCast(std.mem.indexOf(u8, tag, w.word).? + 1)); + p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = wx, .row = r.y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = wx, .row = r.y } }); + p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = wx, .row = r.y } }); + p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = wx, .row = r.y } }); + try std.testing.expectEqual(@as(u32, 30), try Asked.one(p, w.kind)); + // Clicked bare, it asks at the cursor, where the sweep left it. + pane.body.cur_row = 0; + pane.body.cur_col = 2; + p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .press, .col = wx, .row = r.y } }); + p.update(.{ .mouse = .{ .button = config.exec_button, .kind = .release, .col = wx, .row = r.y } }); + try std.testing.expectEqual(@as(u32, 2), try Asked.one(p, w.kind)); + } + // A symbol the file does not hold is said, and nothing is asked. + exec.runBuiltin(p, .Def, 0, "", "gamma"); + try std.testing.expectError(error.NothingAsked, Asked.one(p, .definition)); + try std.testing.expectEqualStrings("Def: no gamma in this file", pane.msg[0..pane.msg_len]); +} + test "the Tutor pane is named +Tutor in the session's directory, never a bare path at the root" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); @@ -4508,6 +4587,9 @@ pub const Pardes = struct { chord_hold: bool = false, /// The look just run found nothing (look.zig missed). look_missed: bool = false, + /// The look being run opens a .diff or .patch as text whatever DiffLook + /// says: Diff going back from a +Diff, Edit's B (it edits the file). + look_text: bool = false, look_hover_wait: ?look.LookHoverWait = null, /// The place a look-hover last found nothing to open: the pointer /// resting there does not ask again every frame (look.noteLookHover). @@ -4748,6 +4830,8 @@ pub const Pardes = struct { const named = try std.fs.path.join(gpa, &.{ dir, "+Pager" }); gpa.free(shown.file.?.path); shown.file.?.path = named; + shown.file.?.pager = true; + shown.tty_filter = true; shown.file.?.pager_diff = panes.File.looksLikeDiff(content[0..@min(content.len, 64 * 1024)]); shown.file.?.pager_spans = page.spans; p.oneColumn(); @@ -6674,7 +6758,8 @@ pub const Pardes = struct { pub const SavePath = Effect.Buf(effect_path_cap); - pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg: []const u8) void { + pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8) void { + var arg = arg_in; if (!normal.multiOnce(p)) return; // one question per keystroke, from the primary // Lspwhy narrates the last query where it was asked -- that pane's // file, place and argument -- from wherever it is run. @@ -6697,10 +6782,30 @@ pub const Pardes = struct { (!zig_buf and std.mem.indexOfAny(u8, arg, " \t\r\n\"\\") != null)) return p.reportFailure(id, std.fmt.bufPrint(&said, "Rename: {s} is no name", .{arg}) catch "Rename: no name"); } - const off = if (pane.file) |f| modal.offsetAt(f.content, .{ + var off = if (pane.file) |f| modal.offsetAt(f.content, .{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)), }) else 0; + // Def or Refs given a symbol (a 2-1 chord's selection) asks at its + // occurrence nearest the cursor, which a sweep leaves at one end of + // what it selected; the server is asked at a place, never a name. + if ((kind == .definition or kind == .references) and arg.len > 0) { + const content = pane.file.?.content; + var nearest: ?usize = null; + var best: usize = 0; + var from: usize = 0; + while (std.mem.indexOfPos(u8, content, from, arg)) |at_hit| : (from = at_hit + 1) { + const d = if (at_hit > off) at_hit - off else off -| (at_hit + arg.len); + if (nearest != null and at_hit > off and d >= best) break; + if (nearest == null or d < best) { + nearest = at_hit; + best = d; + } + } + off = nearest orelse + return p.reportFailure(id, std.fmt.bufPrint(&said, "{s}: no {s} in this file", .{ lspWord(kind), arg }) catch "no such symbol in this file"); + arg = ""; + } // Lspwhy asks the last query again, narrated: its kind and argument, // at its place when asked from its pane. None yet: a definition. var explained: [160]u8 = undefined; @@ -6858,6 +6963,8 @@ pub const Pardes = struct { fn lspWord(kind: lsp.Kind) []const u8 { return switch (kind) { .hover => "Hover", + .definition => "Def", + .references => "Refs", .explain => "Lspwhy", .incoming_calls => "Callers", .outgoing_calls => "Callees", diff --git a/src/syntax.zig b/src/syntax.zig index b7406b04..89d96239 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -854,7 +854,13 @@ pub fn highlightLocationRows(gpa: std.mem.Allocator, content: []const u8, rows: if (comptime @hasField(@TypeOf(row), "location_end")) { address_only = row.location_end > 0 and source_start == end; } - if (!address_only) { + // A row its producer coloured whole is coloured below: no + // fragment of it to parse. + var coloured = false; + if (comptime @hasField(@TypeOf(row), "colors")) { + coloured = row.colors.len > 0 and row.colors.len >= end - source_start; + } + if (!address_only and !coloured) { sources[source_count] = .{ .index = index, .start = source_start, .len = end - source_start }; source_count += 1; } @@ -1037,10 +1043,15 @@ fn childOfKind(node: ts.Node, kind: []const u8) ?ts.Node { /// A diff line's style byte carries whether the line was added or removed /// over its syntax style (the low bits), so the painter can tint its row -/// and mark its prefix. +/// and mark its prefix; Diff marks the words a changed line changed +/// (hunks.zig), drawn on a stronger tint. pub const diff_added: u8 = 0x80; pub const diff_removed: u8 = 0x40; -pub const syn_bits: u8 = 0x3f; +pub const diff_emph: u8 = 0x20; +/// A +Diff line added or removed whole, paired with no line it changed: +/// its row takes a faint tint, on its marker's byte. +pub const diff_whole: u8 = 0x10; +pub const syn_bits: u8 = 0x0f; /// A file section's hunks are parsed together, each side as one text, in /// pieces: a piece takes whole hunks until it holds `diff_piece_lines` diff --git a/src/tagline.zig b/src/tagline.zig index d13f3c5f..cf0b17fd 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -21,6 +21,13 @@ pub const pdf_pane_tail = " " ++ config.pdf_pane_builtins_str; pub const file_pane_tail = " " ++ config.file_pane_builtins_str; pub const context_pane_tail = file_pane_tail ++ " TreeContext"; pub const locations_pane_tail = file_pane_tail ++ " LocationsConfig"; +/// A file a language server speaks for (by its extension): its jumps too. +pub const lsp_pane_tail = file_pane_tail ++ " " ++ config.lsp_pane_builtins_str; +pub const lsp_context_pane_tail = context_pane_tail ++ " " ++ config.lsp_pane_builtins_str; +pub const pager_pane_tail = " " ++ config.pager_pane_builtins_str; +pub const diff_pane_tail = " " ++ config.diff_pane_builtins_str; +pub const pager_diff_pane_tail = " " ++ config.pager_diff_pane_builtins_str; +pub const diff_view_tail = " " ++ config.diff_view_builtins_str ++ " LocationsConfig"; pub const terminal_pane_tail = " " ++ config.terminal_pane_builtins_str; pub const command_pane_tail = " " ++ config.command_pane_builtins_str; pub const dir_pane_tail = " " ++ config.dir_pane_builtins_str; @@ -164,10 +171,15 @@ pub fn curTail(pane: *Pane) []const u8 { pub fn defaultTail(pane: *const Pane) []const u8 { if (comptime pdf_enabled) if (pane.pdf != null) return pdf_pane_tail; if (pane.file) |file| if (file.listing != null) return dir_pane_tail; - if (pane.file) |file| if (file.output) |out| + if (pane.file) |file| if (file.pager) return if (file.pager_diff) pager_diff_pane_tail else pager_pane_tail; + if (pane.file != null and pane.colorAlgo() == .diff) return diff_pane_tail; + if (pane.file) |file| if (file.output) |out| { + if (std.meta.eql(out.from, panes.Output.Origin{ .cmd = .Diff })) return diff_view_tail; if (panes.Output.usesLocationsConfig(out.from)) return locations_pane_tail; - if (panes.File.supportsContext(pane)) return context_pane_tail; - if (pane.file != null) return file_pane_tail; + }; + const speaks = if (pane.file) |file| file.output == null and file.mini == null and pardes.lsp.speaks(file.path) else false; + if (panes.File.supportsContext(pane)) return if (speaks) lsp_context_pane_tail else context_pane_tail; + if (pane.file != null) return if (speaks) lsp_pane_tail else file_pane_tail; if (pane.command != null) return command_pane_tail; if (pane.isTerminal()) return if (pane.shell_tail_len > 0) pane.shell_tail[0..pane.shell_tail_len] else terminal_pane_tail; return pane_tail; diff --git a/src/terminal.zig b/src/terminal.zig index 3bb1fbda..3190c6e3 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -2041,7 +2041,7 @@ pub fn recolorAnsi(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16 const filtered: ?*FilteredColors = if (pane.tty_filter) blk: { const tz_filter = tracy.zone(@src(), "filterInit"); defer tz_filter.end(); - filtered_storage = FilteredColors.init(p, pane); + filtered_storage = FilteredColors.init(p, &pane.terminal.?.vt); break :blk &filtered_storage; } else null; // DECSCNM, read once: the filtered palette folds it in itself, the raw @@ -2192,7 +2192,9 @@ fn cellStyle(p: *Pardes, ci: ghostty_vt.PageList.Cell, filtered: ?*FilteredColor return cs; } -const FilteredColors = struct { +/// A program's colours mapped to the theme (Filter): a terminal's cells, or +/// a +Pager's spans (`vt` null, the program's palette xterm's own). +pub const FilteredColors = if (enabled) struct { source: GColor.Palette, target: *const GColor.Palette, theme_bg: GColor.RGB, @@ -2212,16 +2214,18 @@ const FilteredColors = struct { cache_key: [256]u8 = undefined, cache_valid: [256]bool = @splat(false), - fn init(p: *Pardes, pane: *const Pane) FilteredColors { + pub fn init(p: *Pardes, vt: ?*const ghostty_vt.Terminal) FilteredColors { var source = GColor.default; - for (&source, 0..) |*rgb, i| - rgb.* = pane.terminal.?.vt.colorForXterm(.{ .palette = @intCast(i) }) orelse rgb.*; + if (vt) |t| { + for (&source, 0..) |*rgb, i| + rgb.* = t.colorForXterm(.{ .palette = @intCast(i) }) orelse rgb.*; + } const theme = p.theme(); var theme_bg = asGhostRgb(theme.bg orelse theme.tag_bg); var theme_fg = asGhostRgb(theme.fg orelse theme.tag_fg); - var dynamic_bg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .background }); - var dynamic_fg = pane.terminal.?.vt.colorForXterm(.{ .dynamic = .foreground }); - if (pane.terminal.?.vt.modes.get(.reverse_colors)) { + var dynamic_bg = if (vt) |t| t.colorForXterm(.{ .dynamic = .background }) else null; + var dynamic_fg = if (vt) |t| t.colorForXterm(.{ .dynamic = .foreground }) else null; + if (vt != null and vt.?.modes.get(.reverse_colors)) { std.mem.swap(GColor.RGB, &theme_bg, &theme_fg); std.mem.swap(?GColor.RGB, &dynamic_bg, &dynamic_fg); } @@ -2280,6 +2284,18 @@ const FilteredColors = struct { return asPardesColor(self.keyedRgb(style.bg(cell, &self.source).?)); } + /// A +Pager span's colour (pager.zig), as `fg` and `bg` map a cell's. + pub fn spanColor(self: *FilteredColors, color: pardes.Color, is_bg: bool) pardes.Color { + return switch (color) { + .default => color, + .index => |idx| if (is_bg) self.bg_for_palette[idx] else self.fg_for_palette[idx], + .rgb => |rgb| blk: { + const keyed = self.keyedRgb(asGhostRgb(rgb)); + break :blk asPardesColor(if (is_bg) keyed else self.legible(keyed)); + }, + }; + } + fn legible(self: *const FilteredColors, rgb: GColor.RGB) GColor.RGB { if (contrastOf(luminanceOf(rgb), self.default_bg_luminance) >= config.tty_filter_min_contrast) return rgb; @@ -2317,7 +2333,7 @@ const FilteredColors = struct { self.cache_valid[slot] = true; return best; } -}; +} else struct {}; const channel_luminance: [256]f64 = blk: { @setEvalBranchQuota(20000); @@ -2570,7 +2586,7 @@ test "terminal Filter maps the default roles before it maps anything else" { // the null-page fallback that only the legacy dark theme exercises. for (0..9) |t| { p.settings.theme = @intCast(t); - const stage_one = FilteredColors.init(p, pane); + const stage_one = FilteredColors.init(p, &pane.terminal.?.vt); // `dark` declares no background of its own, which is exactly why the // resolver reads the tag colours as the fallback rather than `.?`. const theme = p.theme(); @@ -2584,7 +2600,7 @@ test "terminal Filter maps the default roles before it maps anything else" { p.settings.theme = 0; p.update(.{ .output = .{ .pane = 0, .bytes = "\x1b]11;#5f5f5f\x1b\\" } }); - var moved = FilteredColors.init(p, pane); + var moved = FilteredColors.init(p, &pane.terminal.?.vt); try testing.expect(!moved.default_bg.eql(moved.theme_bg)); try testing.expect(moved.default_bg.eql(moved.keyedRgb(.{ .r = 0x5f, .g = 0x5f, .b = 0x5f }))); } @@ -2609,7 +2625,7 @@ test "terminal Filter refuses a foreground that would collapse onto the page" { for (0..9) |t| { p.settings.theme = @intCast(t); - var fc = FilteredColors.init(p, pane); + var fc = FilteredColors.init(p, &pane.terminal.?.vt); const page = asPardesColor(fc.default_bg); const rescued = asPardesColor(fc.fallback_fg); _ = frame.reset(.retain_capacity); @@ -2661,7 +2677,7 @@ test "terminal Filter holds every projected foreground off the page" { for (0..9) |t| { p.settings.theme = @intCast(t); - var fc = FilteredColors.init(p, pane); + var fc = FilteredColors.init(p, &pane.terminal.?.vt); var refused: usize = 0; for (fc.target, 0..) |projected, key| { const ink = fc.legible(projected); diff --git a/test/snapshots/diffview.golden b/test/snapshots/diffview.golden index 9e171fd8..868e5e85 100644 --- a/test/snapshots/diffview.golden +++ b/test/snapshots/diffview.golden @@ -1,7 +1,7 @@ == snap diff-pane grid=100x31 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/diffview/cwd/change.diff Save Tty Collapse Del +| /tmp/pardes-snap/diffview/cwd/change.diff Save Tty Diff Collapse Del | 1 diff --git a/src/shape.zig b/src/shape.zig | 2 index 1111111..2222222 100644 | 3 --- a/src/shape.zig @@ -55,7 +55,7 @@ |29: 0-0 d,#608269, 1-99 d,#0d1410, |30: 0-0 d,#608269, 1-99 d,#0d1410, == snap look-added-line grid=100x31 cursor=55,22 -|16: /tmp/pardes-snap/diffview/cwd/src/shape.zig Save Tty Collapse Del TreeContext +|16: /tmp/pardes-snap/diffview/cwd/src/shape.zig Save Tty Collapse Del TreeContext Def Refs |17: 1 const std = @import("std"); |18: 2 |19: 3 pub const Shape = union(enum) { @@ -134,7 +134,7 @@ |30: 0-0 d,#152019, 1-99 d,#0d1410, == snap command-look grid=100x31 cursor=23,10 |3: 1 cat change.diff -|5: /tmp/pardes-snap/diffview/cwd/src/shape.zig Save Tty Collapse Del TreeContext +|5: /tmp/pardes-snap/diffview/cwd/src/shape.zig Save Tty Collapse Del TreeContext Def Refs |6: 1 const std = @import("std"); |7: 2 |8: 3 pub const Shape = union(enum) { diff --git a/test/snapshots/lsp-client-edit.golden b/test/snapshots/lsp-client-edit.golden index c36d15be..c9d93379 100644 --- a/test/snapshots/lsp-client-edit.golden +++ b/test/snapshots/lsp-client-edit.golden @@ -1,7 +1,7 @@ == snap formatted grid=100x25 cursor=7,4 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| * /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext +| * /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext Def Refs | 1 // formatted by mock formatted 1 range(s) | 2 mod lib; | 3 @@ -12,7 +12,7 @@ | 8 } | 9 == snap unformatted grid=100x25 cursor=7,3 -|2: /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext +|2: /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext Def Refs |3: 1 mod lib; |4: 2 |5: 3 fn main() { @@ -23,12 +23,12 @@ |10: 8 |11: == snap renamed grid=100x25 cursor=12,5 -|2: * /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext +|2: * /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext Def Refs |3: 1 mod lib; renamed 2 range(s) |6: 4 let x = sum(1, 2); |7: 5 let y = sum(3, 4); == snap unrenamed grid=100x25 cursor=12,5 -|2: /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext +|2: /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext Def Refs |3: 1 mod lib; |6: 4 let x = add(1, 2); |7: 5 let y = add(3, 4); diff --git a/test/snapshots/lsp-client.golden b/test/snapshots/lsp-client.golden index 23d86e11..13771394 100644 --- a/test/snapshots/lsp-client.golden +++ b/test/snapshots/lsp-client.golden @@ -1,7 +1,7 @@ == snap gd-jumped grid=100x25 cursor=16,12 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lsp-client/cwd/main.rs Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lsp-client/cwd/main.rs Save Tty Collapse Del TreeContext Def Refs | 1 mod lib; --:--:-- lsp rust-analyzer: ready | 2 | 3 fn main() { @@ -9,7 +9,7 @@ | 5 let y = add(3, 4); | 6 let _ = x + y; | 7 } -| /tmp/pardes-snap/lsp-client/cwd/lib.rs Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lsp-client/cwd/lib.rs Save Tty Collapse Del TreeContext Def Refs | 1 // mock fixture | 2 pub fn add(a: i32, b: i32) -> i32 { | 3 a + b diff --git a/test/snapshots/lsp-rename-files.golden b/test/snapshots/lsp-rename-files.golden index ea093dbf..4f71424e 100644 --- a/test/snapshots/lsp-rename-files.golden +++ b/test/snapshots/lsp-rename-files.golden @@ -1,12 +1,12 @@ == snap opened grid=100x25 cursor=7,8 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lsp-rename-files/cwd/lib.rs Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lsp-rename-files/cwd/lib.rs Save Tty Collapse Del TreeContext Def Refs | 1 // main.rs | 2 pub fn add(a: i32, b: i32) -> i32 { | 3 a + b | 4 } -| /tmp/pardes-snap/lsp-rename-files/cwd/main.rs Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lsp-rename-files/cwd/main.rs Save Tty Collapse Del TreeContext Def Refs | 1 mod lib; | 2 | 3 fn main() { diff --git a/test/snapshots/lsp-rename.golden b/test/snapshots/lsp-rename.golden index ba19d8f0..6b85822c 100644 --- a/test/snapshots/lsp-rename.golden +++ b/test/snapshots/lsp-rename.golden @@ -1,7 +1,7 @@ == snap renamed grid=110x25 cursor=17,10 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| * /tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse Del TreeContext +| * /tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse Del TreeContext Def Refs | 1 const std = @import("std"); renamed 2 range(s) | 2 | 3 fn renamed_helper(x: u32) u32 { @@ -18,11 +18,11 @@ | 14 } | 15 == snap undone grid=110x25 cursor=17,10 -|2: /tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse Del TreeContext +|2: /tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse Del TreeContext Def Refs |3: 1 const std = @import("std"); |5: 3 fn helper(x: u32) u32 { |10: 8 _ = helper(41); == snap redone grid=110x25 cursor=17,10 -|2: * /tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse Del TreeContext +|2: * /tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse Del TreeContext Def Refs |5: 3 fn renamed_helper(x: u32) u32 { |10: 8 _ = renamed_helper(41); diff --git a/test/snapshots/lsp.golden b/test/snapshots/lsp.golden index 048d1ed3..2225de00 100644 --- a/test/snapshots/lsp.golden +++ b/test/snapshots/lsp.golden @@ -1,7 +1,7 @@ == snap opened grid=120x41 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lsp/cwd/a.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lsp/cwd/a.zig Save Tty Collapse Del TreeContext Def Refs | 1 const std = @import("std"); | 2 | 3 fn helper(x: u32) u32 { @@ -34,4 +34,4 @@ == snap step grid=120x41 cursor=15,3 |3: 1 const std = @import("std"); == snap nothing grid=120x41 cursor=7,5 -|3: 1 const std = @import("std"); definition: not found +|3: 1 const std = @import("std"); Def: not found diff --git a/test/snapshots/lspcomplete.golden b/test/snapshots/lspcomplete.golden index a56101e8..85c26e30 100644 --- a/test/snapshots/lspcomplete.golden +++ b/test/snapshots/lspcomplete.golden @@ -1,7 +1,7 @@ == snap opened grid=120x41 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext Def Refs | 1 const Shade = enum { | 2 verdigris, | 3 cinnabar, @@ -16,7 +16,7 @@ | 12 // note. see below | 13 == snap indent grid=120x41 cursor=11,12 -|2: ^* /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext +|2: ^* /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext Def Refs |12: 10 } == snap commentindent grid=120x41 cursor=19,14 |3: 1 const Shade = enum { --:--:-- lsp zls ready — /tmp/pardes-snap/lspcomplete/cwd @@ -31,7 +31,7 @@ |18: 3 == snap refill grid=120x41 cursor=16,10 == snap step grid=120x41 cursor=16,10 -|2: * /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext +|2: * /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext Def Refs == snap txtindent grid=120x41 cursor=15,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol @@ -41,7 +41,7 @@ == snap nosemi grid=100x19 cursor=29,9 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -|^* /tmp/pardes-snap/lspcomplete/cwd/c.zig Save Tty Collapse Del TreeContext +|^* /tmp/pardes-snap/lspcomplete/cwd/c.zig Save Tty Collapse Del TreeContext Def Refs | 1 const Shade = enum { --:--:-- lsp zls ready — /tmp/pardes-snap/lspcomplete/cwd | 2 verdigris, | 3 cinnabar, @@ -57,7 +57,7 @@ == snap nobrace grid=100x19 cursor=16,10 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -|^* /tmp/pardes-snap/lspcomplete/cwd/d.zig Save Tty Collapse Del TreeContext +|^* /tmp/pardes-snap/lspcomplete/cwd/d.zig Save Tty Collapse Del TreeContext Def Refs | 1 const Shade = enum { --:--:-- lsp zls ready — /tmp/pardes-snap/lspcomplete/cwd | 2 verdigris, | 3 cinnabar, diff --git a/test/snapshots/lspcompletemoved.golden b/test/snapshots/lspcompletemoved.golden index c83e3038..403c6931 100644 --- a/test/snapshots/lspcompletemoved.golden +++ b/test/snapshots/lspcompletemoved.golden @@ -1,7 +1,7 @@ == snap typedthrough grid=120x21 cursor=16,14 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -|^* /tmp/pardes-snap/lspcompletemoved/cwd/a.zig Save Tty Collapse Del TreeContext +|^* /tmp/pardes-snap/lspcompletemoved/cwd/a.zig Save Tty Collapse Del TreeContext Def Refs | 1 const Shade = enum { --:--:-- lsp zls ready — /tmp/pardes-snap/lspcompletemoved/cwd | 2 verdigris, | 3 cinnabar, diff --git a/test/snapshots/lspdebug.golden b/test/snapshots/lspdebug.golden index 75fba98f..4beda019 100644 --- a/test/snapshots/lspdebug.golden +++ b/test/snapshots/lspdebug.golden @@ -1,7 +1,7 @@ == snap opened grid=120x45 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lspdebug/cwd/z.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lspdebug/cwd/z.zig Save Tty Collapse Del TreeContext Def Refs | 1 const std = @import("std"); | 2 | 3 fn helper() u32 { diff --git a/test/snapshots/lsprelpath.golden b/test/snapshots/lsprelpath.golden index b4022b1d..a3760316 100644 --- a/test/snapshots/lsprelpath.golden +++ b/test/snapshots/lsprelpath.golden @@ -1,7 +1,7 @@ == snap absrow grid=100x35 cursor=21,16 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lsprelpath/cwd/sub/parent.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lsprelpath/cwd/sub/parent.zig Save Tty Collapse Del TreeContext Def Refs | 1 const shade = @import("../shad --:--:-- lsp zls ready — /tmp/pardes-snap/lsprelpath/cwd/sub | 2 | 3 pub fn pick(s: shade.Shade) u8 { @@ -14,7 +14,7 @@ | 2 pub const Shade = enum { | 3 parent.zig:3:22-26 | 4 pub fn pick(s: shade.Shade) u8 { -| /tmp/pardes-snap/lsprelpath/cwd/shade.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lsprelpath/cwd/shade.zig Save Tty Collapse Del TreeContext Def Refs | 1 pub const Shade = enum { | 2 verdigris, | 3 cinnabar, @@ -61,7 +61,7 @@ == snap subrow grid=100x35 cursor=20,16 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lsprelpath/cwd/sub/subdir.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lsprelpath/cwd/sub/subdir.zig Save Tty Collapse Del TreeContext Def Refs | 1 const tint = @import("inner/ti --:--:-- lsp zls ready — /tmp/pardes-snap/lsprelpath/cwd/sub | 2 | 3 pub fn hue(t: tint.Tint) u8 { @@ -74,7 +74,7 @@ | 2 pub const Tint = enum { | 3 subdir.zig:3:20-23 | 4 pub fn hue(t: tint.Tint) u8 { -| /tmp/pardes-snap/lsprelpath/cwd/sub/inner/tint.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/lsprelpath/cwd/sub/inner/tint.zig Save Tty Collapse Del TreeContext Def Refs | 1 pub const Tint = enum { | 2 ochre, | 3 indigo, diff --git a/test/snapshots/ninep.golden b/test/snapshots/ninep.golden index c6b5f0af..e524fa30 100644 --- a/test/snapshots/ninep.golden +++ b/test/snapshots/ninep.golden @@ -1,7 +1,7 @@ == snap opened grid=90x15 cursor=7,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext Def Refs | 1 const greeting = "café λ 界 é"; | 2 | 3 pub fn choose(ok: bool) u32 { @@ -30,8 +30,8 @@ @0: 0-74 #b2c3b8,#1d2824,,tagline 75-89 d,#1d2824,,tagline |1: New Tty Find Grep Joincol Delcol @1: 0-1 #ffffff,#887455,,tagline 2-2 d,#314738,,tagline 3-34 #becfc4,#314738,,tagline 35-89 d,#314738,,tagline -|2: /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext -@2: 0-1 #000000,#add38a,,tagline 2-2 d,#314738,,tagline 3-29 #becfc4,#314738,,tagline 30-37 #dfbce5,#314738,,tagline 38-71 #becfc4,#314738,,tagline 72-89 d,#314738,,tagline +|2: /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext Def Refs +@2: 0-1 #000000,#add38a,,tagline 2-2 d,#314738,,tagline 3-29 #becfc4,#314738,,tagline 30-37 #dfbce5,#314738,,tagline 38-80 #becfc4,#314738,,tagline 81-89 d,#314738,,tagline |3: 1 const greeting = "café λ 界 é"; +3: 28="é" 30="λ" 32="界" 33="" 35="é" @3: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-23 #e5eee5,#0d1410,,body 24-36 #b8d88a,#0d1410,,body 37-37 #e5eee5,#0d1410,,body 38-89 d,#0d1410,,body @@ -73,7 +73,7 @@ |7: 5 return 7; @7: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-19 #e5eee5,#0d1410,,body 20-89 d,#0d1410,,body == snap edited-with-colors-off grid=90x15 cursor=7,4 -|2: * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext +|2: * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext Def Refs |3: 1 // café λ 界 |4: 2 const greeting = "café λ 界 é"; |5: 3 @@ -83,8 +83,8 @@ |9: 7 } |10: 8 == 9p edited-with-colors-off grid=90x15 cursor=7,4,block -|2: * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext -@2: 0-0 #000000,#add38a,,tagline 1-1 #000000,#f9cb70,b,tagline 2-2 d,#314738,,tagline 3-29 #becfc4,#314738,,tagline 30-37 #dfbce5,#314738,,tagline 38-71 #becfc4,#314738,,tagline 72-89 d,#314738,,tagline +|2: * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext Def Refs +@2: 0-0 #000000,#add38a,,tagline 1-1 #000000,#f9cb70,b,tagline 2-2 d,#314738,,tagline 3-29 #becfc4,#314738,,tagline 30-37 #dfbce5,#314738,,tagline 38-80 #becfc4,#314738,,tagline 81-89 d,#314738,,tagline |3: 1 // café λ 界 +3: 13="é" 15="λ" 17="界" 18="" @3: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-18 #e5eee5,#0d1410,,body 19-89 d,#0d1410,,body @@ -152,8 +152,8 @@ @0: 0-74 #b2c3b8,#1d2824,,tagline 75-104 d,#1d2824,,tagline |1: New Tty Find Grep Joincol Delcol @1: 0-1 #ffffff,#887455,,tagline 2-2 d,#314738,,tagline 3-34 #becfc4,#314738,,tagline 35-104 d,#314738,,tagline -|2: * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext -@2: 0-0 #000000,#add38a,,tagline 1-1 #000000,#f9cb70,b,tagline 2-2 d,#314738,,tagline 3-29 #becfc4,#314738,,tagline 30-37 #dfbce5,#314738,,tagline 38-71 #becfc4,#314738,,tagline 72-104 d,#314738,,tagline +|2: * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext Def Refs +@2: 0-0 #000000,#add38a,,tagline 1-1 #000000,#f9cb70,b,tagline 2-2 d,#314738,,tagline 3-29 #becfc4,#314738,,tagline 30-37 #dfbce5,#314738,,tagline 38-80 #becfc4,#314738,,tagline 81-104 d,#314738,,tagline |3: 1 // café λ 界 Colors +3: 13="é" 15="λ" 17="界" 18="" @3: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-18 #b9f480,#0d1410,,body 19-96 d,#0d1410,,body 97-97 d,#1d2824,,tagline 98-103 #b2c3b8,#1d2824,,tagline 104-104 d,#1d2824,,tagline @@ -193,7 +193,7 @@ == snap resized grid=105x20 cursor=7,4 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext +| * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext Def Refs | 1 // café λ 界 Colors | 2 const greeting = "café λ 界 é"; | 3 diff --git a/test/snapshots/pagercolor.golden b/test/snapshots/pagercolor.golden index 811d3d96..abd264d1 100644 --- a/test/snapshots/pagercolor.golden +++ b/test/snapshots/pagercolor.golden @@ -41,9 +41,8 @@ | | | -| /tmp/pardes-snap/pagercolor/cwd/+Pager Save Tty Collapse Del -| 1 red bold green rgb ul NAME us plain -| 2 +| /tmp/pardes-snap/pagercolor/cwd/+Pager Save Tty Filter Collapse Del +| red bold green rgb ul NAME us plain == style pager-colours grid=100x50 |0: 0-99 #b2c3b8,#1d2824, |1: 0-1 d,#887455, 2-2 d,#314738, 3-99 #becfc4,#314738, @@ -88,8 +87,8 @@ |40: 0-0 d,#608269, 1-99 d,#0d1410, |41: 0-0 d,#608269, 1-99 d,#0d1410, |42: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-41 #d3b0d9,#1d2824, 42-99 #b2c3b8,#1d2824, -|43: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f1a39b,#0d1410, 11-20 #b6ce94,#0d1410,b 21-21 #b6ce94,#0d1410, 22-25 #c86400,#0d1410, 26-27 #e5eee5,#0d1410,u 28-28 #e5eee5,#0d1410, 29-32 #e5eee5,#0d1410,b 33-33 #e5eee5,#0d1410, 34-35 #e5eee5,#0d1410,u 36-99 #e5eee5,#0d1410, -|44: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, +|43: 0-0 d,#608269, 1-1 d,#0d1410, 2-5 #f1a39b,#0d1410, 6-15 #b6ce94,#0d1410,b 16-16 #b6ce94,#0d1410, 17-20 #c5917e,#0d1410, 21-22 #e5eee5,#0d1410,u 23-23 #e5eee5,#0d1410, 24-27 #e5eee5,#0d1410,b 28-28 #e5eee5,#0d1410, 29-30 #e5eee5,#0d1410,u 31-99 #e5eee5,#0d1410, +|44: 0-0 d,#608269, 1-99 d,#0d1410, |45: 0-0 d,#608269, 1-99 d,#0d1410, |46: 0-0 d,#608269, 1-99 d,#0d1410, |47: 0-0 d,#608269, 1-99 d,#0d1410, @@ -100,21 +99,19 @@ |6: 3[m\n\033[1m+++ b/x\033[m\n\033[36m@@ -1 +1 @@\033[m\n\033[31m-old\033[m\n\033[32m+new\033[m\n' | |7: $(readlink /proc/$PPID/exe) - |8: $ -|43: 1 commit 0123abc -|44: 2 diff --git a/x b/x -|45: 3 --- a/x -|46: 4 +++ b/x -|47: 5 @@ -1 +1 @@ -|48: 6 -old -|49: 7 +new +|9: /tmp/pardes-snap/pagercolor/cwd/+Diff Save Tty Diff Collapse Del LocationsConfig +|10: commit 0123abc +|11: x:1 +|12: -old +|13: +new +|49: /tmp/pardes-snap/pagercolor/cwd/+Pager Save Tty Filter Diff Collapse Del == style pager-diff-colours grid=100x50 |6: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, |7: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, |8: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|43: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e9c680,#0d1410, -|44: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-24 #b9f480,#0d1410,b 25-99 #b9f480,#0d1410, -|45: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-13 #b9f480,#0d1410,b 14-99 #b9f480,#0d1410, -|46: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-13 #b9f480,#0d1410,b 14-99 #b9f480,#0d1410, -|47: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #b6c59e,#0d1410, -|48: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-7 #f1a39b,#302b25,b 8-99 #f8c082,#302b25, -|49: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-7 #b6ce94,#263025,b 8-99 #b8d88a,#263025, +|9: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-40 #d3b0d9,#1d2824, 41-99 #b2c3b8,#1d2824, +|10: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, +|11: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #59675c,#0d1410, +|12: 0-0 d,#608269, 1-1 d,#0d1410, 2-2 #f1a39b,#1a1d18,b 3-99 #f8c082,#1a1d18, +|13: 0-0 d,#608269, 1-1 d,#0d1410, 2-2 #b6ce94,#171f18,b 3-99 #b8d88a,#171f18, +|49: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-41 #d3b0d9,#1d2824, 42-99 #b2c3b8,#1d2824, diff --git a/test/snapshots/selregex.golden b/test/snapshots/selregex.golden index e3f3b2d7..480ad8a2 100644 --- a/test/snapshots/selregex.golden +++ b/test/snapshots/selregex.golden @@ -1,7 +1,7 @@ == snap prompt-armed grid=160x25 cursor=159,3 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse Del TreeContext Def Refs | 1 const one = 1; Select / | 2 const two = 2; | 3 const three = 3; @@ -51,12 +51,12 @@ |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-159 #e5eee5,#0d1410, == snap commented grid=160x25 cursor=14,3 -|2: * /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse Del TreeContext +|2: * /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse Del TreeContext Def Refs |3: 1 // const one = 1; |4: 2 // const two = 2; |5: 3 // const three = 3; == snap uncommented grid=160x25 cursor=11,3 -|2: /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse Del TreeContext +|2: /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse Del TreeContext Def Refs |3: 1 const one = 1; |4: 2 const two = 2; |5: 3 const three = 3; diff --git a/test/snapshots/syntax.golden b/test/snapshots/syntax.golden index 2f7a6b74..43bfe485 100644 --- a/test/snapshots/syntax.golden +++ b/test/snapshots/syntax.golden @@ -1,11 +1,12 @@ -== snap zig-open grid=150x31 cursor=7,7 +== snap zig-open grid=150x31 cursor=7,8 |Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/syntax/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/syntax/cwd Tty+bash Save Mode Filter Collapse Del | ls ls | demo.zig demo.zig | -| /tmp/pardes-snap/syntax/cwd/demo.zig Save Tty Collapse Del TreeContext +| /tmp/pardes-snap/syntax/cwd/demo.zig Save Tty Collapse Del TreeContext D +| ef Refs | 1 const std = @import("std"); // greet | 2 pub fn main() void { | 3 var x: u32 = 42; @@ -15,7 +16,6 @@ | | | -| | /tmp/pardes-snap/syntax/cwd Tty+bash Save Mode Filter Collapse Del | ls | demo.zig @@ -27,12 +27,12 @@ |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, |6: 0-1 d,#add38a, 2-2 d,#314738, 3-30 #becfc4,#314738, 31-39 #dfbce5,#314738, 40-74 #becfc4,#314738, 75-75 #becfc4,#608269, 76-149 #becfc4,#0d1410, -|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-18 #e5eee5,#0d1410, 19-25 #c9a7ed,#0d1410, 26-26 #e5eee5,#0d1410, 27-31 #b8d88a,#0d1410, 32-34 #e5eee5,#0d1410, 35-74 #b9f480,#0d1410, 75-75 #b9f480,#608269, 76-149 #b9f480,#0d1410, -|8: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, -|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-23 #e5eee5,#0d1410, 24-25 #f8c082,#0d1410, 26-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, -|10: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, -|11: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, -|12: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, +|7: 0-2 d,#314738, 3-74 #becfc4,#314738, 75-75 #becfc4,#608269, 76-149 #becfc4,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-18 #e5eee5,#0d1410, 19-25 #c9a7ed,#0d1410, 26-26 #e5eee5,#0d1410, 27-31 #b8d88a,#0d1410, 32-34 #e5eee5,#0d1410, 35-74 #b9f480,#0d1410, 75-75 #b9f480,#608269, 76-149 #b9f480,#0d1410, +|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-23 #e5eee5,#0d1410, 24-25 #f8c082,#0d1410, 26-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, +|11: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, +|12: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |13: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, |14: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, |15: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, @@ -52,10 +52,10 @@ |29: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, |30: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, == style colors-off grid=150x31 -|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-66 #e5eee5,#0d1410, 67-67 #e5eee5,#1d2824, 68-74 #b2c3b8,#1d2824, 75-75 #b2c3b8,#608269, 76-149 #b2c3b8,#0d1410, -|8: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, -|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-66 #e5eee5,#0d1410, 67-67 #e5eee5,#1d2824, 68-74 #b2c3b8,#1d2824, 75-75 #b2c3b8,#608269, 76-149 #b2c3b8,#0d1410, +|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, == style colors-on grid=150x31 -|7: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-18 #e5eee5,#0d1410, 19-25 #c9a7ed,#0d1410, 26-26 #e5eee5,#0d1410, 27-31 #b8d88a,#0d1410, 32-34 #e5eee5,#0d1410, 35-66 #b9f480,#0d1410, 67-67 #b9f480,#1d2824, 68-74 #b2c3b8,#1d2824, 75-75 #b2c3b8,#608269, 76-149 #b2c3b8,#0d1410, -|8: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, -|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-23 #e5eee5,#0d1410, 24-25 #f8c082,#0d1410, 26-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, +|8: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-18 #e5eee5,#0d1410, 19-25 #c9a7ed,#0d1410, 26-26 #e5eee5,#0d1410, 27-31 #b8d88a,#0d1410, 32-34 #e5eee5,#0d1410, 35-66 #b9f480,#0d1410, 67-67 #b9f480,#1d2824, 68-74 #b2c3b8,#1d2824, 75-75 #b2c3b8,#608269, 76-149 #b2c3b8,#0d1410, +|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-23 #e5eee5,#0d1410, 24-25 #f8c082,#0d1410, 26-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, -- cgit v1.3 From 1ecb9b720840ea8e4753823fa8cddcf5d6a3a4d2 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 8 Oct 2026 12:03:46 -0300 Subject: Add a readable static Callstack pane and align tagline text --- docs/typ/builtins-gui.json | 6 + docs/typ/builtins-tty.json | 6 + docs/typ/guide.typ | 33 +++- docs/typ/reference.typ | 10 ++ src/CHANGELOG.md | 15 ++ src/File.zig | 82 ++++++--- src/Output.zig | 79 +++++++-- src/body_layer.zig | 42 ++--- src/builtins.zig | 13 +- src/colors.zig | 10 +- src/config.zig | 46 ++++- src/draw.zig | 18 +- src/dump.zig | 4 +- src/edit.zig | 4 +- src/exec.zig | 16 +- src/host_io.zig | 12 ++ src/layout.zig | 22 +++ src/locations.zig | 179 +++++++++++++++++++- src/look.zig | 17 +- src/lsp/lsp.zig | 10 +- src/lsp/lsp_client.zig | 263 +++++++++++++++++++++++++++-- src/modal.zig | 4 +- src/mouse.zig | 26 ++- src/ninep/ctl.zig | 22 ++- src/normal.zig | 3 +- src/panes.zig | 9 +- src/pardes.zig | 81 +++++++-- src/syntax.zig | 17 +- src/tagline.zig | 19 ++- test/column_drag.zig | 14 +- test/hxcases/waivers.jsonl | 1 + test/panes.zig | 151 ++++++++++++++++- test/snapshots/argv.golden | 26 +-- test/snapshots/badutf.golden | 14 +- test/snapshots/boot.golden | 12 +- test/snapshots/builtins.golden | 10 +- test/snapshots/builtins.snap | 2 + test/snapshots/callstack-inline.golden | 65 +++++++ test/snapshots/callstack-inline.snap | 30 ++++ test/snapshots/callstack.golden | 27 +++ test/snapshots/callstack.snap | 19 +++ test/snapshots/chordcut.golden | 40 ++--- test/snapshots/cmdexit.golden | 10 +- test/snapshots/cmdword.golden | 18 +- test/snapshots/colgrip.golden | 42 ++--- test/snapshots/collapse.golden | 20 +-- test/snapshots/cornerdrag-left.golden | 62 +++---- test/snapshots/cornerdrag.golden | 90 +++++----- test/snapshots/cursorline.golden | 20 +-- test/snapshots/delask.golden | 14 +- test/snapshots/diffview.golden | 32 ++-- test/snapshots/dirpane.golden | 10 +- test/snapshots/doccol.golden | 20 +-- test/snapshots/edit.golden | 24 +-- test/snapshots/emptycol.golden | 20 +-- test/snapshots/exec-bigdrag.golden | 8 +- test/snapshots/exec.golden | 8 +- test/snapshots/fileedit.golden | 10 +- test/snapshots/filewatch.golden | 10 +- test/snapshots/find.golden | 24 +-- test/snapshots/fsearch.golden | 26 +-- test/snapshots/ghostty-mid.golden | 12 +- test/snapshots/grep.golden | 16 +- test/snapshots/headersweep-restored.golden | 40 ++--- test/snapshots/headersweep.golden | 46 ++--- test/snapshots/hscroll.golden | 16 +- test/snapshots/images.golden | 42 ++--- test/snapshots/jumps.golden | 20 +-- test/snapshots/layout-close.golden | 62 +++---- test/snapshots/layout-open.golden | 32 ++-- test/snapshots/leader.golden | 44 +++-- test/snapshots/load.golden | 24 +-- test/snapshots/logquiet.golden | 6 +- test/snapshots/look-center.golden | 10 +- test/snapshots/look-dir.golden | 16 +- test/snapshots/look-file-1col.golden | 8 +- test/snapshots/look-file.golden | 20 +-- test/snapshots/lookloaded.golden | 20 +-- test/snapshots/lookpanes.golden | 52 +++--- test/snapshots/lookrange.golden | 20 +-- test/snapshots/lsp-client-edit.golden | 12 +- test/snapshots/lsp-client.golden | 10 +- test/snapshots/lsp-rename-files.golden | 10 +- test/snapshots/lsp-rename.golden | 10 +- test/snapshots/lsp.golden | 10 +- test/snapshots/lspcomplete.golden | 34 ++-- test/snapshots/lspcompletemoved.golden | 6 +- test/snapshots/lspdebug.golden | 6 +- test/snapshots/lsprelpath.golden | 40 ++--- test/snapshots/markup.golden | 24 +-- test/snapshots/mini.golden | 56 +++--- test/snapshots/modal.golden | 24 +-- test/snapshots/msg.golden | 14 +- test/snapshots/multicursor.golden | 24 +-- test/snapshots/nested-optout.golden | 32 ++-- test/snapshots/nested.golden | 28 +-- test/snapshots/ninep.golden | 56 +++--- test/snapshots/pagercolor.golden | 42 +++-- test/snapshots/pipe.golden | 10 +- test/snapshots/psearch.golden | 26 +-- test/snapshots/reflow.golden | 8 +- test/snapshots/respawn.golden | 8 +- test/snapshots/restore.golden | 8 +- test/snapshots/rsearch.golden | 12 +- test/snapshots/savepane.golden | 10 +- test/snapshots/scroll.golden | 24 +-- test/snapshots/scrolloff.golden | 8 +- test/snapshots/selarg.golden | 12 +- test/snapshots/selregex.golden | 16 +- test/snapshots/shellset.golden | 12 +- test/snapshots/shrinktag.golden | 24 +-- test/snapshots/splitparent.golden | 42 ++--- test/snapshots/stepgrain.golden | 20 +-- test/snapshots/syntax.golden | 24 +-- test/snapshots/tag.golden | 22 +-- test/snapshots/tagalign.golden | 60 ++++--- test/snapshots/tagalign2col.golden | 39 +++-- test/snapshots/tagbottom.golden | 26 +-- test/snapshots/tagbottomimage.golden | 22 +-- test/snapshots/tagbottomshort.golden | 34 ++-- test/snapshots/tagcmd.golden | 12 +- test/snapshots/tagnav.golden | 44 ++--- test/snapshots/tagpath.golden | 30 ++-- test/snapshots/theme.golden | 242 +++++++++++++------------- test/snapshots/themesel.golden | 146 ++++++++-------- test/snapshots/tinywin.golden | 60 +++---- test/snapshots/topbarexec.golden | 28 +-- test/snapshots/tty.golden | 18 +- test/snapshots/ttyclick.golden | 16 +- test/snapshots/ttyedit.golden | 16 +- test/snapshots/ttyfollow.golden | 16 +- test/snapshots/ttyhelp.golden | 10 +- test/snapshots/ttylook.golden | 32 ++-- test/snapshots/ttyonly.golden | 16 +- test/snapshots/ttypaste.golden | 12 +- test/snapshots/ttyprompt.golden | 16 +- test/snapshots/ttytaken.golden | 14 +- test/snapshots/tutor.golden | 10 +- test/snapshots/wheeldrift.golden | 6 +- test/snapshots/winch.golden | 24 +-- test/snapshots/windownav.golden | 12 +- test/snapshots/windowops.golden | 84 ++++----- test/snapshots/wrap.golden | 14 +- test/snapshots/yankpaste.golden | 6 +- 144 files changed, 2646 insertions(+), 1596 deletions(-) create mode 100644 test/snapshots/callstack-inline.golden create mode 100644 test/snapshots/callstack-inline.snap create mode 100644 test/snapshots/callstack.golden create mode 100644 test/snapshots/callstack.snap (limited to 'src/File.zig') diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index 83a410dc..f602ee92 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -6,6 +6,10 @@ {"name": "BootShell", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "keep, replace", "doc": "A document dropped where a lone untouched shell stands: keep the shell, or replace it."}, {"name": "Callees", "leader": "SPC l C", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the functions the function under the cursor calls."}, {"name": "Callers", "leader": "SPC l c", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the callers of the function under the cursor."}, + {"name": "Callstack", "leader": "SPC l b", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Show outermost callers first, with signatures and call sites (gc)."}, + {"name": "CallstackCorners", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "rounded, square", "doc": "Callstack tree corners: rounded (the default) or square; bare, it switches styles. Applies to the next Callstack query."}, + {"name": "CallstackDepth", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Caller levels collected by Callstack, 1 through 64; default 8. Bare, it says the current limit."}, + {"name": "CallstackLayout", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "inline, stacked", "doc": "Callstack snippets below their locations (stacked, the default) or beside them (inline); bare, it switches layouts. Applies to the next Callstack query."}, {"name": "Changelog", "leader": "SPC h c", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "This build's version and what changed to reach it, printed into an output buffer the same way Config prints the live settings."}, {"name": "ChipShadow", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "In a terminal, a notice chip casts a cell's shadow right and down, on or off."}, {"name": "ClipPaste", "leader": "SPC p", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Paste the system clipboard after the selection."}, @@ -65,6 +69,8 @@ {"name": "Ligatures", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A font's programming ligatures draw across their cells, on or off."}, {"name": "LocationsConfig", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Set how location rows are drawn, or show how they are when bare."}, {"name": "Look", "leader": null, "also": ["enter", "right-click"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Look at its argument: open the file or address it names, else find the word, as a right click does."}, + {"name": "LookNext", "leader": "SPC j n", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Select the next Look location across panes; Enter opens it."}, + {"name": "LookPrev", "leader": "SPC j p", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Select the previous Look location across panes; Enter opens it."}, {"name": "LookWord", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "search, list", "doc": "A plain word looked at: search selects its next place in the pane, list lists every place in a +Search."}, {"name": "Lspinfo", "leader": "SPC l i", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Show which language servers serve this file and their state."}, {"name": "Lspwhy", "leader": "SPC l w", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Explain how the last language server request was answered, step by step."}, diff --git a/docs/typ/builtins-tty.json b/docs/typ/builtins-tty.json index 35e12875..e02f4201 100644 --- a/docs/typ/builtins-tty.json +++ b/docs/typ/builtins-tty.json @@ -5,6 +5,10 @@ {"name": "BootShell", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "keep, replace", "doc": "A document dropped where a lone untouched shell stands: keep the shell, or replace it."}, {"name": "Callees", "leader": "SPC l C", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the functions the function under the cursor calls."}, {"name": "Callers", "leader": "SPC l c", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the callers of the function under the cursor."}, + {"name": "Callstack", "leader": "SPC l b", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Show outermost callers first, with signatures and call sites (gc)."}, + {"name": "CallstackCorners", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "rounded, square", "doc": "Callstack tree corners: rounded (the default) or square; bare, it switches styles. Applies to the next Callstack query."}, + {"name": "CallstackDepth", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Caller levels collected by Callstack, 1 through 64; default 8. Bare, it says the current limit."}, + {"name": "CallstackLayout", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "inline, stacked", "doc": "Callstack snippets below their locations (stacked, the default) or beside them (inline); bare, it switches layouts. Applies to the next Callstack query."}, {"name": "Changelog", "leader": "SPC h c", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "This build's version and what changed to reach it, printed into an output buffer the same way Config prints the live settings."}, {"name": "ChipShadow", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "In a terminal, a notice chip casts a cell's shadow right and down, on or off."}, {"name": "ClipPaste", "leader": "SPC p", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Paste the system clipboard after the selection."}, @@ -55,6 +59,8 @@ {"name": "Left", "leader": "SPC w h", "also": ["C-w h", "C-w left"], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane, or column tag, to the left."}, {"name": "LocationsConfig", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Set how location rows are drawn, or show how they are when bare."}, {"name": "Look", "leader": null, "also": ["enter", "right-click"], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Look at its argument: open the file or address it names, else find the word, as a right click does."}, + {"name": "LookNext", "leader": "SPC j n", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Select the next Look location across panes; Enter opens it."}, + {"name": "LookPrev", "leader": "SPC j p", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Select the previous Look location across panes; Enter opens it."}, {"name": "LookWord", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "search, list", "doc": "A plain word looked at: search selects its next place in the pane, list lists every place in a +Search."}, {"name": "Lspinfo", "leader": "SPC l i", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Show which language servers serve this file and their state."}, {"name": "Lspwhy", "leader": "SPC l w", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Explain how the last language server request was answered, step by step."}, diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index 55f8a4f0..7058592f 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -218,10 +218,39 @@ around it, a `+`/`-` before each line, the words a changed line changed tinted and a line added or removed whole faintly. A mailed patch keeps its message and diffstat above. The files are found from the diff's directory or one above it. #word("Diff") on a `+Diff` shows the diff itself as -text (a paged one's `+Pager` is folded under it), and on the text stacks +text (a paged one's `+Pager` is closed once stacked), and on the text stacks it again; #word("DiffLook") `text` in the startup file opens the text first. += Call hierarchy + +Put the cursor on a function and run #word("Callstack") (#key("g c") or #key("SPC l b")). +`+Callstack` starts at the outermost callers and follows calls down toward +the selected function, with shared callers grouped and vertical guides +joining the levels with rounded corners. Each caller has a clickable location and its function +signature, extracted by the same tree-sitter context mechanism as other +location results. Signatures and call-site snippets use source syntax colors; +only calls to the selected function receive background emphasis. Guides +continue alongside every line of a multiline signature and through screen +wrapping. Cross-directory Look paths are shortened when possible. +#btn("B3") or #key("Enter") on a location opens and reveals that source +pane. #word("LookNext") / #word("LookPrev") (#keys("SPC j n", "SPC j p")) +select locations without opening them. The view follows the language +server's static call hierarchy; recursive paths are marked `↻`, and a +large hierarchy invites continuing from another function. +#word("CallstackDepth") reports the current caller depth; +`CallstackDepth 16` changes it for subsequent queries. The default is 8 +levels, and the accepted range is 1–64. The view also caps collection at +64 callers. + +`CallstackLayout stacked` (the default) puts each signature and call snippet below its +location, aligned with the location text; `CallstackLayout inline` puts it +beside the location again. A bare #word("CallstackLayout") switches modes. +`CallstackCorners rounded` (the default) uses rounded tree guides; +`CallstackCorners square` restores sharp corners. Bare #word("CallstackCorners") +switches styles. Layout and corner changes apply to the next query. These settings are retained +by #word("Dump") / #word("Restore"). + = `pardes FILE` and `--wait` In a pane's shell: @@ -242,7 +271,7 @@ refusals and `--nested` are in the reference. [#key("x"), #key("v"), #key(";")], [select the line; extend; collapse to the cursor], [#key("s")], [a cursor per regex match; every edit acts at each], [#key("/"), #keys("n", "N")], [substring search; repeat the search in the current text, wrapping at the ends], - [#keys("Space j n", "Space j p")], [#word("LookNext") / #word("LookPrev"): select locations across panes; #key("Enter") opens one], + [#keys("SPC j n", "SPC j p")], [#word("LookNext") / #word("LookPrev"): select locations across panes; #key("Enter") opens one], [#key("g l")], [line end], [`12G`], [line 12; a bare #key("G") does nothing], [#key("SPC ?")], [#word("Help"): every builtin, with its leader path and keys; `SPC w ?` only the paths under `SPC w`; #word("Tutor") (#key("SPC h t")) practises them], diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index 909c1e1a..05176951 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -262,6 +262,16 @@ A line written to #file("exec") is #word("Exec"): the server answers in this file alone while another open file of its language still holds the old name, a row per such file (zls renaming at a declaration; from a use it reaches every file); + #word("Callstack") (#key("g c") or #key("SPC l b")) opens and focuses `+Callstack`, + with static caller ancestry, tree-sitter signatures and Look locations + for callers and call sites. #word("CallstackDepth") reports or sets the + runtime depth (1–64, default 8) for subsequent queries. + `CallstackLayout stacked` (the default) aligns snippets below their locations; + `CallstackLayout inline` places the snippets beside them. + `CallstackCorners rounded` (the default) or `CallstackCorners square` + selects the tree corner style for the next query; bare, it switches styles. + #word("Callers") and #word("Callees") keep their short + lists and single-result jumps. #word("Diagnostics") and #word("Symbols") list the file's in `+Search`; #word("Lspinfo") fills `+Lsp`, the pane its write answers, with which server serves the file and its state (`not started yet` until its first diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index e15faca7..4fe0760c 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,21 @@ ## Unreleased +- Callstack (gc or Space l b) opens a readable static call hierarchy with + outermost callers first, tree-sitter signatures, depth guides and clickable call sites. + `gc` replaces the old move-to-viewport-center binding. + CallstackDepth sets the caller depth at runtime (1–64, default 8). + CallstackLayout stacked is the default, aligning snippets below their + locations with rounded tree corners; inline + keeps them beside the locations. CallstackCorners square restores sharp + tree corners; rounded remains the default. + Signatures use syntax colors; only calls to the queried function get + background emphasis, and tree guides continue through multiline signatures + and wrapped rows. Cross-directory call locations use shorter relative paths. +- Workspace, column and pane tags share a tighter text inset. +- A diff paged into a session (`git show | pardes -`) opens its `+Diff` + alone; the `+Pager` no longer stays folded under it. + - n/N follow Helix search registers, counts, wrapping and select mode. `*` sets a search from the selection; `Alt-*` omits word boundaries. The location ring remains as LookNext/LookPrev (Space j n/p). diff --git a/src/File.zig b/src/File.zig index 31392ebd..c42e39ec 100644 --- a/src/File.zig +++ b/src/File.zig @@ -253,6 +253,8 @@ fn dumpLocationRows(arena: std.mem.Allocator, rows: []const locations.Row) ![]co for (rows, saved) |row, *out| out.* = .{ .kind = @enumFromInt(@intFromEnum(row.kind)), .declaration = row.declaration, + .mark_occurrence = row.mark_occurrence, + .source_column = row.source_column, .path = row.path, .line = row.at.line, .col = row.at.col, @@ -271,6 +273,10 @@ fn sameSavedLocation(a: dump.LocationRow, b: dump.LocationRow) bool { } fn restoreLocationRows(gpa: std.mem.Allocator, content: []const u8, saved: []const dump.LocationRow) ![]locations.Row { + return restoreOutputLocationRows(gpa, content, saved, false); +} + +fn restoreOutputLocationRows(gpa: std.mem.Allocator, content: []const u8, saved: []const dump.LocationRow, callstack: bool) ![]locations.Row { if (saved.len == 0) return &.{}; if (saved.len > std.mem.count(u8, content, "\n") + 1) return error.InvalidLocationRows; const rows = try gpa.alloc(locations.Row, saved.len); @@ -286,29 +292,44 @@ fn restoreLocationRows(gpa: std.mem.Allocator, content: []const u8, saved: []con var previous_line: []const u8 = ""; for (saved, rows, 0..) |row, *out, index| { const line = lines.next() orelse return error.InvalidLocationRows; - if (row.path.len == 0 or row.path.len >= 4096 or + if ((!callstack and row.path.len == 0) or row.path.len >= 4096 or row.location_end > row.code_start or row.code_start > line.len or (row.kind == .match and row.location_end == 0) or (row.declaration and row.kind != .context) or row.line > std.math.maxInt(i32) or row.col > std.math.maxInt(i32) or row.end_line > std.math.maxInt(i32) or row.end_col > std.math.maxInt(i32)) return error.InvalidLocationRows; - const inline_row = row.code_start > row.location_end and row.code_start > 0 and line[row.code_start - 1] == '\t'; - const address_row = !inline_row and row.location_end > 0 and row.code_start == line.len; - const source_row = row.location_end == 0 and row.code_start == 0; - if (!inline_row and !address_row and !source_row) return error.InvalidLocationRows; - if (row.kind == .preview) { - if (!source_row or index == 0) return error.InvalidLocationRows; - const previous = saved[index - 1]; - if (previous.kind != .match or previous.location_end == 0 or previous.code_start != previous_line.len or previous_line[previous_line.len - 1] == '\t' or - !sameSavedLocation(previous, row)) return error.InvalidLocationRows; - } - if (address_row) { - if (index + 1 >= saved.len) return error.InvalidLocationRows; - const following = saved[index + 1]; - const expected: @TypeOf(row.kind) = if (row.kind == .match) .preview else .context; - if (following.kind != expected or following.code_start != 0 or following.location_end != 0 or - following.declaration != row.declaration or !sameSavedLocation(row, following)) return error.InvalidLocationRows; + if (callstack) { + if (row.location_end > 0) { + const prefix = locations.treePrefix(line); + const parsed = locations.parseRaw(line[prefix.end..]); + if (row.kind != .match or parsed.at.line == 0 or + !std.mem.eql(u8, parsed.path, row.path) or + parsed.at.line != row.line or parsed.at.col != row.col or + parsed.at.end_line != row.end_line or parsed.at.end_col != row.end_col or + prefix.end + parsed.end != row.location_end or + prefix.end + parsed.code_start != row.code_start) return error.InvalidLocationRows; + } else if (row.kind == .preview) { + if (index == 0 or saved[index - 1].kind != .match or !sameSavedLocation(saved[index - 1], row)) return error.InvalidLocationRows; + } else if (row.kind != .context or (row.path.len == 0 and (row.line != 0 or row.code_start != line.len))) return error.InvalidLocationRows; + } else { + const inline_row = row.code_start > row.location_end and row.code_start > 0 and line[row.code_start - 1] == '\t'; + const address_row = !inline_row and row.location_end > 0 and row.code_start == line.len; + const source_row = row.location_end == 0 and row.code_start == 0; + if (!inline_row and !address_row and !source_row) return error.InvalidLocationRows; + if (row.kind == .preview) { + if (!source_row or index == 0) return error.InvalidLocationRows; + const previous = saved[index - 1]; + if (previous.kind != .match or previous.location_end == 0 or previous.code_start != previous_line.len or previous_line[previous_line.len - 1] == '\t' or + !sameSavedLocation(previous, row)) return error.InvalidLocationRows; + } + if (address_row) { + if (index + 1 >= saved.len) return error.InvalidLocationRows; + const following = saved[index + 1]; + const expected: @TypeOf(row.kind) = if (row.kind == .match) .preview else .context; + if (following.kind != expected or following.code_start != 0 or following.location_end != 0 or + following.declaration != row.declaration or !sameSavedLocation(row, following)) return error.InvalidLocationRows; + } } const code_len = line.len - row.code_start; if (row.colors_b64.len > std.base64.standard.Encoder.calcSize(code_len)) return error.InvalidLocationRows; @@ -320,6 +341,8 @@ fn restoreLocationRows(gpa: std.mem.Allocator, content: []const u8, saved: []con out.* = .{ .kind = @enumFromInt(@intFromEnum(row.kind)), .declaration = row.declaration, + .mark_occurrence = row.mark_occurrence, + .source_column = row.source_column, .path = path, .at = .{ .line = row.line, .col = row.col, .end_line = row.end_line, .end_col = row.end_col }, .location_end = row.location_end, @@ -992,7 +1015,8 @@ pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { } else null; if (saved.location_rows.len != 0 and output == null) return error.InvalidLocationRows; - const location_rows = try restoreLocationRows(p.gpa, content, saved.location_rows); + const is_callstack = if (output) |state| std.meta.eql(state.from, Output.Origin{ .query = .callstack }) else false; + const location_rows = try restoreOutputLocationRows(p.gpa, content, saved.location_rows, is_callstack); errdefer locations.freeRows(p.gpa, location_rows); var mini: ?Mini.State = null; @@ -1707,9 +1731,16 @@ fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) const row = if (context) @as(usize, @intCast(pane.wrap_line[i])) else body_line; const at = if (context) 0 else body_at; const text = if (row < total) sourceLine(pane, @intCast(row)) else ""; + var guide_buffer: [1024]u8 = undefined; + const guide = if (at > 0 and width > 1 and f.output != null and + std.meta.eql(f.output.?.from, Output.Origin{ .query = .callstack })) + locations.treeContinuation(text, &guide_buffer, width - 1) + else + ""; + const pad = displayWidth(guide); // Headers use one screen row per source row, preserving signatures // without allowing a long ancestor to consume the whole viewport. - const end = if (width == 0 or context) text.len else fitEnd(text, at, width); + const end = if (width == 0 or context) text.len else fitEnd(text, at, width - pad); const cut = if (pane.hscroll > 0 and width == 0) modal.graphemeStart(text, @min(@as(usize, @intCast(pane.hscroll)), text.len)) else @@ -1717,6 +1748,7 @@ fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) if ((width > 0 or pane.context_rows > 0) and record_wrap) { pane.wrap_line[i] = @intCast(row); pane.wrap_col[i] = @intCast(cut); + pane.wrap_pad[i] = @intCast(pad); pane.wrap_n = @intCast(i + 1); } if (row < total) { @@ -1735,6 +1767,8 @@ fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) } if (dst) |out| @memcpy(out[written..][0..prefix.len], prefix); written += prefix.len; + if (dst) |out| @memcpy(out[written..][0..guide.len], guide); + written += guide.len; const shown = text[cut..end]; if (dst) |out| @memcpy(out[written..][0..shown.len], shown); written += shown.len; @@ -1935,7 +1969,11 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. } }.before); var c: usize = 0; - var screen_c: usize = 0; + const pad: usize = if (vr < pane.wrap_n) pane.wrap_pad[vr] else 0; + for (0..@min(pad, tw -| prefix_width)) |col| { + s.at(tx + @as(u16, @intCast(prefix_width + col)), body_y + vr).style.fg = .{ .rgb = p.bodyChrome().diagnostic_info }; + } + var screen_c: usize = pad; while (hs + c < limit and prefix_width + screen_c < tw) { const grapheme_end = @min(limit, modal.nextGrapheme(line, hs + c)); const cells = graphemeDisplayWidth(line[hs + c .. grapheme_end]); @@ -2218,8 +2256,8 @@ pub fn paintWordSelection( if (next.line == row) hi = @min(hi, next.at); const lo = @max(word_lo, here.at); if (hi <= lo) continue; - const c0 = @as(i32, prefix_width) + displayOffset(pane, row, here.at, lo); - const c1 = @as(i32, prefix_width) + displayEndOffset(pane, row, here.at, hi - 1); + const c0 = @as(i32, prefix_width) + here.pad + displayOffset(pane, row, here.at, lo); + const c1 = @as(i32, prefix_width) + here.pad + displayEndOffset(pane, row, here.at, hi - 1); var col = @max(@as(i32, prefix_width), c0); while (col <= c1 and col < @as(i32, tw)) : (col += 1) { const cell = s.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(vr))); diff --git a/src/Output.zig b/src/Output.zig index 9e194615..9ed33ebe 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -53,13 +53,14 @@ const RowDecoration = struct { location_end: usize = 0, prefix_end: usize = 0, declaration: bool = false, + guide_end: usize = 0, mark_start: usize = 0, mark_end: usize = 0, severity: enum { none, err, warning, info, hint } = .none, /// Nothing in the row is decorated: most rows of most files. pub fn plain(row: RowDecoration) bool { - return !row.declaration and row.location_end == 0 and row.prefix_end == 0 and row.mark_end <= row.mark_start; + return row.guide_end == 0 and !row.declaration and row.location_end == 0 and row.prefix_end == 0 and row.mark_end <= row.mark_start; } /// `chrome` is the theme's own (Pardes.bodyChrome): body paper changes @@ -68,6 +69,7 @@ const RowDecoration = struct { /// working it out takes the contrast searches' pow calls. pub fn styleAt(row: RowDecoration, chrome: *const pardes.ChromeTheme, byte: usize) ?pardes.CellStyle { if (row.plain()) return null; + if (byte < row.guide_end) return .{ .fg = .{ .rgb = chrome.diagnostic_info } }; if (row.declaration or byte < @max(row.location_end, row.prefix_end)) return .{ .fg = .{ .rgb = chrome.lineno } }; if (byte < row.mark_start or byte >= row.mark_end) return null; @@ -91,32 +93,38 @@ fn rowDecoration(output: ?State, line: []const u8) RowDecoration { pub fn decorateRow(output: ?State, line: []const u8, metadata: ?locations.Row) RowDecoration { const origin = (output orelse return .{}).from; + const callstack = std.meta.eql(origin, Origin{ .query = .callstack }); + const prefix = locations.treePrefix(if (callstack) line else ""); + const trimmed = line[prefix.end..]; + const indent = prefix.end; if (!traits(origin).locations) return .{}; - const target = locations.parse(line); + const target = if (callstack) locations.parseRaw(trimmed) else locations.parse(trimmed); const spot = if (metadata) |m| m.at else target.at; if (spot.line == 0) return .{}; var row: RowDecoration = .{ - .location_end = if (metadata) |m| m.location_end else target.end, - .prefix_end = if (metadata) |m| m.code_start else target.end, + .guide_end = indent, + .location_end = if (metadata) |m| m.location_end else indent + target.end, + .prefix_end = if (metadata) |m| m.code_start else indent + target.end, .declaration = if (metadata) |m| m.declaration else false, }; - const source_start = if (metadata) |m| m.code_start else target.code_start; + const source_start = if (metadata) |m| m.code_start else indent + target.code_start; if (source_start >= line.len) return row; if (metadata) |m| if (m.kind == .context) return row; const mark_occurrence = switch (origin) { .search => true, .cmd => |cmd| cmd == .Grep, .query => |kind| switch (kind) { - .definition, .declaration, .type_definition, .implementation, .references => true, + .definition, .declaration, .type_definition, .implementation, .references, .callstack => true, else => false, }, else => false, }; - if (mark_occurrence and spot.col > 0 and spot.end_line == spot.line and + if (mark_occurrence and (if (metadata) |m| m.mark_occurrence else !prefix.branch) and spot.col > 0 and spot.end_line == spot.line and spot.end_col >= spot.col) { - row.mark_start = source_start +| (spot.col - 1); - row.mark_end = @min(line.len, source_start +| spot.end_col); + const source_column = if (metadata) |m| m.source_column else 0; + row.mark_start = source_start +| ((spot.col - 1) -| source_column); + row.mark_end = @min(line.len, source_start +| (spot.end_col -| source_column)); } const is_diagnostic = switch (origin) { .query => |kind| kind == .diagnostics or kind == .workspace_diagnostics, @@ -135,6 +143,25 @@ pub fn decorateRow(output: ?State, line: []const u8, metadata: ?locations.Row) R return row; } +test "callstack guides and Look locations share result decoration" { + const from: State = .{ .from = .{ .query = .callstack } }; + const loc = rowDecoration(from, "└──┬ lib.rs:2:8-10 fn add() {"); + try std.testing.expectEqual(@as(usize, "└──┬ lib.rs:2:8-10".len), loc.location_end); + try std.testing.expect(!loc.declaration); + try std.testing.expect(!usesLocationsConfig(from.from)); + try std.testing.expect(!traits(from.from).jumps); + const call_line = " lib.rs:12:12-20 return calculate(value);"; + const call = rowDecoration(from, call_line); + try std.testing.expectEqualStrings("calculate", call_line[call.mark_start..call.mark_end]); + const reference = rowDecoration(.{ .from = .{ .query = .references } }, call_line[4..]); + try std.testing.expectEqual(reference.mark_start + 4, call.mark_start); + try std.testing.expectEqual(reference.mark_end + 4, call.mark_end); + try std.testing.expectEqual(reference.location_end + 4, call.location_end); + const tab_line = " tab.zig:4:9-11 \treturn run();"; + const tab_call = rowDecoration(from, tab_line); + try std.testing.expectEqualStrings("run", tab_line[tab_call.mark_start..tab_call.mark_end]); +} + test "result decoration follows source byte ranges and diagnostic provenance" { const row = rowDecoration(.{ .from = .search }, "src/a.rs:3:5-7 let abc = 1;"); try std.testing.expectEqualStrings("abc", "src/a.rs:3:5-7 let abc = 1;"[row.mark_start..row.mark_end]); @@ -237,6 +264,7 @@ pub fn traits(o: Origin) Traits { .cmd => |b| builtins.registry.outputTraits(b) orelse unreachable, .query => |k| switch (k) { .hover => .{ .name = config.hover_buffer }, + .callstack => .{ .name = "+Callstack", .steps = true, .locations = true }, // prose: an action list, a diff, a report about the backend .code_action, .format, .status, .explain => .{ .name = config.lsp_buffer }, .rename => .{ .name = config.search_buffer, .steps = true, .locations = true }, @@ -267,7 +295,8 @@ pub fn usesLocationsConfig(from: Origin) bool { const tr = traits(from); return tr.steps and !tr.commands and from != .pdf_links and !std.meta.eql(from, Origin{ .cmd = .Find }) and - !std.meta.eql(from, Origin{ .query = .completion }); + !std.meta.eql(from, Origin{ .query = .completion }) and + !std.meta.eql(from, Origin{ .query = .callstack }); } pub fn fileTraits(out: ?State) Traits { @@ -533,8 +562,11 @@ pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: [] return; } } - if (usesLocationsConfig(from)) { - const formatted = try locations.format(p, dir, content, anchor, true); + if (usesLocationsConfig(from) or std.meta.eql(from, Origin{ .query = .callstack })) { + const formatted = if (std.meta.eql(from, Origin{ .query = .callstack })) + try locations.formatCallstack(p, dir, content) + else + try locations.format(p, dir, content, anchor, true); p.gpa.free(result_content); result_content = formatted.content; result_rows = formatted.rows; @@ -863,7 +895,7 @@ pub fn openThemes(p: *Pardes, id: usize) !void { pub fn isWalkRow(file: *const File.State, row: usize, line: []const u8) bool { const state = file.output orelse return true; - if (usesLocationsConfig(state.from)) return isResultRow(file, row); + if (usesLocationsConfig(state.from) or std.meta.eql(state.from, Origin{ .query = .callstack })) return isResultRow(file, row); if (!std.meta.eql(state.from, Origin{ .cmd = .Themes })) return true; // Section labels are for reading, not stops in the command walk. return std.mem.startsWith(u8, std.mem.trimStart(u8, line, " \t"), comptime config.Runtime.findAction(.theme).?.word ++ " "); @@ -901,11 +933,14 @@ fn openStepped(p: *Pardes, id: usize, from: Origin, content: []u8) !void { fn helpContent(gpa: std.mem.Allocator, prefix: []const u8) ![]u8 { const full_header = "pardes builtins, and how to run each:\nSPC and its keys, a chord, a button, the\ntopbar - or the name, executed anywhere.\n\n"; const group_header = "pardes builtins under SPC"; + const calls_help = "\nCallstack: static caller chains,\nwith signatures and clickable call sites.\nCallers / Callees: one direction at a time.\n"; + const show_calls_help = prefix.len == 0 or std.mem.eql(u8, prefix, "l"); const language_footer = "\nlanguage keys (motions, not words):\n" ++ "gd gD gy gi gr goto: definition,\n" ++ " declaration, type-def,\n" ++ " implementation, refs\n" ++ + "gc Callstack\n" ++ "]d [d ]D [D diagnostics: next,\n" ++ " prev, last, first\n" ++ "= format (applies, one\n" ++ @@ -918,6 +953,7 @@ fn helpContent(gpa: std.mem.Allocator, prefix: []const u8) ![]u8 { full_header.len + language_footer.len else group_header.len + prefix.len * 2 + 2; + if (show_calls_help) len += calls_help.len; for (pardes.builtin_rows) |row| { // a path-less builtin filters as the empty path: in the full listing // (which starts with nothing) and out of every group @@ -948,6 +984,10 @@ fn helpContent(gpa: std.mem.Allocator, prefix: []const u8) ![]u8 { content[at] = '\n'; at += 1; } + if (show_calls_help) { + @memcpy(content[at..][0..calls_help.len], calls_help); + at += calls_help.len; + } if (prefix.len == 0) { @memcpy(content[at..][0..language_footer.len], language_footer); at += language_footer.len; @@ -963,7 +1003,7 @@ pub fn openHelp(p: *Pardes, id: usize, prefix: []const u8) !void { return openRead(p, id, .{ .cmd = .Help }, prefix, content); } -test "full Help renders every builtin row, then the language keys" { +test "full Help renders builtin rows, a call hierarchy guide, then language keys" { const content = try helpContent(std.testing.allocator, ""); defer std.testing.allocator.free(content); @@ -974,17 +1014,22 @@ test "full Help renders every builtin row, then the language keys" { for (pardes.builtin_rows) |row| try std.testing.expectEqualStrings(row.line, lines.next() orelse return error.MissingBuiltinHelpRow); - // ...and after the last row, the language-keys section: the one part of - // the keymap no builtin row can carry, closing the page. + // The short call guide disambiguates the three related commands. + try std.testing.expectEqualStrings("", lines.next() orelse return error.MissingCallHelp); + try std.testing.expectEqualStrings("Callstack: static caller chains,", lines.next() orelse return error.MissingCallHelp); + try std.testing.expectEqualStrings("with signatures and clickable call sites.", lines.next() orelse return error.MissingCallHelp); + try std.testing.expectEqualStrings("Callers / Callees: one direction at a time.", lines.next() orelse return error.MissingCallHelp); + // The language keys close the page. try std.testing.expectEqualStrings("", lines.next() orelse return error.MissingLanguageKeys); try std.testing.expectEqualStrings("language keys (motions, not words):", lines.next() orelse return error.MissingLanguageKeys); try std.testing.expect(std.mem.indexOf(u8, body, "\ngd gD gy gi gr goto: definition,\n") != null); - // the group view stays a pure filter: no footer under a prefix + // The language group also explains call commands, without the motion footer. const group = try helpContent(std.testing.allocator, "l"); defer std.testing.allocator.free(group); try std.testing.expect(std.mem.indexOf(u8, group, "language keys") == null); + try std.testing.expect(std.mem.indexOf(u8, group, "Callstack: static caller chains") != null); } pub fn openConfig(p: *Pardes, id: usize) !void { diff --git a/src/body_layer.zig b/src/body_layer.zig index b24bd6ed..2aa8e5f8 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -113,8 +113,8 @@ fn paintSourceSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: []c const lo = @max(start, row.lo); const hi = @min(end, row.hi); if (lo >= hi) continue; - var col = prefix + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], lo - start))); - const last = if (row.to_edge and hi == end) @as(i32, width) else prefix + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], hi - start))); + var col = prefix + source.pad + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], lo - start))); + const last = if (row.to_edge and hi == end) @as(i32, width) else prefix + source.pad + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], hi - start))); while (col < last and col < width) : (col += 1) { const cell = s.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(visible))); cell.default = false; @@ -399,14 +399,14 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane (if (pane.file != null) panes.File.displayOffset(pane, w.line, w.at, bnd.lo_col) else - panes.File.lineDisplayOffset(visible_line, @intCast(@max(0, w.at)), @intCast(@max(0, bnd.lo_col)))) + vpfx + panes.File.lineDisplayOffset(visible_line, @intCast(@max(0, w.at)), @intCast(@max(0, bnd.lo_col)))) + vpfx + w.pad else - vpfx; + vpfx + w.pad; const cend: i32 = if (w.line == bnd.hi_row and @as(usize, @intCast(@max(0, bnd.hi_col))) < past_view) (if (pane.file != null) panes.File.displayEndOffset(pane, w.line, w.at, bnd.hi_col) else - panes.File.lineDisplayEndOffset(visible_line, @intCast(@max(0, w.at)), @intCast(@max(0, bnd.hi_col)))) + vpfx + panes.File.lineDisplayEndOffset(visible_line, @intCast(@max(0, w.at)), @intCast(@max(0, bnd.hi_col)))) + vpfx + w.pad else @as(i32, tw) - 1; var col: i32 = @max(cstart, vpfx); @@ -432,7 +432,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane modal.lineSlice(body, @intCast(@max(0, cw.row))), @intCast(@max(0, cw.at)), @intCast(@max(0, sr.col)), - )) + vpfx; + )) + vpfx + cw.pad; if (crow >= pane.tag_rows and crow < @as(i32, body_bottom) and ccol >= vpfx and ccol < tw) { const cell = s.at(tx + @as(u16, @intCast(ccol)), body_y + @as(u16, @intCast(crow - pane.tag_rows))); cell.default = false; @@ -455,7 +455,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane const row: i32 = @intCast(pos.row); const wp = pane.wrapRow(row, @intCast(pos.col)); const cx = if (pane.file != null) - @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayOffset(pane, row, wp.at, @intCast(pos.col)) + @as(i32, panes.File.gutterWidth(pane)) + wp.pad + panes.File.displayOffset(pane, row, wp.at, @intCast(pos.col)) else panes.File.lineDisplayOffset(modal.lineSlice(flat, pos.row), @intCast(@max(0, wp.at)), pos.col); if (wp.row >= 0 and wp.row < body_h and cx >= 0 and cx < tw) @@ -478,20 +478,20 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane // Off the view, the cursor is not measured (its column may be // millions of bytes along a line whose start is shown). if (cwp.row >= 0 and prow < body_bottom and !pastView(pane, body, crow, cwp.row, cwp.at, ccol, tw)) { - // Files store source-byte columns; the Surface stores display - // cells, so account for every expanded tab before the cursor. - const cx = if (pane.file != null) - @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayOffset(pane, crow, cwp.at, ccol) - else if (pane.body.cur_pinned) - panes.File.lineDisplayOffset( - modal.lineSlice(body, @intCast(@max(0, cwp.row))), - @intCast(@max(0, cwp.at)), - @intCast(@max(0, ccol)), - ) - else - ccol; - if (prow >= pane.tag_rows and cx >= 0 and prow < body_bottom and cx < tw) - s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = body_y + @as(u16, @intCast(prow - pane.tag_rows)), .bar = pane.body.mode == .insert }; + // Files store source-byte columns; the Surface stores display + // cells, so account for every expanded tab before the cursor. + const cx = if (pane.file != null) + @as(i32, panes.File.gutterWidth(pane)) + cwp.pad + panes.File.displayOffset(pane, crow, cwp.at, ccol) + else if (pane.body.cur_pinned) + panes.File.lineDisplayOffset( + modal.lineSlice(body, @intCast(@max(0, cwp.row))), + @intCast(@max(0, cwp.at)), + @intCast(@max(0, ccol)), + ) + else + ccol; + if (prow >= pane.tag_rows and cx >= 0 and prow < body_bottom and cx < tw) + s.cursor = .{ .x = tx + @as(u16, @intCast(cx)), .y = body_y + @as(u16, @intCast(prow - pane.tag_rows)), .bar = pane.body.mode == .insert }; } } else if (panes.terminal.visibleCursor(pane)) |cur| { if (cur.y + pane.tag_rows < body_bottom and cur.x < tw) diff --git a/src/builtins.zig b/src/builtins.zig index ef769b48..f73c5982 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -236,8 +236,8 @@ pub const registry = struct { // are the default .toggle, .transition, .scene, .dump_dir, .choice, .lift, .shader_animation, .motion, .shell => false, .theme, .font, .tagline_size, .window_opacity, .window_blur, .message_ms, .shader, .inactive_dim, .grip_width => true, - // bare, it says the width (exec.applySettingBuiltin) - .tab => false, + // bare, it says the current value (exec.applySettingBuiltin) + .tab, .callstack_depth => false, }; unreachable; } @@ -1839,6 +1839,7 @@ pub const Forward = struct { /// Select the next Look location across panes; Enter opens it. pub const LookNext = struct { + pub const quiet = true; pub fn run(c: Ctx) void { look.lookWalk(c.p, 1); } @@ -1846,6 +1847,7 @@ pub const LookNext = struct { /// Select the previous Look location across panes; Enter opens it. pub const LookPrev = struct { + pub const quiet = true; pub fn run(c: Ctx) void { look.lookWalk(c.p, -1); } @@ -1952,6 +1954,13 @@ pub const WsDiagnostics = struct { } }; +/// Show outermost callers first, with signatures and call sites (gc). +pub const Callstack = struct { + pub fn run(c: Ctx) void { + c.p.lspRequest(c.id, .callstack, ""); + } +}; + /// List the callers of the function under the cursor. pub const Callers = struct { pub fn run(c: Ctx) void { diff --git a/src/colors.zig b/src/colors.zig index 2dcb906a..379d1301 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -126,9 +126,11 @@ test "every faithful port meets pardes's chrome floors in its own colours, with } test "a derived separator or tint keeps the theme's own when it already stands off" { - const forge = &themes[for (themes[0..native_count], 0..) |t, i| { - if (std.mem.eql(u8, t.name, "forge")) break i; - } else unreachable]; + const forge = &themes[ + for (themes[0..native_count], 0..) |t, i| { + if (std.mem.eql(u8, t.name, "forge")) break i; + } else unreachable + ]; const chrome = ChromeTheme.fromTheme(forge); try std.testing.expectEqual(forge.border.?, chrome.border); // forge's own tint is 1.23:1 off its tag: pushed on the way it leans. @@ -1075,7 +1077,7 @@ test "render uses target content colors while chrome is in flight" { Color{ .rgb = source_chrome.tag_bg }, surface.at(0, 0).style.bg, ); - const topbar_cell = surface.at(0, 0); + const topbar_cell = surface.at(@import("pardes.zig").TAG_TEXT_INSET, 0); try std.testing.expect(!std.mem.eql(u8, topbar_cell.grapheme(), " ")); try std.testing.expectEqual(FontRole.tagline, topbar_cell.style.font_role); const r = p.rects[0]; diff --git a/src/config.zig b/src/config.zig index fb34b746..50009660 100644 --- a/src/config.zig +++ b/src/config.zig @@ -43,6 +43,7 @@ pub const leader_path = paths: { .WsDiagnostics = "lD", .Lspinfo = "li", .Lspwhy = "lw", + .Callstack = "lb", .Callers = "lc", .Callees = "lC", .Supertypes = "lt", @@ -67,6 +68,9 @@ pub const leader_path = paths: { .Putall = null, .Incl = null, .Tab = null, + .CallstackDepth = null, + .CallstackLayout = null, + .CallstackCorners = null, .Zerox = null, .ClipYank = "y", .ClipYankMain = "Y", @@ -580,7 +584,8 @@ pub const goto_line_down: []const Chord = &.{.{ .cp = 'j' }}; pub const goto_line_up: []const Chord = &.{.{ .cp = 'k' }}; pub const goto_column: []const Chord = &.{.{ .cp = '|' }}; pub const goto_view_top: []const Chord = &.{.{ .cp = 't' }}; -pub const goto_view_center: []const Chord = &.{.{ .cp = 'c' }}; +// gc opens Callstack; it no longer moves the cursor to the viewport center. +pub const goto_view_center: []const Chord = &.{}; pub const goto_view_bottom: []const Chord = &.{.{ .cp = 'b' }}; pub const goto_last_modification: []const Chord = &.{.{ .cp = '.' }}; pub const goto_word: []const Chord = &.{.{ .cp = 'w' }}; @@ -591,6 +596,7 @@ pub const goto_declaration: []const Chord = &.{.{ .cp = 'D' }}; pub const goto_type_definition: []const Chord = &.{.{ .cp = 'y' }}; pub const goto_implementation: []const Chord = &.{.{ .cp = 'i' }}; pub const goto_references: []const Chord = &.{.{ .cp = 'r' }}; +pub const goto_callstack: []const Chord = &.{.{ .cp = 'c' }}; pub const match_bracket: []const Chord = &.{.{ .cp = 'm' }}; pub const match_inside = 'i'; @@ -835,6 +841,9 @@ pub const Runtime = struct { /// acme's Tab: a tab's width in cells, in every pane (config.tab_now /// is what the drawing and the column arithmetic read). tab: u16 = tab_width, + callstack_layout: CallstackLayout = .stacked, + callstack_corners: CallstackCorners = .rounded, + callstack_depth: u8 = @import("lsp/lsp.zig").callstack_default_depth, pub const ShaderAnimation = enum { off, on, always }; pub const Placement = enum { acme, pardes }; @@ -845,8 +854,10 @@ pub const Runtime = struct { pub const Pager = enum { pardes, off }; pub const TermImages = enum { real, petscii }; pub const JumpScope = enum { file, all }; + pub const CallstackLayout = enum { @"inline", stacked }; + pub const CallstackCorners = @import("lsp/lsp.zig").CallstackCorners; /// A setting that is one of a few words, each an enum field of Runtime. - pub const Choice = enum { placement, boot_shell, look_word, dir_look, diff_look, pager, term_images, jump_scope }; + pub const Choice = enum { placement, boot_shell, look_word, dir_look, diff_look, pager, term_images, jump_scope, callstack_layout, callstack_corners }; /// shadow: a soft drop shadow. rim: a light hairline along the top of /// the focused pane's tag rows. auto: a shadow on a light page; on a @@ -1034,6 +1045,7 @@ pub const Runtime = struct { inactive_dim, grip_width, tab, + callstack_depth, transition: animation.Transition, scene: Scene, /// A Shadertoy file into the post chain or out of it; `off` empties @@ -1118,6 +1130,9 @@ pub const Runtime = struct { .{ .word = "PagerColor", .action = .{ .toggle = .pager_color }, .doc = "A +Pager keeps its program's colours, on or off; for the next text paged." }, .{ .word = "TermImages", .action = .{ .choice = .term_images }, .doc = "How a new terminal draws its program's kitty graphics: real, as pixels where it can, or petscii, as glyph art." }, .{ .word = "JumpScope", .action = .{ .choice = .jump_scope }, .doc = "What Back and Forward keep to: file, the focused pane's file until it runs out that way, or all, every place in order." }, + .{ .word = "CallstackLayout", .action = .{ .choice = .callstack_layout }, .doc = "Callstack snippets below their locations (stacked, the default) or beside them (inline); bare, it switches layouts. Applies to the next Callstack query." }, + .{ .word = "CallstackCorners", .action = .{ .choice = .callstack_corners }, .doc = "Callstack tree corners: rounded (the default) or square; bare, it switches styles. Applies to the next Callstack query." }, + .{ .word = "CallstackDepth", .action = .callstack_depth, .doc = "Caller levels collected by Callstack, 1 through 64; default 8. Bare, it says the current limit." }, .{ .word = "Tab", .action = .tab, .doc = "A tab's width in cells, 1 through 16, in every pane; bare, it says the width." }, }; @@ -1319,6 +1334,12 @@ pub const Runtime = struct { if (percent < 50 or percent > 300) return false; state.grip_width = percent; }, + .callstack_depth => { + const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); + const depth = std.fmt.parseInt(u8, text, 10) catch return false; + if (depth < 1 or depth > @import("lsp/lsp.zig").callstack_max_depth) return false; + state.callstack_depth = depth; + }, .tab => { const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); const width = std.fmt.parseInt(u16, text, 10) catch return false; @@ -1361,6 +1382,7 @@ pub const Runtime = struct { .inactive_dim, .window_opacity, .window_blur => "0-100 (a percentage)", .grip_width => "50-300 (a percentage)", .tab => "1-16 (cells)", + .callstack_depth => "1-64 (levels)", .tagline_size => std.fmt.comptimePrint("{d}-{d} (a percentage)", .{ tagline_percent_min, tagline_percent_max }), .message_ms => std.fmt.comptimePrint("0-{d} (milliseconds)", .{message_ms_max}), .shell => "a path of at most 255 bytes; bare, $SHELL, else /bin/sh", @@ -1523,6 +1545,7 @@ pub const Runtime = struct { try out.print("# {s} unsupported\n", .{setting.word}), .motion => try out.print("{s} {s}\n", .{ setting.word, @tagName(state.motion) }), .inactive_dim => try out.print("{s} {d}\n", .{ setting.word, state.inactive_dim }), + .callstack_depth => try out.print("{s} {d}\n", .{ setting.word, state.callstack_depth }), .tab => try out.print("{s} {d}\n", .{ setting.word, state.tab }), .grip_width => if (setting.enabled(context.capabilities)) try out.print("{s} {d}\n", .{ setting.word, state.grip_width }) @@ -1816,11 +1839,14 @@ pub const Runtime = struct { .pager => "off", .term_images => "petscii", .jump_scope => "all", + .callstack_layout => "inline", + .callstack_corners => "square", }, .lift => "rim", .motion => "playful", .inactive_dim => "35", .grip_width => "200", + .callstack_depth => "16", .tab => "8", else => null, }; @@ -1892,11 +1918,14 @@ pub const Runtime = struct { .pager => "Pager off\n", .term_images => "TermImages petscii\n", .jump_scope => "JumpScope all\n", + .callstack_layout => "CallstackLayout inline\n", + .callstack_corners => "CallstackCorners square\n", }, .lift => "Lift rim\n", .motion => "Motion playful\n", .inactive_dim => "InactiveDim 35\n", .grip_width => "GripWidth 200\n", + .callstack_depth => "CallstackDepth 16\n", .tab => "Tab 8\n", .theme, .font => unreachable, }; @@ -2474,3 +2503,16 @@ test "reference.typ's #fstree is the tree the session serves, file for file" { }; if (drift) return error.FsTreeDrift; } + +test "CallstackDepth is bounded and keeps the last valid runtime limit" { + var state: Runtime = .{}; + try std.testing.expectEqual(@as(u8, 8), state.callstack_depth); + for ([_][]const u8{ "1", "8", "16", "64" }) |value| { + try std.testing.expect(Runtime.apply(&state, Runtime.find("CallstackDepth").?, value)); + try std.testing.expectEqual(try std.fmt.parseInt(u8, value, 10), state.callstack_depth); + } + for ([_][]const u8{ "0", "65", "256", "-1", "eight", "" }) |value| { + try std.testing.expect(!Runtime.apply(&state, Runtime.find("CallstackDepth").?, value)); + try std.testing.expectEqual(@as(u8, 64), state.callstack_depth); + } +} diff --git a/src/draw.zig b/src/draw.zig index 9fcbb15f..b35d55e8 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -412,15 +412,15 @@ fn recede(p: *Pardes, s: *Surface, id: usize, amount: f32, focused: bool) void { } } const body = &s.body_layers[id]; - if (body.rows != 0) for (body.cells[0..@as(usize, body.cols) * body.rows]) |*cell| { + if (body.rows != 0) for (body.cells[0 .. @as(usize, body.cols) * body.rows]) |*cell| { if (!(focused and selected(cell, th.sel_bg))) fadeStyle(&cell.style, th.fg, th.bg, palette, amount, &memo); }; if (focused) return; const tag = &s.tag_layers[id]; - if (tag.rows != 0) for (tag.cells[0..@as(usize, tag.cols) * tag.rows]) |*cell| fadeStyle(&cell.style, chrome.tag_fg, tag.bg, palette, amount, &memo); + if (tag.rows != 0) for (tag.cells[0 .. @as(usize, tag.cols) * tag.rows]) |*cell| fadeStyle(&cell.style, chrome.tag_fg, tag.bg, palette, amount, &memo); for (0..Pane.Notices.max) |i| { const notice = &s.tag_layers[NOTICE_LAYER_BASE + id * Pane.Notices.max + i]; - if (notice.rows != 0) for (notice.cells[0..@as(usize, notice.cols) * notice.rows]) |*cell| fadeStyle(&cell.style, chrome.tag_fg, notice.bg, palette, amount, &memo); + if (notice.rows != 0) for (notice.cells[0 .. @as(usize, notice.cols) * notice.rows]) |*cell| fadeStyle(&cell.style, chrome.tag_fg, notice.bg, palette, amount, &memo); } } @@ -978,7 +978,12 @@ pub fn paintHeaders(p: *Pardes, s: *Surface, arena: std.mem.Allocator) !void { if (s.region(.workspace_tag, Region.none)) |region| { const top = if (p.header_focus and p.header_column == null) p.header_top else 0; const layer = &s.tag_layers[MAX_PANES + MAX_COLS]; - try renderHeaderLayer(p, arena, layer, .workspace, 0, region.rect, tagline.topbar(p), top, chrome.tag_bg, chrome.tag_fg); + var viewport = region.rect; + const inset = @min(TAG_TEXT_INSET, viewport.w); + s.fill(viewport.x, viewport.y, inset, viewport.h, .{ .bg = .{ .rgb = chrome.tag_bg }, .fg = .{ .rgb = chrome.tag_fg }, .font_role = .tagline }); + viewport.x += inset; + viewport.w -= inset; + try renderHeaderLayer(p, arena, layer, .workspace, 0, viewport, tagline.topbar(p), top, chrome.tag_bg, chrome.tag_fg); joinHeaderRows(s, layer, chrome.tag_fg); } const column_rows = p.columnBarHeight(); @@ -1348,8 +1353,7 @@ pub fn paintPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pa const at = modal.positionAt(shown.text, shown.fromReal(@intCast(@max(0, pane.input.cur_col)))); if (at.row < top or at.row >= top + rows) break :caret null; break :caret .{ .row = at.row - top, .at = @min(lines[at.row - top].len, at.col) }; - } - else if (pane.focus == .tag and pane.prompt == .none) caret: { + } else if (pane.focus == .tag and pane.prompt == .none) caret: { const real = modal.offsetAt(whole, .{ .row = @intCast(@max(0, pane.tag.cur_row)), .col = @intCast(@max(0, pane.tag.cur_col)) }); const at = modal.positionAt(shown.text, shown.fromReal(real)); if (at.row < top or at.row >= top + rows) break :caret null; @@ -2392,7 +2396,7 @@ test "a pane focus reaches brightens on the same spring the one it leaves dims o // The file's first glyph's ink, in whichever form its body has. fn of(s: *const Surface) [3]u8 { const body = &s.body_layers[0]; - const cells = if (body.rows != 0) body.cells[0..@as(usize, body.cols) * body.rows] else s.cells; + const cells = if (body.rows != 0) body.cells[0 .. @as(usize, body.cols) * body.rows] else s.cells; for (cells) |cell| if (!cell.default and cell.len == 1 and cell.text[0] == 's' and cell.style.font_role == .body) return switch (cell.style.fg) { .rgb => |rgb| rgb, else => .{ 0, 0, 0 }, diff --git a/src/dump.zig b/src/dump.zig index 201f5bf2..402918c4 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -56,7 +56,7 @@ pub fn outPath(buf: *[1024:0]u8, dir_setting: []const u8) ?[:0]const u8 { const ds = es.getDaySeconds(); var stamp: [32]u8 = undefined; const base = std.fmt.bufPrint(&stamp, "pardes-{d:0>4}{d:0>2}{d:0>2}-{d:0>2}{d:0>2}{d:0>2}", .{ - yd.year, md.month.numeric(), @as(u8, md.day_index) + 1, + yd.year, md.month.numeric(), @as(u8, md.day_index) + 1, ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(), }) catch return null; return uniqueIn(buf, dir, base); @@ -194,6 +194,8 @@ pub const Terminal = struct { }; pub const LocationRow = struct { + mark_occurrence: bool = true, + source_column: usize = 0, kind: enum { match, context, preview }, declaration: bool = false, path: []const u8, diff --git a/src/edit.zig b/src/edit.zig index b2909d87..5dbce0bf 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -241,8 +241,8 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { if (raw) next = .{ .line = source.line + 1, .at = 0 }; const end = if (next.line == source.line) @min(line.len, @as(usize, @intCast(@max(0, next.at)))) else line.len; const start: usize = @intCast(@max(0, source.at)); - const lo = @min(end, panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, left - prefix)))); - const at = @min(end, panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, right - prefix)))); + const lo = @min(end, panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, left - prefix - source.pad)))); + const at = @min(end, panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, right - prefix - source.pad)))); row.* = .{ .row = source.line, .lo = lo, diff --git a/src/exec.zig b/src/exec.zig index 2a6bd55c..d03a4a48 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -140,7 +140,7 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l &pane.body, wrapped.line, wrapped.at, - clicked.c0 - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0), + clicked.c0 - wrapped.pad - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0), ) else clicked.c0; @@ -214,9 +214,9 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l const last = pane.wrapRow(row, hi - 1); if (first.row < 0 or last.row < 0) return result; expanded.r0 = first.row + @as(i32, pane.tag_rows); - expanded.c0 = @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayOffset(pane, row, first.at, 0); + expanded.c0 = @as(i32, panes.File.gutterWidth(pane)) + first.pad + panes.File.displayOffset(pane, row, first.at, 0); expanded.r1 = last.row + @as(i32, pane.tag_rows); - expanded.c1 = @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayEndOffset(pane, row, last.at, hi - 1); + expanded.c1 = @as(i32, panes.File.gutterWidth(pane)) + last.pad + panes.File.displayEndOffset(pane, row, last.at, hi - 1); } else { const shown = if (raw) raw_line else line; expanded.c0 = 0; @@ -242,9 +242,9 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l const last = pane.wrapRow(row, hi - 1); if (first.row >= 0 and last.row >= 0) { expanded.r0 = first.row + @as(i32, pane.tag_rows); - expanded.c0 = @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayOffset(pane, row, first.at, lo); + expanded.c0 = @as(i32, panes.File.gutterWidth(pane)) + first.pad + panes.File.displayOffset(pane, row, first.at, lo); expanded.r1 = last.row + @as(i32, pane.tag_rows); - expanded.c1 = @as(i32, panes.File.gutterWidth(pane)) + panes.File.displayEndOffset(pane, row, last.at, hi - 1); + expanded.c1 = @as(i32, panes.File.gutterWidth(pane)) + last.pad + panes.File.displayEndOffset(pane, row, last.at, hi - 1); } result.preview = expanded; result.expanded = expanded; @@ -1120,6 +1120,12 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] } if (!p.settings.apply(setting, want)) p.reportFailure(p.active, "Shell: takes " ++ comptime config.Runtime.takes(.shell).?); }, + .callstack_depth => if (arg == null) { + var said: [40]u8 = undefined; + return p.setMessage(p.active, std.fmt.bufPrint(&said, "CallstackDepth {d}", .{p.settings.callstack_depth}) catch "CallstackDepth"); + } else if (!p.settings.apply(setting, arg)) { + p.reportFailure(p.active, "CallstackDepth: takes " ++ comptime config.Runtime.takes(.callstack_depth).?); + }, // Bare, it says the width, as acme's Tab does. .tab => if (arg == null) { var said: [32]u8 = undefined; diff --git a/src/host_io.zig b/src/host_io.zig index 7314affc..a90c903d 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -136,6 +136,8 @@ pub const Lsp = struct { /// One language query, owned by the worker that runs it. pub const Job = struct { + callstack_depth: u8 = pardes.lsp.callstack_default_depth, + callstack_corners: pardes.lsp.CallstackCorners = .rounded, id: u32, kind: pardes.lsp.Kind, offset: u32, @@ -178,6 +180,8 @@ pub const Lsp = struct { const root = try gpa.dupe(u8, filesystem.localPath(declared_root) orelse declared_root); errdefer gpa.free(root); job.* = .{ + .callstack_depth = core.settings.callstack_depth, + .callstack_corners = core.settings.callstack_corners, .id = req.id, .kind = req.kind, .offset = req.offset, @@ -234,6 +238,8 @@ pub const Lsp = struct { .arg = job.arg, .root = job.root, .others = job.others, + .callstack_depth = job.callstack_depth, + .callstack_corners = job.callstack_corners, }, &out.writer) catch { deliver(ctx, job.id, null); return; @@ -250,6 +256,8 @@ pub const Lsp = struct { const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); + core.settings.callstack_depth = 16; + core.settings.callstack_corners = .square; var needle: [6]u8 = "needle".*; const job = try snapshot(gpa, core, .{ .id = 7, @@ -260,6 +268,10 @@ pub const Lsp = struct { }); defer job.free(gpa); + core.settings.callstack_depth = 2; + core.settings.callstack_corners = .rounded; + try std.testing.expectEqual(pardes.lsp.CallstackCorners.square, job.callstack_corners); + try std.testing.expectEqual(@as(u8, 16), job.callstack_depth); try std.testing.expectEqual(@as(u32, 7), job.id); try std.testing.expectEqual(pardes.lsp.Kind.status, job.kind); try std.testing.expectEqualStrings("needle", job.arg); diff --git a/src/layout.zig b/src/layout.zig index a2211dfd..40bce75a 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -266,6 +266,28 @@ pub fn setColumnWeights(p: *Pardes, col: usize, heights: *const [MAX_PANES]u16) } } +/// Give a newly opened report enough rows to read, borrowing only space +/// above the other panes' usable minima. Keep their tags and bodies visible. +pub fn givePaneRows(p: *Pardes, id: usize, wanted: u16, context: usize) void { + const at = findPane(p, id) orelse return; + compute(p); + var heights: [MAX_PANES]u16 = @splat(0); + for (p.col_panes[at.col][0..p.col_n[at.col]]) |other| heights[other] = p.rects[other].h; + var missing = wanted -| heights[id]; + for (p.col_panes[at.col][0..p.col_n[at.col]]) |other| { + if (other == id or p.panes[other].?.collapsed) continue; + const body_rows: u16 = if (other == context) 6 else 3; + const minimum = @max(minRows(p, other), p.panes[other].?.tag_rows + body_rows); + const take = @min(missing, heights[other] -| minimum); + heights[other] -= take; + heights[id] += take; + missing -= take; + if (missing == 0) break; + } + setColumnWeights(p, at.col, &heights); + p.sync(); +} + pub fn applyRowSplit(p: *Pardes, cc: usize, k: usize, cur_y: u16) void { if (k + 1 >= p.col_n[cc]) return; const a = p.panes[p.col_panes[cc][k]] orelse return; diff --git a/src/locations.zig b/src/locations.zig index 7755f6fd..745393e5 100644 --- a/src/locations.zig +++ b/src/locations.zig @@ -16,6 +16,8 @@ pub fn isContextLine(line: []const u8) bool { pub const Row = struct { kind: enum { match, context, preview }, declaration: bool = false, + mark_occurrence: bool = true, + source_column: usize = 0, path: []u8, at: look.Spot, location_end: usize, @@ -34,7 +36,7 @@ pub fn freeRows(gpa: std.mem.Allocator, rows: []Row) void { pub fn equalRows(a: []const Row, b: []const Row) bool { if (a.len != b.len) return false; for (a, b) |left, right| { - if (left.kind != right.kind or left.declaration != right.declaration or !std.meta.eql(left.at, right.at) or + if (left.kind != right.kind or left.declaration != right.declaration or left.mark_occurrence != right.mark_occurrence or left.source_column != right.source_column or !std.meta.eql(left.at, right.at) or left.location_end != right.location_end or left.code_start != right.code_start or !std.mem.eql(u8, left.path, right.path) or !std.mem.eql(u8, left.colors, right.colors)) return false; } @@ -119,7 +121,8 @@ pub fn parse(line: []const u8) Parsed { return parseRaw(line); } -fn parseRaw(line: []const u8) Parsed { +/// Native producer rows have one separator byte before untouched source. +pub fn parseRaw(line: []const u8) Parsed { var at: usize = 1; while (at < line.len) : (at += 1) { if (line[at] != ':' or at + 1 == line.len or !std.ascii.isDigit(line[at + 1])) continue; @@ -148,6 +151,8 @@ const Pending = struct { original: ?usize, hidden: bool = false, declaration: bool = false, + mark_occurrence: bool = true, + source_column: usize = 0, depth: usize = 0, colors: []const u8 = &.{}, @@ -174,6 +179,174 @@ pub fn sourceText(p: *pardes.Pardes, arena: std.mem.Allocator, dir: []const u8, return .{ .path = lexical, .bytes = arena.dupe(u8, bytes) catch return null }; } +/// Byte boundary after the guides in a call tree, independent of source indentation. +pub fn treePrefix(line: []const u8) struct { end: usize, branch: bool } { + var at: usize = 0; + while (at < line.len) { + for ([_][]const u8{ "╰──┬ ", "├──╮ ", "╰──╮ ", "├─── ", "╰─── ", "├──┬ ", "└──┬ ", "└─── " }) |branch| { + if (std.mem.startsWith(u8, line[at..], branch)) return .{ .end = at + branch.len, .branch = true }; + } + if (std.mem.startsWith(u8, line[at..], "├─ ") or std.mem.startsWith(u8, line[at..], "└─ ") or std.mem.startsWith(u8, line[at..], "╰─ ")) + return .{ .end = at + "└─ ".len, .branch = false }; + if (std.mem.startsWith(u8, line[at..], "│")) { + at += "│".len; + } else if (line[at] == ' ') { + at += 1; + } else break; + } + return .{ .end = at, .branch = false }; +} + +/// The same tree columns carried across a soft-wrapped display row. This is +/// presentation only: source bytes and Look addresses remain untouched. +pub fn treeContinuation(line: []const u8, buffer: []u8, max_cells: usize) []const u8 { + const prefix = line[0..treePrefix(line).end]; + var out: std.Io.Writer = .fixed(buffer); + var it = (std.unicode.Utf8View.init(prefix) catch return "").iterator(); + var cells: usize = 0; + var end: usize = 0; + while (it.nextCodepoint()) |cp| { + if (cells >= max_cells) break; + out.writeAll(if (cp == '│' or cp == '├' or cp == '┬' or cp == '╮') "│" else " ") catch break; + cells += 1; + if (cp != ' ') end = out.buffered().len; + } + if (end == 0) return ""; + // Keep one cell between the continuation and the wrapped source text. + if (end < out.buffered().len) end += 1; + return out.buffered()[0..end]; +} + +/// Enrich caller nodes on the UI thread, using the same source/declaration cache +/// as LocationsContext. The LSP worker only supplies relationships and addresses. +pub fn formatCallstack(p: *pardes.Pardes, dir: []const u8, input: []const u8) !Result { + const arena = p.scratch.allocator(); + var out: std.Io.Writer.Allocating = .init(p.gpa); + errdefer out.deinit(); + var rows: std.ArrayList(Row) = .empty; + errdefer { + for (rows.items) |row| { + p.gpa.free(row.path); + p.gpa.free(row.colors); + } + rows.deinit(p.gpa); + } + const stacked = p.settings.callstack_layout == .stacked; + var sources: std.StringHashMap(?Source) = .init(arena); + var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, input, "\n"), '\n'); + while (lines.next()) |raw| { + const mark = @import("lsp/lsp.zig").callstack_match; + const focus = std.mem.startsWith(u8, raw, mark); + const line = if (focus) raw[mark.len..] else raw; + const prefix = treePrefix(line); + const target = parseRaw(line[prefix.end..]); + if (target.at.line == 0) { + try out.writer.print("{s}\n", .{line}); + try appendMetadata(p.gpa, &rows, .{ .path = "", .at = .{}, .label = "", .code = "", .original = null }, .context, 0, line.len, false); + continue; + } + const entry = try sources.getOrPut(target.path); + if (!entry.found_existing) entry.value_ptr.* = sourceText(p, arena, dir, target.path); + const source = entry.value_ptr.*; + var cached: Cache.Hit = .{ .analysis = .{} }; + defer cached.deinit(p.tree_sitter_gpa); + if (source) |text| cached = p.locations_cache.get(p.tree_sitter_gpa, text.path, text.bytes, true, true) catch .{ .analysis = .{} }; + var code = line[prefix.end + target.code_start ..]; + var colors: []const u8 = &.{}; + var source_row = target.at.line - 1; + if (source) |text| { + const row = target.at.line - 1; + if (prefix.branch) { + // Choose the innermost header containing the server's name range. + var chosen: ?syntax.ContextDeclaration = null; + for (cached.analysis.declarations) |declaration| { + if (declaration.start_line <= row and row <= declaration.header_end_line) { + if (chosen == null or declaration.end_byte - declaration.start_byte < chosen.?.end_byte - chosen.?.start_byte) + chosen = declaration; + } + } + if (chosen) |header| { + code = text.bytes[header.start_byte..header.header_end_byte]; + source_row = header.start_line; + } else { + const fallback = @import("modal.zig").lineSlice(text.bytes, row); + if (fallback.len > 0) code = fallback; + } + } + { + const offset = @import("modal.zig").lineStartOffset(text.bytes, source_row); + if (offset + code.len <= cached.analysis.colors.len and + std.mem.eql(u8, code, text.bytes[offset..][0..code.len])) + colors = cached.analysis.colors[offset..][0..code.len]; + } + } + const recursion = prefix.branch and std.mem.endsWith(u8, line, " ↻ recursion"); + const first_line = code[0 .. std.mem.indexOfScalar(u8, code, '\n') orelse code.len]; + const source_indent = if (stacked) first_line.len - std.mem.trimStart(u8, first_line, " \t").len else 0; + if (stacked) { + const end = prefix.end + target.end; + try out.writer.print("{s}\n", .{line[0..end]}); + try appendMetadata(p.gpa, &rows, .{ .path = target.path, .at = target.at, .label = "", .code = "", .original = null, .mark_occurrence = false }, .match, end, end, false); + } + var header_lines = std.mem.splitScalar(u8, code, '\n'); + var first = true; + var color_offset: usize = 0; + while (header_lines.next()) |code_line| { + const start = out.written().len; + if (stacked) { + var guide_buf: [1024]u8 = undefined; + const guide = treeContinuation(line, &guide_buf, std.math.maxInt(usize)); + try out.writer.writeAll(guide); + const width = pardes.panes.File.displayWidth(line[0..prefix.end]); + try out.writer.splatByteAll(' ', width -| pardes.panes.File.displayWidth(guide)); + } else if (first) { + try out.writer.writeAll(line[0 .. prefix.end + target.end]); + try out.writer.writeByte(' '); + } else { + const branch_start = prefix.end - "└──┬ ".len; + try out.writer.writeAll(line[0..branch_start]); + try out.writer.writeAll(if (std.mem.startsWith(u8, line[branch_start..], "├")) "│ " else " "); + try out.writer.writeAll(if (std.mem.endsWith(u8, line[0..prefix.end], "┬ ") or std.mem.endsWith(u8, line[0..prefix.end], "╮ ")) "│ " else " "); + try out.writer.splatByteAll(' ', pardes.panes.File.displayWidth(line[prefix.end..][0..target.end]) + 1); + } + const code_start = out.written().len - start; + const trim = @min(source_indent, code_line.len - std.mem.trimStart(u8, code_line, " \t").len); + try out.writer.writeAll(code_line[trim..]); + const recursion_note = recursion and first and !std.mem.endsWith(u8, code_line, " ↻ recursion"); + if (recursion_note) try out.writer.writeAll(" ↻ recursion"); + try out.writer.writeByte('\n'); + try appendMetadata(p.gpa, &rows, .{ + .path = target.path, + .at = if (first) target.at else .{ .line = source_row + 1 }, + .label = "", + .code = code_line[trim..], + .source_column = trim, + .original = null, + .mark_occurrence = focus and !prefix.branch, + .colors = if (colors.len >= color_offset + code_line.len) colors[color_offset + trim ..][0 .. code_line.len - trim] else &.{}, + }, if (first) (if (stacked) .preview else .match) else .context, if (first and !stacked) prefix.end + target.end else 0, code_start, true); + // Recursion notes are prose, outside the source snapshot. + if (recursion_note) { + const added = " ↻ recursion".len; + const row = &rows.items[rows.items.len - 1]; + if (row.colors.len > 0) { + const expanded = try p.gpa.alloc(u8, row.colors.len + added); + @memcpy(expanded[0..row.colors.len], row.colors); + @memset(expanded[row.colors.len..], 0); + p.gpa.free(row.colors); + row.colors = expanded; + } + } + color_offset += code_line.len + 1; + source_row += 1; + first = false; + } + } + const owned_rows = try rows.toOwnedSlice(p.gpa); + errdefer freeRows(p.gpa, owned_rows); + return .{ .content = try out.toOwnedSlice(), .rows = owned_rows, .anchor = null }; +} + /// Inputs are sorted results. Expand each source group, merge context with /// matches, then align groups of eight matches. All temporary source data /// stays in the caller's scratch arena; returned text and rows are owned. @@ -334,7 +507,7 @@ fn appendMetadata(gpa: std.mem.Allocator, rows: *std.ArrayList(Row), pending: Pe errdefer gpa.free(path); const colors = try gpa.dupe(u8, if (source) pending.colors else &.{}); errdefer gpa.free(colors); - try rows.append(gpa, .{ .kind = kind, .declaration = pending.declaration, .path = path, .at = pending.at, .location_end = location_end, .code_start = code_start, .colors = colors }); + try rows.append(gpa, .{ .kind = kind, .declaration = pending.declaration, .mark_occurrence = pending.mark_occurrence, .source_column = pending.source_column, .path = path, .at = pending.at, .location_end = location_end, .code_start = code_start, .colors = colors }); } const alignment_entries = 8; diff --git a/src/look.zig b/src/look.zig index 5795979f..1065cb02 100644 --- a/src/look.zig +++ b/src/look.zig @@ -524,7 +524,7 @@ pub fn cursorWordSel(p: *Pardes, pane: *Pane) Pane.Sel { const w = pane.wrapRow(pane.body.cur_row, pane.body.cur_col); const vrow = w.row + @as(i32, pane.tag_rows); const vcol = if (pane.file != null) - panes.File.displayOffset(pane, pane.body.cur_row, w.at, pane.body.cur_col) + @as(i32, panes.File.gutterWidth(pane)) + w.pad + panes.File.displayOffset(pane, pane.body.cur_row, w.at, pane.body.cur_col) + @as(i32, panes.File.gutterWidth(pane)) else blk: { const lines = edit.paneCursorLines(p, &pane.body) catch break :blk pane.body.cur_col; const local = pane.body.cur_row; @@ -892,7 +892,13 @@ fn lookSpanIn(p: *Pardes, pane: *Pane, from: LookFrom, delta: i32, budget: *usiz if (grain == .whole) break :span wholeRowSpan(ln); if (pane.file) |f| if (@as(usize, @intCast(r)) < f.location_rows.len) { const end = f.location_rows[@intCast(r)].location_end; - if (end > 0) break :span @as(?Span, .{ .start = 0, .end = end }); + if (end > 0) { + const start_byte = if (f.output != null and std.meta.eql(f.output.?.from, panes.Output.Origin{ .query = .callstack })) + @import("locations.zig").treePrefix(ln).end + else + 0; + break :span @as(?Span, .{ .start = start_byte, .end = end }); + } }; break :span lineSpan(p, ln, dir, &realbuf); } orelse continue; @@ -1057,6 +1063,7 @@ pub fn focusPaneLine(p: *Pardes, id: usize, at: Spot, landing: enum { center, ke if (id >= MAX_PANES) return; const pane = p.panes[id] orelse return; p.active = id; + if (pane.collapsed) layout.toggleCollapse(p, id); pane.body.normal.clear(); if (pane.hasPdf()) { if (landing == .keep) return; @@ -2677,7 +2684,7 @@ test "Incl's directories find a name found nowhere else, too; bare Incl l try std.testing.expectEqual(@as(usize, 0), p.incl.items.len); } -test "n in a command pane walks its own file:line places, whoever walked last" { +test "LookNext in a command pane walks its own file:line places, whoever walked last" { if (!platform_has_fs) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -2706,12 +2713,12 @@ test "n in a command pane walks its own file:line places, whoever walked last" { cmd.focus = .body; cmd.body.mode = .normal; for ([_]u21{ 'g', 'g' }) |cp| p.update(.{ .key = .{ .cp = cp } }); - p.update(.{ .key = .{ .cp = 'n' } }); + exec.runBuiltin(p, .LookNext, p.active, "", null); try std.testing.expectEqual(dst, p.active); const first = cmd.look_at orelse return error.NoSpot; const lines = try edit.paneCursorLines(p, &cmd.body); try std.testing.expect(std.mem.startsWith(u8, lines[@intCast(first.row)][@intCast(first.col0)..], "x.c:3:1")); - p.update(.{ .key = .{ .cp = 'n' } }); + exec.runBuiltin(p, .LookNext, p.active, "", null); try std.testing.expectEqual(dst, p.active); const second = cmd.look_at orelse return error.NoSpot; try std.testing.expect(std.mem.startsWith(u8, lines[@intCast(second.row)][@intCast(second.col0)..], "y.c:2:1")); diff --git a/src/lsp/lsp.zig b/src/lsp/lsp.zig index 8dc4da4f..96d42bbd 100644 --- a/src/lsp/lsp.zig +++ b/src/lsp/lsp.zig @@ -16,6 +16,7 @@ pub const Kind = enum { format, select_refs, completion, + callstack, incoming_calls, outgoing_calls, supertypes, @@ -24,7 +25,14 @@ pub const Kind = enum { explain, }; +pub const callstack_match = "@callstack-match "; +pub const CallstackCorners = enum { rounded, square }; +pub const callstack_default_depth: u8 = 8; +pub const callstack_max_depth: u8 = 64; + pub const Req = struct { + callstack_depth: u8 = callstack_default_depth, + callstack_corners: CallstackCorners = .rounded, kind: Kind, path: []const u8, source: [:0]const u8, @@ -46,7 +54,7 @@ pub const Doc = struct { path: []const u8, source: [:0]const u8 }; /// file of the server's language is synced before it is asked. pub fn reachesOtherFiles(kind: Kind) bool { return switch (kind) { - .rename, .references, .implementation, .workspace_symbols, .incoming_calls, .outgoing_calls, .supertypes, .subtypes => true, + .rename, .references, .implementation, .workspace_symbols, .callstack, .incoming_calls, .outgoing_calls, .supertypes, .subtypes => true, else => false, }; } diff --git a/src/lsp/lsp_client.zig b/src/lsp/lsp_client.zig index 561195fe..54bbaa79 100644 --- a/src/lsp/lsp_client.zig +++ b/src/lsp/lsp_client.zig @@ -521,7 +521,8 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io }; const pos = posOf(req.source, req.offset, c.caps.enc); - var cx: Cx = .{ .arena = arena, .base = req.root, .cur_path = req.path, .cur_src = req.source, .out = out }; + var cx: Cx = .{ .arena = arena, .base = req.root, .cur_path = req.path, .cur_src = req.source, .out = out, .relative_parents = req.kind == .callstack, .callstack_corners = req.callstack_corners }; + for (req.others) |doc| try cx.files.append(arena, .{ .path = doc.path, .text = doc.source }); tr.note("server {s} (pid {d}), root {s}, {s} columns", .{ @tagName(c.state), c.pid, c.root, @tagName(c.caps.enc), }); @@ -642,6 +643,7 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io n += 1; } }, + .callstack => try callstack(c, si, arena, &cx, uri.items, pos, deadline, tr, req.callstack_depth), .incoming_calls => try hierarchy(c, si, arena, &cx, uri.items, pos, deadline, .incoming, tr), .outgoing_calls => try hierarchy(c, si, arena, &cx, uri.items, pos, deadline, .outgoing, tr), .supertypes => try hierarchy(c, si, arena, &cx, uri.items, pos, deadline, .supers, tr), @@ -869,6 +871,184 @@ fn sortEdits(edits: []PutEdit) void { }.lt); } +/// A bounded static hierarchy. Reuse the prepared item verbatim (including +/// server data), and retain every call-site range rather than just a declaration. +fn hierarchyResult(c: *Conn, arena: std.mem.Allocator, item: std.json.Value, method: []const u8, deadline: i64) Err!?std.json.Value { + if (jsonDepth(item, 0) > 96) return null; + var body: std.ArrayList(u8) = .empty; + try app(&body, arena, "\"item\":"); + try app(&body, arena, std.json.Stringify.valueAlloc(arena, item, .{}) catch return error.OutOfMemory); + return call(c, arena, method, body.items, deadline); +} + +const CallTree = struct { + const Site = struct { range: std.json.Value, focus: bool }; + const Node = struct { + item: std.json.Value, + ranges: std.ArrayList(Site) = .empty, + children: std.ArrayList(usize) = .empty, + cycle: bool = false, + }; + nodes: std.ArrayList(Node) = .empty, + roots: std.ArrayList(usize) = .empty, + path: [lsp.callstack_max_depth]std.json.Value = undefined, + depth_limit: usize = lsp.callstack_default_depth, + visited: usize = 0, + limited: bool = false, + siblings: [lsp.callstack_max_depth]bool = @splat(false), + rendered: usize = 0, + + /// Incoming paths arrive nearest-first. Insert them outermost-first, + /// sharing common caller prefixes and retaining all their call sites. + fn addPath(tree: *CallTree, arena: std.mem.Allocator, path: []const std.json.Value, cycle: bool) Err!void { + var parent: ?usize = null; + var at = path.len; + while (at > 0) { + at -= 1; + const entry = path[at]; + const item = get(entry, "from").?; + const children = if (parent) |id| tree.nodes.items[id].children.items else tree.roots.items; + const found = for (children) |id| { + if (sameCall(tree.nodes.items[id].item, item)) break id; + } else null; + const id = found orelse blk: { + const id = tree.nodes.items.len; + try tree.nodes.append(arena, .{ .item = item }); + if (parent) |pid| { + try tree.nodes.items[pid].children.append(arena, id); + } else try tree.roots.append(arena, id); + break :blk id; + }; + const node = &tree.nodes.items[id]; + node.cycle = node.cycle or (cycle and at == 0); + for (items(get(entry, "fromRanges"))) |range| { + const parsed = rangeOf(range) orelse continue; + for (node.ranges.items) |*other| { + if (std.meta.eql(parsed, rangeOf(other.range).?)) { + other.focus = other.focus or at == 0; + break; + } + } else try node.ranges.append(arena, .{ .range = range, .focus = at == 0 }); + } + parent = id; + } + } +}; + +fn sameCall(a: std.json.Value, b: std.json.Value) bool { + const au = str(get(a, "uri")) orelse return false; + const bu = str(get(b, "uri")) orelse return false; + const ar = rangeOf(get(a, "selectionRange") orelse get(a, "range")) orelse return false; + const br = rangeOf(get(b, "selectionRange") orelse get(b, "range")) orelse return false; + return std.mem.eql(u8, au, bu) and std.meta.eql(ar, br); +} + +fn callPrefix(out: *std.Io.Writer, tree: *const CallTree, depth: usize) Err!void { + for (tree.siblings[0..depth]) |more| try out.writeAll(if (more) "│ " else " "); +} + +fn validCaller(entry: std.json.Value) bool { + const from = get(entry, "from") orelse return false; + const uri = str(get(from, "uri")) orelse return false; + return std.mem.startsWith(u8, uri, "file:") and + rangeOf(get(from, "selectionRange") orelse get(from, "range")) != null; +} + +fn callstack(c: *Conn, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, tr: *Trace, max_depth: u8) Err!void { + if (!c.caps.call_hier) return lsp.none(cx.out, "{s} does not answer call hierarchy (no callHierarchyProvider)", .{specs[si].name}); + const b = try atPos(arena, uri, pos); + const prepared = (try call(c, arena, "textDocument/prepareCallHierarchy", b.items, deadline)) orelse return; + if (items(prepared).len == 0) return lsp.none(cx.out, "no function at this position", .{}); + for (items(prepared)) |item| { + var tree: CallTree = .{ .depth_limit = std.math.clamp(max_depth, 1, lsp.callstack_max_depth) }; + const incoming = try hierarchyResult(c, arena, item, "callHierarchy/incomingCalls", deadline); + const count = try collectCallers(c, arena, item, incoming, deadline, &tree, 0); + if (count == 0) try cx.out.writeAll("No callers reported\n"); + try renderCallers(cx, c.caps.enc, &tree, tree.roots.items, 0); + if (tree.limited) try cx.out.writeAll("… continue from a function above with Callstack\n"); + tr.note("callstack: {d} callers", .{tree.rendered}); + } +} + +fn collectCallers(c: *Conn, arena: std.mem.Allocator, focus: std.json.Value, incoming: ?std.json.Value, deadline: i64, tree: *CallTree, depth: usize) Err!usize { + var count: usize = 0; + for (items(incoming)) |entry| { + if (tree.visited >= 64) { + tree.limited = true; + break; + } + if (!validCaller(entry)) continue; + const from = get(entry, "from").?; + const cycle = sameCall(focus, from) or for (tree.path[0..depth]) |ancestor| { + if (sameCall(get(ancestor, "from").?, from)) break true; + } else false; + tree.path[depth] = entry; + tree.visited += 1; + count += 1; + var children: usize = 0; + if (!cycle) { + if (depth + 1 == tree.depth_limit or tree.visited >= 64) { + tree.limited = true; + } else { + const ancestors = try hierarchyResult(c, arena, from, "callHierarchy/incomingCalls", deadline); + children = try collectCallers(c, arena, focus, ancestors, deadline, tree, depth + 1); + } + } + if (children == 0) try tree.addPath(arena, tree.path[0 .. depth + 1], cycle); + } + return count; +} + +fn callerLess(tree: *const CallTree, a: usize, b: usize) bool { + const left = tree.nodes.items[a].item; + const right = tree.nodes.items[b].item; + const uri_order = std.mem.order(u8, str(get(left, "uri")).?, str(get(right, "uri")).?); + if (uri_order != .eq) return uri_order == .lt; + return callRangeLess({}, get(left, "selectionRange") orelse get(left, "range").?, get(right, "selectionRange") orelse get(right, "range").?); +} + +fn callRangeLess(_: void, a: std.json.Value, b: std.json.Value) bool { + const left = rangeOf(a).?; + const right = rangeOf(b).?; + return left.sl < right.sl or (left.sl == right.sl and left.sc < right.sc); +} + +fn renderCallers(cx: *Cx, enc: Enc, tree: *CallTree, children: []usize, depth: usize) Err!void { + std.mem.sort(usize, children, @as(*const CallTree, tree), callerLess); + for (children, 0..) |id, index| { + if (tree.rendered >= 64) { + tree.limited = true; + return; + } + const node = &tree.nodes.items[id]; + const item = node.item; + const uri = str(get(item, "uri")).?; + const more = index + 1 < children.len; + try callPrefix(cx.out, tree, depth); + const has_children = node.children.items.len > 0 or node.ranges.items.len > 0; + const rounded = cx.callstack_corners == .rounded; + try cx.out.writeAll(if (more) "├" else if (rounded) "╰" else "└"); + try cx.out.writeAll(if (has_children) "──┬ " else "─── "); + const name = flat(cx.arena, str(get(item, "name")) orelse "(unnamed)"); + const label = if (node.cycle) try std.fmt.allocPrint(cx.arena, "{s} ↻ recursion", .{name}) else name; + try emitRange(cx, enc, uri, get(item, "selectionRange") orelse get(item, "range"), label); + tree.rendered += 1; + tree.siblings[depth] = more; + std.mem.sort(CallTree.Site, node.ranges.items, {}, struct { + fn less(_: void, a: CallTree.Site, b: CallTree.Site) bool { + return callRangeLess({}, a.range, b.range); + } + }.less); + for (node.ranges.items, 0..) |site, site_index| { + if (site.focus) try cx.out.writeAll(lsp.callstack_match); + try callPrefix(cx.out, tree, depth + 1); + try cx.out.writeAll(if (node.children.items.len > 0 or site_index + 1 < node.ranges.items.len) "├─ " else if (rounded) "╰─ " else "└─ "); + try emitRange(cx, enc, uri, site.range, ""); + } + try renderCallers(cx, enc, tree, node.children.items, depth + 1); + } +} + const Hier = enum { incoming, outgoing, supers, subs }; /// The two-step hierarchy kinds: prepare at the cursor, then follow every @@ -894,17 +1074,7 @@ fn hierarchy(c: *Conn, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []cons const b = try atPos(arena, uri, pos); const prepared = (try call(c, arena, prepare, b.items, deadline)) orelse return; for (items(prepared)) |item| { - // the item goes back VERBATIM — servers hide resolution state in - // `data` and a re-serialized subset would come back unresolvable. - // But only if it can round-trip: Stringify panics past its nesting - // limit, so a server that nests a bomb in `data` gets no rows for - // that item, not a dead editor. - if (jsonDepth(item, 0) > 96) continue; - var body: std.ArrayList(u8) = .empty; - try app(&body, arena, "\"item\":"); - const item_json = std.json.Stringify.valueAlloc(arena, item, .{}) catch return error.OutOfMemory; - try app(&body, arena, item_json); - const result = (try call(c, arena, follow, body.items, deadline)) orelse return; + const result = (try hierarchyResult(c, arena, item, follow, deadline)) orelse return; for (items(result)) |entry| switch (h) { .incoming => { // one row per CALL SITE, under the caller's name — that is @@ -965,6 +1135,8 @@ const Cx = struct { cur_src: []const u8, out: *std.Io.Writer, rows: usize = 0, + relative_parents: bool = false, + callstack_corners: lsp.CallstackCorners = .rounded, files: std.ArrayList(struct { path: []const u8, text: []const u8 }) = .empty, fn text(cx: *Cx, path: []const u8) ?[]const u8 { @@ -1018,7 +1190,10 @@ fn emitRange(cx: *Cx, enc: Enc, uri: []const u8, range: ?std.json.Value, note: [ const lntext: []const u8 = if (src) |t| t[@min(bol, t.len)..@min(eol, t.len)] else ""; const col = colBytes(lntext, r.sc, enc); - const shown = lsp.rel(cx.base, path); + const shown = if (cx.relative_parents) blk: { + const relative = std.fs.path.relativePosix(cx.arena, "/", cx.base, path) catch break :blk path; + break :blk if (relative.len < path.len) relative else path; + } else lsp.rel(cx.base, path); // A same-line exclusive end byte offset is also the displayed inclusive // one-based column. Multi-line ranges display only their starting address. const end_col = if (r.el == r.sl and r.ec > r.sc) colBytes(lntext, r.ec, enc) else col; @@ -2131,6 +2306,68 @@ fn coord(v: ?std.json.Value) ?u32 { // ----------------------------------------------------------------- tests +test "caller trees reverse incoming paths and merge shared callers and sites" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const fixture = try std.json.parseFromSliceLeaky(std.json.Value, arena, "[{\"from\":{\"name\":\"left\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":3,\"character\":0},\"end\":{\"line\":3,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":3,\"character\":0},\"end\":{\"line\":3,\"character\":4}}]},{\"from\":{\"name\":\"right\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":4,\"character\":0},\"end\":{\"line\":4,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":4,\"character\":0},\"end\":{\"line\":4,\"character\":4}}]},{\"from\":{\"name\":\"page\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":1,\"character\":0},\"end\":{\"line\":1,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":1,\"character\":0},\"end\":{\"line\":1,\"character\":4}}]},{\"from\":{\"name\":\"page\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":1,\"character\":0},\"end\":{\"line\":1,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":2,\"character\":0},\"end\":{\"line\":2,\"character\":4}}]},{\"from\":{\"name\":\"main\",\"uri\":\"file:///test.c\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":4}}},\"fromRanges\":[{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":4}}]}]", .{}); + const entries = items(fixture); + var tree: CallTree = .{}; + try tree.addPath(arena, &.{ entries[0], entries[2], entries[4] }, false); + try tree.addPath(arena, &.{ entries[1], entries[3], entries[4] }, false); + try std.testing.expectEqual(@as(usize, 1), tree.roots.items.len); + try std.testing.expectEqual(@as(usize, 4), tree.nodes.items.len); + const root = tree.nodes.items[tree.roots.items[0]]; + try std.testing.expectEqualStrings("main", str(get(root.item, "name")).?); + try std.testing.expectEqual(@as(usize, 1), root.ranges.items.len); + const page = tree.nodes.items[root.children.items[0]]; + try std.testing.expectEqual(@as(usize, 2), page.children.items.len); + try std.testing.expectEqual(@as(usize, 2), page.ranges.items.len); + try std.testing.expect(!root.ranges.items[0].focus); + for (page.ranges.items) |site| try std.testing.expect(!site.focus); + for (page.children.items) |id| try std.testing.expect(tree.nodes.items[id].ranges.items[0].focus); + var out: std.Io.Writer.Allocating = .init(arena); + var cx: Cx = .{ .arena = arena, .base = "/", .cur_path = "/test.c", .cur_src = "main_call();\npage_left();\npage_right();\nleft_call();\nright_call();\n", .out = &out.writer }; + try renderCallers(&cx, .utf8, &tree, tree.roots.items, 0); + const text = out.written(); + try std.testing.expectEqual(@as(usize, 2), std.mem.count(u8, text, lsp.callstack_match)); + const main_at = std.mem.indexOf(u8, text, " main\n").?; + const page_at = std.mem.indexOf(u8, text, " page\n").?; + const left_at = std.mem.indexOf(u8, text, " left\n").?; + const right_at = std.mem.indexOf(u8, text, " right\n").?; + try std.testing.expect(main_at < page_at and page_at < left_at and left_at < right_at); + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, text, "main_call();")); + try std.testing.expect(std.mem.indexOf(u8, text, "page_left();").? < std.mem.indexOf(u8, text, "page_right();").?); + try std.testing.expect(std.mem.indexOf(u8, text, "├──┬ test.c:4:") != null); + try std.testing.expect(std.mem.indexOf(u8, text, "╰──┬ test.c:1:") != null); + cx.callstack_corners = .square; + tree.rendered = 0; + const square_start = out.written().len; + try renderCallers(&cx, .utf8, &tree, tree.roots.items, 0); + const square = out.written()[square_start..]; + try std.testing.expect(std.mem.indexOf(u8, square, "├──┬ test.c:4:") != null); + try std.testing.expect(std.mem.indexOf(u8, square, "└──┬ test.c:1:") != null); + try std.testing.expect(std.mem.indexOf(u8, square, "╰") == null); + try std.testing.expect(std.mem.indexOf(u8, square, "╮") == null); + var recursive: CallTree = .{}; + try recursive.addPath(arena, &.{ entries[0], entries[0] }, true); + try std.testing.expect(!recursive.nodes.items[recursive.roots.items[0]].cycle); + try std.testing.expect(recursive.nodes.items[1].cycle); +} + +test "callstack cross-crate paths remain resolvable without absolute path clutter" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const range = try std.json.parseFromSliceLeaky(std.json.Value, arena, + \\{"start":{"line":1,"character":3},"end":{"line":1,"character":6}} + , .{}); + var out: std.Io.Writer.Allocating = .init(arena); + var cx: Cx = .{ .arena = arena, .base = "/workspace/merkle-tree/src", .cur_path = "", .cur_src = "", .out = &out.writer, .relative_parents = true }; + try emitRange(&cx, .utf8, "file:///workspace/entry/src/entry.rs", range, "fn run()"); + try std.testing.expectEqualStrings("../../entry/src/entry.rs:2:4-6 fn run()\n", out.written()); +} + test "LSP client rename and format propagate incomplete edit encoding" { const gpa = std.testing.allocator; const uri = "file:///file.c"; diff --git a/src/modal.zig b/src/modal.zig index 548524ae..50e0ddf4 100644 --- a/src/modal.zig +++ b/src/modal.zig @@ -36,6 +36,7 @@ pub const Normal = struct { goto_type_definition, goto_implementation, goto_references, + goto_callstack, view_top, view_center, @@ -320,7 +321,7 @@ pub const Normal = struct { undo, redo, }; - pub const Lsp = enum { definition, declaration, type_definition, implementation, references, format }; + pub const Lsp = enum { definition, declaration, type_definition, implementation, references, callstack, format }; pub const Counted = struct { count: u32, @@ -471,6 +472,7 @@ pub const Normal = struct { if (key.has(.goto_type_definition)) return resultAction(.{ .lsp = .type_definition }); if (key.has(.goto_implementation)) return resultAction(.{ .lsp = .implementation }); if (key.has(.goto_references)) return resultAction(.{ .lsp = .references }); + if (key.has(.goto_callstack)) return resultAction(.{ .lsp = .callstack }); return .ignored; }, .view => { diff --git a/src/mouse.zig b/src/mouse.zig index 733479dd..536a4fdb 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -100,7 +100,7 @@ pub const HeaderSweep = struct { /// as a pane tag's sweep stays on its tag. fn headerPoint(p: *Pardes, column: ?usize, mcol: u16, mrow: u16, clamp: bool) ?struct { t: *panes.Text, text: []const u8, line: u16, at: usize } { const t = if (column) |c| &p.col_tags[c] else &p.global_tag; - const x = if (column) |c| p.col_x[c] + TAG_TEXT_INSET else 0; + const x = if (column) |c| p.col_x[c] + TAG_TEXT_INSET else TAG_TEXT_INSET; const focused = p.header_focus and p.header_column == column; const text = edit.flatSurface(p, t) catch return null; const base = if (column != null) p.topBarHeight() else 0; @@ -588,7 +588,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { p.header_drag = false; return; }; - const x = if (p.header_column) |c| p.col_x[c] + TAG_TEXT_INSET else 0; + const x = if (p.header_column) |c| p.col_x[c] + TAG_TEXT_INSET else TAG_TEXT_INSET; const text = edit.flatSurface(p, t) catch return; // `row` is the header's row on screen, `line` the line of its text // shown there. @@ -612,7 +612,8 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { pane.closePrompt(); }; var column: ?usize = null; - var x: u16 = 0; + var x: u16 = TAG_TEXT_INSET; + if (mcol < x) return; if (mrow >= p.topBarHeight()) { for (0..p.ncol) |c| if (mcol >= p.col_x[c] and mcol < p.col_x[c] + p.col_w[c]) { column = c; @@ -1047,7 +1048,7 @@ fn gestureRange(p: *Pardes, id: usize, text: []const u8, on_tag: bool, operand: const top = lead[0] - @as(i32, pane.tag_rows); if (top < 0) break :lead null; const w = pane.wrapAt(top); - const col = edit.paneByteAtDisplay(p, &pane.body, w.line, w.at, lead[1] - panes.File.gutterWidth(pane)); + const col = edit.paneByteAtDisplay(p, &pane.body, w.line, w.at, lead[1] - panes.File.gutterWidth(pane) - w.pad); break :lead .{ .row = @intCast(@max(0, w.line)), .col = @intCast(@max(0, col)), @@ -1154,7 +1155,7 @@ fn sweepPoint(p: *Pardes, pane: *panes.Pane, r: i32, c: i32) ?modal.Cursor { if (visible < 0) return null; const w = pane.wrapAt(visible); if (w.line < 0) return null; - const col = edit.paneByteAtDisplay(p, &pane.body, w.line, w.at, c - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0)); + const col = edit.paneByteAtDisplay(p, &pane.body, w.line, w.at, c - w.pad - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0)); return .{ .row = @intCast(w.line), .col = @intCast(@max(0, col)) }; } @@ -1268,7 +1269,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { &pane.body, w.line, w.at, - sl.c1 - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0), + sl.c1 - w.pad - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0), ); pane.body.cur_pinned = true; if (edit.clampFileCursor(&pane.body)) pane.ensureCursorVisible(); @@ -1312,7 +1313,14 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { pane.sel[b] = expanded else if (operand.text == null) pane.sel[b].state = .none; - if (s.button == config.look_button and clk.r0 >= pane.tag_rows and pane.body.mode != .tty) { + if (s.button == config.look_button and clk.r0 >= pane.tag_rows and pane.body.mode != .tty and operand.expanded != null) { + // This click chose a new word. An old keyboard anchor + // must not stretch to it; borrowed selections retain + // their original cursor and extent. + pane.body.vsel.active = false; + pane.body.msel.active = false; + pane.body.nsel = 0; + pane.body.select = false; pane.body.cur_row = operand.row; pane.body.cur_col = operand.col; if (edit.clampFileCursor(&pane.body)) pane.ensureCursorVisible(); @@ -1431,8 +1439,8 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { const w1 = pane.wrapAt(@max(0, sl.r1 - @as(i32, pane.tag_rows))); const row0 = w0.line; const row1 = w1.line; - const col0 = edit.paneByteAtDisplay(p, &pane.body, w0.line, w0.at, sl.c0 - pfx); - const col1 = edit.paneByteAtDisplay(p, &pane.body, w1.line, w1.at, sl.c1 - pfx); + const col0 = edit.paneByteAtDisplay(p, &pane.body, w0.line, w0.at, sl.c0 - pfx - w0.pad); + const col1 = edit.paneByteAtDisplay(p, &pane.body, w1.line, w1.at, sl.c1 - pfx - w1.pad); pane.body.cur_row = row1; pane.body.cur_col = col1; pane.body.cur_pinned = true; diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index e6e738a5..f6457b83 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -554,6 +554,7 @@ fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ? .font => config.Runtime.FontSpec.parse(arg) != null, // Bare, it says the width, as from a pane's exec. .tab => arg.len == 0 or (std.fmt.parseInt(u16, arg, 10) catch 0) -% 1 < 16, + .callstack_depth => arg.len == 0 or (std.fmt.parseInt(u8, arg, 10) catch 0) -% 1 < pardes.lsp.callstack_max_depth, else => probe: { var probe = p.settings; break :probe probe.apply(setting, if (arg.len > 0) arg else null); @@ -662,6 +663,7 @@ pub fn writeSettingsOf(p: *Pardes, s: *const config.Runtime, w: *std.Io.Writer) .motion => try w.print("{s} {s}\n", .{ word, @tagName(s.motion) }), .inactive_dim => try w.print("{s} {d}\n", .{ word, s.inactive_dim }), .grip_width => try w.print("{s} {d}\n", .{ word, s.grip_width }), + .callstack_depth => try w.print("{s} {d}\n", .{ word, s.callstack_depth }), .tab => try w.print("{s} {d}\n", .{ word, s.tab }), } } @@ -743,12 +745,13 @@ pub fn fillPager(p: *Pardes, serial: u32, held: *std.ArrayList(u8)) error{OutOfM f.pager_spans = page.spans; f.saved_revision = f.revision; // A diff paged (`git show`, difftui's patches): its hunks stacked in a - // +Diff (DiffLook hunks), the +Pager folded to its tag under it for - // Diff to bring back. The keyboard stays where it was, as a page's. + // +Diff (DiffLook hunks) in the +Pager's place, the +Pager closed. The + // keyboard stays where it was, as a page's. if (f.pager_diff and p.settings.diff_look == .hunks) { const keyboard = p.active; - if (panes.Output.openDiff(p, id, f.path, f.content)) |_| { - if (!pane.collapsed) pardes.layout.toggleCollapse(p, id); + if (panes.Output.openDiff(p, id, f.path, f.content)) |hid| { + // ponytail: the text is gone with it; Diff on the +Diff says no such file. + p.removePane(id, hid) catch {}; } else |_| {} if (p.panes[keyboard] != null) p.active = keyboard; } @@ -1452,6 +1455,8 @@ test "the root ctl reads the settings as a write takes them, and takes the sessi try testing.expectEqual(@as(u64, settings.len), call(p, .{ .tag = 1, .op = .getattr, .node = root_ctl }).reply.attr.size); try testing.expect(std.mem.indexOf(u8, settings, "Verbose on\n") != null); try testing.expect(std.mem.indexOf(u8, settings, "LocationsConfig ") != null); + try testing.expect(std.mem.indexOf(u8, settings, "CallstackDepth 8\n") != null); + try testing.expectEqual(Status.ok, wr(p, root_ctl, "CallstackDepth").reply.status); // Settings only: nothing /status or the DumpConfig window says. try testing.expect(std.mem.indexOf(u8, settings, "Platform") == null); try testing.expect(std.mem.indexOf(u8, settings, "requested") == null); @@ -1494,7 +1499,6 @@ test "the root ctl reads the settings as a write takes them, and takes the sessi try testing.expectEqual(Status.ok, wr(p, root_ctl, "Verbose off").reply.status); } - test "a second lock is refused until the holder unlocks or closes, and binds nobody else" { const p = try withFile(testing.allocator, "one\ntwo\n"); defer p.deinit(); @@ -3920,7 +3924,7 @@ test "a closed file is found again: Recent and /recent list it closed, a look at try testing.expectEqual(Status.ok, wr(p, root_exec, "Recent\n").reply.status); const rows = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; const at = std.mem.indexOf(u8, rows.file.?.content, try std.fmt.bufPrint(&want, "{s}:3:", .{a})).?; - const row = rows.file.?.content[at .. std.mem.indexOfScalarPos(u8, rows.file.?.content, at, '\n').?]; + const row = rows.file.?.content[at..std.mem.indexOfScalarPos(u8, rows.file.?.content, at, '\n').?]; try testing.expect(std.mem.endsWith(u8, row, " (closed)")); try testing.expectEqual(Status.ok, wr(p, Node.of(rows.serial, .look), try std.fmt.bufPrint(&line, "{s}\n", .{row[0 .. row.len - " (closed)".len]})).reply.status); p.sync(); @@ -4159,11 +4163,11 @@ test "a remembered place is clamped to the file as it is now, its selection's tw _ = wr(p, root_exec, "Recent\n"); const rows = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; const at = std.mem.indexOf(u8, rows.file.?.content, "c.txt:").?; - const row = rows.file.?.content[at .. std.mem.indexOfScalarPos(u8, rows.file.?.content, at, '\n').?]; + const row = rows.file.?.content[at..std.mem.indexOfScalarPos(u8, rows.file.?.content, at, '\n').?]; // Both ends are in the row, a range. try testing.expect(std.mem.indexOfScalar(u8, row, '-') != null); var full: [4400]u8 = undefined; - const loc = try std.fmt.bufPrint(&full, "{s}/{s}\n", .{ dir, row[0 .. std.mem.indexOfScalar(u8, row, ' ').?] }); + const loc = try std.fmt.bufPrint(&full, "{s}/{s}\n", .{ dir, row[0..std.mem.indexOfScalar(u8, row, ' ').?] }); // A look at it opens the file, never a miss, clamped to its last line. try testing.expectEqual(Status.ok, wr(p, Node.of(rows.serial, .look), loc).reply.status); p.sync(); @@ -4350,7 +4354,7 @@ test "every word's /commands description is its own doc comment's first sentence undescribed += 1; continue; }; - const word = line[0 .. std.mem.indexOfScalar(u8, line, ' ').?]; + const word = line[0..std.mem.indexOfScalar(u8, line, ' ').?]; if (config.Runtime.find(word)) |setting| { try testing.expect(std.mem.endsWith(u8, line, setting.doc)); continue; diff --git a/src/normal.zig b/src/normal.zig index fad1836b..77feb7cf 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -905,10 +905,11 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void .undo => return edit.doUndo(p, t), .redo => return edit.doRedo(p, t), }, - // gd and gr are the Def and Refs a tag shows, run as a click runs them. + // Language shortcuts run the same builtins as tags and leader commands. .lsp => |request| return switch (request) { .definition => exec.runBuiltin(p, .Def, p.active, "", null), .references => exec.runBuiltin(p, .Refs, p.active, "", null), + .callstack => exec.runBuiltin(p, .Callstack, p.active, "", null), .declaration => p.lspRequest(p.active, .declaration, ""), .type_definition => p.lspRequest(p.active, .type_definition, ""), .implementation => p.lspRequest(p.active, .implementation, ""), diff --git a/src/panes.zig b/src/panes.zig index 89362996..ba1dedb5 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -219,6 +219,7 @@ pub const Pane = struct { // Visible rows map to source lines and raw/display column origins. wrap_line: [limits.wrap_rows]i32 = undefined, wrap_col: [limits.wrap_rows]i32 = undefined, + wrap_pad: [limits.wrap_rows]u16 = @splat(0), wrap_n: u16 = 0, /// A row map also exists for sticky headers when soft wrapping is off. body_wrapped: bool = false, @@ -493,15 +494,15 @@ pub const Pane = struct { return pane.surfRow(terminal.gridOffset(pane)); } - pub fn wrapAt(pane: *Pane, vr: i32) struct { line: i32, at: i32 } { + pub fn wrapAt(pane: *Pane, vr: i32) struct { line: i32, at: i32, pad: i32 = 0 } { if (pane.wrap_n > 0 and vr >= 0 and vr < @as(i32, pane.wrap_n)) - return .{ .line = pane.wrap_line[@intCast(vr)], .at = pane.wrap_col[@intCast(vr)] }; + return .{ .line = pane.wrap_line[@intCast(vr)], .at = pane.wrap_col[@intCast(vr)], .pad = pane.wrap_pad[@intCast(vr)] }; // unwrapped: rows ARE lines, and the byte column a row starts at is the // horizontal scroll (always 0 on a terminal, which never has one) return .{ .line = pane.scroll() + vr, .at = pane.hscroll }; } - pub fn wrapRow(pane: *Pane, line: i32, col: i32) struct { row: i32, at: i32 } { + pub fn wrapRow(pane: *Pane, line: i32, col: i32) struct { row: i32, at: i32, pad: i32 = 0 } { if (pane.wrap_n == 0) return .{ .row = line - pane.scroll(), .at = pane.hscroll }; var i: u16 = 0; while (i < pane.wrap_n) : (i += 1) { @@ -509,7 +510,7 @@ pub const Pane = struct { // the LAST row of a line owns every column past its start, so a // cursor parked on the trailing newline still has somewhere to draw if (i + 1 < pane.wrap_n and pane.wrap_line[i + 1] == line and col >= pane.wrap_col[i + 1]) continue; - return .{ .row = @intCast(i), .at = pane.wrap_col[i] }; + return .{ .row = @intCast(i), .at = pane.wrap_col[i], .pad = pane.wrap_pad[i] }; } return .{ .row = -1, .at = 0 }; } diff --git a/src/pardes.zig b/src/pardes.zig index 29192c33..5f330712 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -220,7 +220,6 @@ pub const Turn = struct { while (t.lsp_answers == answers) t.settled.wait(t.io.?, &t.mutex) catch return; } - pub fn awaitRestored(t: *Turn, restores: u64) void { while (t.restores == restores) t.settled.wait(t.io.?, &t.mutex) catch return; } @@ -294,7 +293,7 @@ pub const MAX_JUMPS = 64; pub const TOPBAR_H: u16 = 1; pub const COLBAR_H: u16 = 1; pub const BOX_H: u16 = 1; -pub const TAG_GAP: u16 = 1; +pub const TAG_GAP: u16 = 0; pub const TAG_TEXT_INSET: u16 = config.GUTTER + TAG_GAP; pub fn taglineBandOffset(row: u16, canvas_h: f32, cell_h: u32, tagline_h: u32) u32 { @@ -655,25 +654,25 @@ test "topbar hover highlights exactly the executable word" { defer frame.deinit(); _ = try p.render(frame.allocator()); - p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = 1, .row = 0 } }); + p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = TAG_TEXT_INSET + 1, .row = 0 } }); _ = frame.reset(.retain_capacity); const hovered = try p.render(frame.allocator()); for (0.."Newcol".len) |col| { - const cell = hovered.at(@intCast(col), 0); + const cell = hovered.at(TAG_TEXT_INSET + @as(u16, @intCast(col)), 0); try std.testing.expectEqual(Color{ .rgb = p.theme().sel_bg }, cell.style.bg); try std.testing.expectEqual(Color{ .rgb = p.theme().sel_fg }, cell.style.fg); } - try std.testing.expectEqual(Color{ .rgb = p.chromeTheme().tag_bg }, hovered.at(6, 0).style.bg); + try std.testing.expectEqual(Color{ .rgb = p.chromeTheme().tag_bg }, hovered.at(TAG_TEXT_INSET + 6, 0).style.bg); - p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = 6, .row = 0 } }); + p.update(.{ .mouse = .{ .button = .none, .kind = .motion, .col = TAG_TEXT_INSET + 6, .row = 0 } }); _ = frame.reset(.retain_capacity); const whitespace = try p.render(frame.allocator()); - try std.testing.expectEqual(Color{ .rgb = p.chromeTheme().tag_bg }, whitespace.at(1, 0).style.bg); + try std.testing.expectEqual(Color{ .rgb = p.chromeTheme().tag_bg }, whitespace.at(TAG_TEXT_INSET + 1, 0).style.bg); p.update(.pointer_leave); _ = frame.reset(.retain_capacity); const left = try p.render(frame.allocator()); - try std.testing.expectEqual(Color{ .rgb = p.chromeTheme().tag_bg }, left.at(1, 0).style.bg); + try std.testing.expectEqual(Color{ .rgb = p.chromeTheme().tag_bg }, left.at(TAG_TEXT_INSET + 1, 0).style.bg); } test "pane-tag Exec prefers Tty and argument builtins before shell fallback" { @@ -1216,7 +1215,7 @@ test "Def and Refs are a speaking file's tag words; gd, gr and a 2-1 chord all r const f = &pane.file.?; p.gpa.free(f.path); f.path = try p.gpa.dupe(u8, "/tmp/x.zig"); - try std.testing.expect(std.mem.endsWith(u8, tagline.curTail(pane), " Def Refs")); + try std.testing.expect(std.mem.endsWith(u8, tagline.curTail(pane), " Def Refs Del")); p.sync(); while (p.nextEffect()) |_| {} const Asked = struct { @@ -1241,6 +1240,9 @@ test "Def and Refs are a speaking file's tag words; gd, gr and a 2-1 chord all r p.update(.{ .key = .{ .cp = 'g' } }); p.update(.{ .key = .{ .cp = 'r' } }); try std.testing.expectEqual(@as(u32, 8), try Asked.one(p, .references)); + p.update(.{ .key = .{ .cp = 'g' } }); + p.update(.{ .key = .{ .cp = 'c' } }); + try std.testing.expectEqual(@as(u32, 8), try Asked.one(p, .callstack)); const r = p.rects[0]; const x0 = r.x + config.GUTTER + panes.File.gutterWidth(pane); @@ -1525,7 +1527,6 @@ test "unknown Exec from a document runs as a command pane in its directory, type try std.testing.expect(spawned); } - const FakeTtyQuery = struct { taken: [MAX_PANES]bool = @splat(false), asked: usize = 0, @@ -2009,7 +2010,6 @@ test "a command pane shows how its command ended, and the next command there run try std.testing.expectEqual(@as(?usize, null), exec.execute(p, 1, long)); } - test "image dump restores source bytes renderer choices and exact custom tail" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); @@ -2062,7 +2062,6 @@ test "image dump restores source bytes renderer choices and exact custom tail" { try std.testing.expectEqualStrings(" Keep Del", redump.panes[0].tag_tail.?); } - test "a Look on a directory does not type ls into an occupied terminal" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .cols = 100, .rows = 30 }); @@ -3374,9 +3373,9 @@ test "editable workspace and column tags are typed into and persist" { p.acknowledgePanelPresentation(&.{}); try std.testing.expectEqual(TOPBAR_H + COLBAR_H, p.rects[0].y); // a sweep over a header is its selection, the caret where it ended - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = 0, .row = 0 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = 6, .row = 0 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = 6, .row = 0 } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = TAG_TEXT_INSET, .row = 0 } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = TAG_TEXT_INSET + 6, .row = 0 } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = TAG_TEXT_INSET + 6, .row = 0 } }); try std.testing.expect(p.global_tag.vsel.active and p.global_tag.vsel.col == 0 and p.global_tag.cur_col == 6); p.update(.{ .key = .{ .cp = 'H', .text = " Help" } }); try std.testing.expect(std.mem.startsWith(u8, p.global_tag.own.?, "Newcol Help Joincol")); @@ -6966,6 +6965,7 @@ pub const Pardes = struct { .definition => "Def", .references => "Refs", .explain => "Lspwhy", + .callstack => "Callstack", .incoming_calls => "Callers", .outgoing_calls => "Callees", .document_symbols => "Symbols", @@ -7081,6 +7081,18 @@ pub const Pardes = struct { // (a multi-file Rename's preview, Lspinfo's +Lsp), made or filled // again, not the pane it was asked from. p.fs.lsp_result = if (p.next_serial != serial_before) p.next_serial else p.fs.refilled; + if (w.kind == .callstack) { + for (p.panes, 0..) |slot, result_id| if (slot) |result_pane| { + if (result_pane.serial != p.fs.lsp_result) continue; + if (p.next_serial != serial_before) { + const report_rows = std.mem.count(u8, result_pane.file.?.content, "\n"); + const wanted: u16 = @intCast(@min(p.screen_h, report_rows + result_pane.tag_rows)); + layout.givePaneRows(p, result_id, wanted, w.pane); + } + look.focusPaneLine(p, result_id, .{ .line = 1, .col = 1 }, .keep); + break; + }; + } if (w.kind == .rename) { var said_buf: [128]u8 = undefined; // Rows that only name a file the server left alone (lsp_client @@ -7624,7 +7636,6 @@ pub const Pardes = struct { return if (frames) |n| p.stepped_ns + n * animation.frame_ns else null; } - /// A render-time animation is moving (a pane's lift): it is sampled at /// each frame's own `now`, so while it moves the shell draws every loop /// and its present (vsync) paces it, at the display's rate. `nextWake` @@ -8514,6 +8525,44 @@ test "the jump list never holds two entries in a row the same, when the one betw try std.testing.expectEqual(@as(u32, 150), p.jumps[1].line); } +test "Callstack always opens and focuses its own pane, reusing it for another symbol" { + if (!lsp.supports.contains(.callstack)) return; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + _ = try p.setTestFile("fn work() {}\n"); + const source = p.panes[0].?; + p.lspRequest(0, .callstack, ""); + const first = p.lsp_wait orelse return error.NoRequest; + p.lspResponse(first.id, "└──┬ /test.txt:1:4-7 work\n@callstack-match └─ /test.txt:1:4-7 fn work() {}\n"); + const report = p.panes[p.active].?; + try std.testing.expect(report != source); + try std.testing.expect(std.mem.endsWith(u8, report.file.?.path, "/+Callstack")); + try std.testing.expectEqual(@as(i32, 0), source.body.cur_row); + const stale_selection = std.mem.indexOfScalar(u8, report.file.?.content, '\n').? + 1; + report.body.setRange(report.file.?.content, 0, .{ .anchor = stale_selection, .head = stale_selection + 6 }, true); + layout.toggleCollapse(p, 0); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const surface = try p.render(frame.allocator()); + p.acknowledgePanelPresentation(&.{}); + const r = p.rects[p.active]; + const row = r.y + report.tag_rows; + const col = r.x + config.GUTTER + panes.File.gutterWidth(report) + 7; + try std.testing.expectEqual(.off, surface.at(col, row).style.ul); + p.update(.{ .mouse = .{ .button = .right, .kind = .press, .row = row, .col = col } }); + p.update(.{ .mouse = .{ .button = .right, .kind = .release, .row = row, .col = col } }); + try std.testing.expect(!source.collapsed); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expect(!report.body.vsel.active); + try std.testing.expectEqual(@as(usize, 0), report.body.nsel); + const serial = report.serial; + p.lspRequest(0, .callstack, ""); + const second = p.lsp_wait orelse return error.NoRequest; + p.lspResponse(second.id, "No callers reported\n"); + try std.testing.expectEqual(serial, p.panes[p.active].?.serial); + try std.testing.expectEqualStrings("No callers reported\n", p.panes[p.active].?.file.?.content); +} + test "Callers with one answer jumps to it and says where, in a msg" { if (!lsp.supports.contains(.incoming_calls)) return; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); diff --git a/src/syntax.zig b/src/syntax.zig index 89d96239..b2f5ea99 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -414,7 +414,6 @@ pub fn walkNodes(tree_ptr: *anyopaque, walk: NodeWalk, from: usize, to: usize, a return 1; } - /// helix's textobjects, which its `]f`, `mif` and kin select: the name a /// query's captures begin with (`function.around`, `test.inside`). pub const Object = @import("modal.zig").Normal.Object; @@ -940,13 +939,10 @@ pub fn highlightLocationRows(gpa: std.mem.Allocator, content: []const u8, rows: } fn codeAfterLocation(line: []const u8) ?struct { path: []const u8, at: usize, text: []const u8 } { - const token_end = std.mem.indexOfAny(u8, line, " \t") orelse return null; - if (token_end == 0) return null; - const token = line[0..token_end]; - const target = look.parsePathLine(token); - if (target.end != token.len) return null; + const trimmed = std.mem.trimStart(u8, line, " \t"); + const target = @import("locations.zig").parseRaw(trimmed); if (target.at.line == 0) return null; - const at = token_end + 1; + const at = line.len - trimmed.len + target.code_start; if (at >= line.len) return null; return .{ .path = target.path, .at = at, .text = line[at..] }; } @@ -1355,6 +1351,11 @@ test "syntax codeAfterLocation takes whole-token locations and nothing else" { try std.testing.expect(codeAfterLocation("src/x.zig:7:2") == null); try std.testing.expect(codeAfterLocation("") == null); try std.testing.expect(codeAfterLocation(" leading space") == null); + const indented = " some directory/x.zig:7:2-9 return 42;"; + const nested = codeAfterLocation(indented) orelse return error.ShouldBeALocation; + try std.testing.expectEqualStrings("some directory/x.zig", nested.path); + try std.testing.expectEqualStrings(" return 42;", nested.text); + try std.testing.expectEqualStrings(nested.text, indented[nested.at..]); } test "syntax default full grammar set highlights Typst source" { @@ -1736,6 +1737,7 @@ test "syntax result fragments preserve source indentation and inline markup" { defer stop(); const fixtures = [_]struct { path: []const u8, source: []const u8 }{ .{ .path = "a.zig", .source = " const number = 42; // note" }, + .{ .path = " nested path/a.zig", .source = " return call(42, \"hello\"); // note" }, .{ .path = "a.md", .source = "# Heading *slant*" }, .{ .path = "a.md", .source = "**bold** and `code`" }, .{ .path = "a.md", .source = " # this is indented code" }, @@ -1961,4 +1963,3 @@ test "syntax source analysis preserves declarations and injected colors" { try std.testing.expectEqual(@as(usize, 0), unsupported.declarations.len); try std.testing.expectEqual(@as(usize, 0), unsupported.colors.len); } - diff --git a/src/tagline.zig b/src/tagline.zig index cf0b17fd..b6601d61 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -19,15 +19,19 @@ const Pardes = pardes.Pardes; pub const pane_tail = " " ++ config.pane_builtins_str; pub const pdf_pane_tail = " " ++ config.pdf_pane_builtins_str; pub const file_pane_tail = " " ++ config.file_pane_builtins_str; -pub const context_pane_tail = file_pane_tail ++ " TreeContext"; -pub const locations_pane_tail = file_pane_tail ++ " LocationsConfig"; -/// A file a language server speaks for (by its extension): its jumps too. -pub const lsp_pane_tail = file_pane_tail ++ " " ++ config.lsp_pane_builtins_str; -pub const lsp_context_pane_tail = context_pane_tail ++ " " ++ config.lsp_pane_builtins_str; +fn withFileCommands(comptime tail: []const u8, comptime words: []const u8) []const u8 { + std.debug.assert(std.mem.endsWith(u8, tail, " Del")); + return tail[0 .. tail.len - " Del".len] ++ " " ++ words ++ " Del"; +} +pub const context_pane_tail = withFileCommands(file_pane_tail, "TreeContext"); +pub const locations_pane_tail = withFileCommands(file_pane_tail, "LocationsConfig"); +/// Language commands precede the final Del, like other file-pane commands. +pub const lsp_pane_tail = withFileCommands(file_pane_tail, config.lsp_pane_builtins_str); +pub const lsp_context_pane_tail = withFileCommands(context_pane_tail, config.lsp_pane_builtins_str); pub const pager_pane_tail = " " ++ config.pager_pane_builtins_str; pub const diff_pane_tail = " " ++ config.diff_pane_builtins_str; pub const pager_diff_pane_tail = " " ++ config.pager_diff_pane_builtins_str; -pub const diff_view_tail = " " ++ config.diff_view_builtins_str ++ " LocationsConfig"; +pub const diff_view_tail = withFileCommands(" " ++ config.diff_view_builtins_str, "LocationsConfig"); pub const terminal_pane_tail = " " ++ config.terminal_pane_builtins_str; pub const command_pane_tail = " " ++ config.command_pane_builtins_str; pub const dir_pane_tail = " " ++ config.dir_pane_builtins_str; @@ -76,7 +80,7 @@ pub fn revealHeader(p: *Pardes) void { if (cur < p.header_top) p.header_top = cur; if (rows > 0 and cur >= p.header_top + rows) p.header_top = cur + 1 - rows; const line = modal.lineSlice(text, cur); - const width = p.tagCapacity(if (p.header_column) |c| p.col_w[c] -| TAG_TEXT_INSET else p.screen_w); + const width = p.tagCapacity(if (p.header_column) |c| p.col_w[c] -| TAG_TEXT_INSET else p.screen_w -| TAG_TEXT_INSET); const col = panes.File.rawDisplayCol(line, @min(@as(usize, @intCast(@max(0, t.cur_col))), line.len)); if (col < p.header_scroll) p.header_scroll = col; if (col >= p.header_scroll + width) p.header_scroll = col -| (width -| 1); @@ -480,4 +484,3 @@ test "a pane tag wraps a long line onto rows, and offsets map both ways" { try std.testing.expectEqual(@as(usize, 10), shown.toReal(11)); // the 'e' of Del try std.testing.expectEqual(@as(usize, 11), shown.fromReal(10)); } - diff --git a/test/column_drag.zig b/test/column_drag.zig index 89508800..a089ab4a 100644 --- a/test/column_drag.zig +++ b/test/column_drag.zig @@ -153,12 +153,14 @@ test "column grip is separate from compact text and the resize seam" { try std.testing.expectEqual(pardes.FontRole.tagline, surface.at(rect.x + pardes.TAG_TEXT_INSET, pardes.TOPBAR_H).style.font_role); try std.testing.expectEqual(pardes.FontRole.tagline, surface.at(rect.x + pardes.TAG_TEXT_INSET, pane_tag_y).style.font_role); } - const gap_x = p.col_x[1] + config.GUTTER; - try std.testing.expectEqualStrings(" ", p.surface.at(gap_x, pardes.TOPBAR_H).grapheme()); - mouse(p, .press, gap_x); - try std.testing.expect(p.drag != .column_move); - try std.testing.expect(!p.header_drag); - mouse(p, .release, gap_x); + if (pardes.TAG_GAP > 0) { + const gap_x = p.col_x[1] + config.GUTTER; + try std.testing.expectEqualStrings(" ", p.surface.at(gap_x, pardes.TOPBAR_H).grapheme()); + mouse(p, .press, gap_x); + try std.testing.expect(p.drag != .column_move); + try std.testing.expect(!p.header_drag); + mouse(p, .release, gap_x); + } p.update(.{ .mouse = headerMouse(layer, 0, .press) }); try std.testing.expect(p.drag != .column_move); try std.testing.expect(p.header_drag); diff --git a/test/hxcases/waivers.jsonl b/test/hxcases/waivers.jsonl index 6abc7de2..34687480 100644 --- a/test/hxcases/waivers.jsonl +++ b/test/hxcases/waivers.jsonl @@ -1,2 +1,3 @@ {"name":"alt-c-window-op","reason":"Alt-c moves a pane to a new column instead of Helix's change-noyank.","reference":{"name":"alt-c-window-op","text":"bc def\n","mode":"insert","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0}},"expected":{"name":"alt-c-window-op","text":"abc def\n","mode":"normal","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0}}} {"name":"msel-ins-checkpoint","reason":"Undo restores the primary range alone: a history entry keeps one range, not every one, so the others stay where the edit left them.","reference":{"name":"msel-ins-checkpoint","text":"Xab\nXab\n","mode":"normal","cursor":{"row":1,"col":1},"anchor":{"row":1,"col":1},"sels":[{"cursor":{"row":0,"col":1},"anchor":{"row":0,"col":1}},{"cursor":{"row":1,"col":1},"anchor":{"row":1,"col":1}}],"primary":1},"expected":{"name":"msel-ins-checkpoint","text":"Xab\nXab\n","mode":"normal","cursor":{"row":1,"col":1},"anchor":{"row":1,"col":1},"sels":[{"cursor":{"row":0,"col":2},"anchor":{"row":0,"col":2}},{"cursor":{"row":1,"col":1},"anchor":{"row":1,"col":1}}],"primary":1}} +{"name":"gc-noscroll","reason":"gc runs the Callstack builtin at the cursor instead of moving to the viewport center; with no language server the cursor stays put.","reference":{"name":"gc-noscroll","text":"l00\nl01\nl02\nl03\nl04\nl05\nl06\nl07\nl08\nl09\nl10\nl11\n","mode":"normal","cursor":{"row":6,"col":0},"anchor":{"row":6,"col":0}},"expected":{"name":"gc-noscroll","text":"l00\nl01\nl02\nl03\nl04\nl05\nl06\nl07\nl08\nl09\nl10\nl11\n","mode":"normal","cursor":{"row":0,"col":0},"anchor":{"row":0,"col":0}}} diff --git a/test/panes.zig b/test/panes.zig index 41061bea..86e52838 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -121,10 +121,12 @@ const TagLayerTests = struct { try std.testing.expectEqual(second, p.drag.move.id); p.update(.{ .mouse = mouse(layer, grip_edge - 0.1, .release) }); try std.testing.expectEqualStrings(" ", p.surface.at(layer.viewport.x - 1, layer.viewport.y).grapheme()); - p.update(.{ .mouse = mouse(layer, edge - 0.1, .press) }); - try std.testing.expect(p.drag != .move); - try std.testing.expect(p.panes[second].?.focus == .body); - p.update(.{ .mouse = mouse(layer, edge - 0.1, .release) }); + if (pardes.TAG_GAP > 0) { + p.update(.{ .mouse = mouse(layer, edge - 0.1, .press) }); + try std.testing.expect(p.drag != .move); + try std.testing.expect(p.panes[second].?.focus == .body); + p.update(.{ .mouse = mouse(layer, edge - 0.1, .release) }); + } p.update(.{ .mouse = mouse(layer, edge + 0.1, .press) }); p.update(.{ .mouse = mouse(layer, edge + 0.1, .release) }); try std.testing.expectEqual(second, p.active); @@ -164,7 +166,6 @@ const TagLayerTests = struct { } }; - // Rows relative to where the pane's body and tag are, whatever height its // tag has (a tag wraps onto more rows when it is long). fn paneAt(p: *Pardes, r: anytype) *pardes.Pane { @@ -2735,6 +2736,146 @@ const OutputTests = struct { } } + test "stacked Callstack aligns source below locations and keeps exact emphasis and navigation" { + if (!syntax.enabled) return error.SkipZigTest; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 30 }); + defer p.deinit(); + const source = " pub fn caller(\n value: u32,\n ) void {\n work(value);\n }\n"; + const pane = try TreeContextTests.setZigFile(p, source); + try std.testing.expectEqual(config.Runtime.CallstackLayout.stacked, p.settings.callstack_layout); + const input = try std.fmt.allocPrint(p.gpa, "╰──╮ {s}:1:12-17 caller\n@callstack-match ╰─ {s}:4:9-12 work(value);\n", .{ pane.file.?.path, pane.file.?.path }); + try fillResults(p, 0, "/", .{ .query = .callstack }, "", input, null); + const result_id = pane.search_pane.?; + const result = p.panes[result_id].?; + const file = &result.file.?; + try std.testing.expectEqual(@as(usize, 6), file.location_rows.len); + try std.testing.expectEqualStrings(" │ pub fn caller(", modal.lineSlice(file.content, 1)); + try std.testing.expectEqualStrings(" │ value: u32,", modal.lineSlice(file.content, 2)); + try std.testing.expectEqualStrings(" │ ) void {", modal.lineSlice(file.content, 3)); + try std.testing.expectEqualStrings(" work(value);", modal.lineSlice(file.content, 5)); + const site = file.location_rows[5]; + try std.testing.expectEqual(@as(usize, 8), site.source_column); + try std.testing.expect(site.colors.len > 0); + const text = modal.lineSlice(file.content, 5); + const decoration = panes.Output.decorateRow(file.output, text, site); + try std.testing.expectEqualStrings("work", text[decoration.mark_start..decoration.mark_end]); + for (file.location_rows, 0..) |row, i| { + try std.testing.expectEqual(i == 0 or i == 4, panes.Output.isResultRow(file, i)); + if (i != 5) try std.testing.expect(!row.mark_occurrence); + } + p.active = result_id; + result.body.cur_row = 4; + result.body.cur_col = " └─ ".len; + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(@as(i32, 3), pane.body.cur_row); + try pardes.dump.dumpState(p); + const restored = try pardes.dump.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); + defer restored.deinit(); + try std.testing.expectEqual(config.Runtime.CallstackLayout.stacked, restored.settings.callstack_layout); + const after = restored.panes[result_id].?.file.?; + try std.testing.expectEqualStrings(file.content, after.content); + try std.testing.expectEqual(@as(usize, 8), after.location_rows[5].source_column); + const restored_decoration = panes.Output.decorateRow(after.output, text, after.location_rows[5]); + try std.testing.expectEqual(decoration, restored_decoration); + try std.testing.expect(p.executeBuiltinLine(0, "CallstackLayout inline")); + try fillResults(p, 0, "/", .{ .query = .callstack }, "", try p.gpa.dupe(u8, "No callers reported\n"), null); + try std.testing.expectEqual(config.Runtime.CallstackLayout.@"inline", p.settings.callstack_layout); + } + + test "Callstack signatures share unsaved tree context and keep guides out of Look selections" { + if (!syntax.enabled) return error.SkipZigTest; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 110, .rows = 30 }); + defer p.deinit(); + p.settings.callstack_layout = .@"inline"; + const source = "const Box = struct {\n" ++ + " pub fn caller(\n" ++ + " value: u32,\n" ++ + " ) void {\n" ++ + " work(value);\n" ++ + " }\n};\n"; + const pane = try TreeContextTests.setZigFile(p, source); + const path = pane.file.?.path; + const input = try std.fmt.allocPrint(p.gpa, "├──┬ {s}:2:12-17 caller\n@callstack-match │ └─ {s}:5:9-12 work(value);\n└─── missing.zig:3:4-8 other ↻ recursion\n", .{ path, path }); + try fillResults(p, 0, "/", .{ .query = .callstack }, "", input, null); + const result_id = pane.search_pane.?; + const result = p.panes[result_id].?; + const file = &result.file.?; + try std.testing.expect(std.mem.indexOf(u8, file.content, "pub fn caller(") != null); + try std.testing.expect(std.mem.indexOf(u8, file.content, "value: u32,") != null); + try std.testing.expect(std.mem.indexOf(u8, file.content, "const Box") == null); + try std.testing.expect(std.mem.indexOf(u8, file.content, "other ↻ recursion") != null); + try std.testing.expectEqual(@as(usize, 5), file.location_rows.len); + for (file.location_rows[0..3]) |row| { + try std.testing.expect(!row.declaration); + try std.testing.expect(!row.mark_occurrence); + try std.testing.expect(row.colors.len > 0); + } + for (1..3) |index| try std.testing.expect(std.mem.startsWith(u8, modal.lineSlice(file.content, index), "│ │ ")); + const analysis = try syntax.analyzeSource(p.scratch.allocator(), path, source, true, true); + for (file.location_rows[0..3], 1..) |row, source_row| { + const offset = modal.lineStartOffset(source, source_row); + try std.testing.expectEqualSlices(u8, analysis.colors[offset..][0..row.colors.len], row.colors); + } + try std.testing.expect(file.location_rows[3].mark_occurrence); + try std.testing.expect(!file.location_rows[3].declaration); + try std.testing.expect(!panes.Output.isWalkRow(file, 1, modal.lineSlice(file.content, 1))); + p.active = result_id; + result.body.cur_row = 0; + result.body.cur_col = 0; + p.update(.{ .key = .{ .cp = ' ' } }); + p.update(.{ .key = .{ .cp = 'j' } }); + p.update(.{ .key = .{ .cp = 'n' } }); + try std.testing.expectEqual(@as(i32, 0), result.body.cur_row); + try std.testing.expectEqual(@as(i32, "├──┬ ".len), result.body.cur_col); + // Enter on the selected signature address must open source, not a path + // accidentally prefixed with tree glyphs. + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); + p.settings.callstack_depth = 16; + try pardes.dump.dumpState(p); + const restored = try pardes.dump.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); + defer restored.deinit(); + try std.testing.expectEqual(@as(u8, 16), restored.settings.callstack_depth); + const restored_file = restored.panes[result_id].?.file.?; + try std.testing.expectEqualStrings(file.content, restored_file.content); + try std.testing.expectEqual(file.location_rows.len, restored_file.location_rows.len); + for (file.location_rows, restored_file.location_rows) |before, after| { + try std.testing.expectEqual(before.mark_occurrence, after.mark_occurrence); + try std.testing.expectEqual(before.at, after.at); + try std.testing.expectEqual(before.code_start, after.code_start); + try std.testing.expectEqualSlices(u8, before.colors, after.colors); + } + // Narrow enough that the location itself wraps. The repeated guide + // consumes cells, but neither changes the source address nor steals + // a click from the wrapped portion of that address. + p.active = result_id; + p.row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 10 }; + p.update(.{ .resize = .{ .cols = 28, .rows = 40 } }); + result.file.?.scroll = 0; + var frame = std.heap.ArenaAllocator.init(p.gpa); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + const wrapped = for (0..result.wrap_n) |vr| { + const w = result.wrapAt(@intCast(vr)); + if (w.line == 0 and w.pad > 0 and w.at < file.location_rows[0].location_end) break vr; + } else return error.MissingWrappedLocation; + const w = result.wrapAt(@intCast(wrapped)); + const shown = try panes.File.bodyText(frame.allocator(), result, file, true); + const shown_line = modal.lineSlice(shown, wrapped); + try std.testing.expect(std.mem.startsWith(u8, shown_line[panes.File.gutterWidth(result)..], "│ │ ")); + const rect = p.rects[result_id]; + const press: pardes.Mouse = .{ .button = .right, .kind = .press, .col = @intCast(rect.x + config.GUTTER + panes.File.gutterWidth(result) + w.pad + 1), .row = @intCast(p.bodyTop(result, rect) + wrapped) }; + + var release = press; + release.kind = .release; + p.update(.{ .mouse = press }); + p.update(.{ .mouse = release }); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); + } + test "Locations context uses unsaved sources and navigation visits only matches" { if (!syntax.enabled) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 30 }); diff --git a/test/snapshots/argv.golden b/test/snapshots/argv.golden index 65b0ac71..9dfa35b9 100644 --- a/test/snapshots/argv.golden +++ b/test/snapshots/argv.golden @@ -1,7 +1,7 @@ == snap noargs grid=100x31 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -|$ /tmp/pardes-snap/argv/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/argv/cwd Tty+bash Save Mode Filter Collapse Del | $ echo ARGV''TTY | ARGVTTY | $ @@ -20,12 +20,12 @@ | | | -| /tmp/pardes-snap/argv/cwd/+New Save Tty Collapse Del +| /tmp/pardes-snap/argv/cwd/+New Save Tty Collapse Del | 1 == snap filearg grid=100x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/argv/cwd/notes.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/argv/cwd/notes.txt Save Tty Collapse Del | 3 line 3 | 4 line 4 | 5 line 5 @@ -34,9 +34,9 @@ | 8 line 8 | 9 == snap filearg-n3 grid=100x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/argv/cwd/notes.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/argv/cwd/notes.txt Save Tty Collapse Del | 1 line 1 | 2 line 2 | 3 line 3 @@ -47,8 +47,8 @@ | 8 line 8 | 9 == snap dirarg grid=100x31 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/argv/cwd/sub Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/argv/cwd/sub Tty+bash Save Mode Filter Collapse Del | ls | inside.txt diff --git a/test/snapshots/badutf.golden b/test/snapshots/badutf.golden index 14aa71dc..1cdd5163 100644 --- a/test/snapshots/badutf.golden +++ b/test/snapshots/badutf.golden @@ -1,17 +1,17 @@ == snap badbytes grid=100x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/badutf/cwd/bad.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/badutf/cwd/bad.txt Save Tty Collapse Del | 1 hello �� world | 2 latin-1 caf� tail | 3 truncated �� here | 4 end | 5 == snap hscroll-midglyph grid=50x31 cursor=46,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/badutf/cwd/wide.txt Save Tty C -| ollapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Du +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/badutf/cwd/wide.txt Save Tty Co +| llapse Del | 1 日本語 日本語 日本語 日本語 日本語 tail | 2 | 3 diff --git a/test/snapshots/boot.golden b/test/snapshots/boot.golden index ac674ed2..85b994d7 100644 --- a/test/snapshots/boot.golden +++ b/test/snapshots/boot.golden @@ -1,13 +1,13 @@ == snap boot grid=100x31 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/boot/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/boot/cwd Tty+bash Save Mode Filter Collapse Del | ls | hello.txt == style boot grid=100x31 -|0: 0-99 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-99 #becfc4,#314738, -|2: 0-1 d,#add38a, 2-2 d,#314738, 3-28 #becfc4,#314738, 29-37 #dfbce5,#314738, 38-99 #becfc4,#314738, +|0: 0-1 d,#1d2824, 2-99 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-99 #becfc4,#314738, +|2: 0-1 d,#add38a, 2-27 #becfc4,#314738, 28-36 #dfbce5,#314738, 37-99 #becfc4,#314738, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-99 d,#0d1410, diff --git a/test/snapshots/builtins.golden b/test/snapshots/builtins.golden index 2207ede6..b9d5c5b2 100644 --- a/test/snapshots/builtins.golden +++ b/test/snapshots/builtins.golden @@ -1,7 +1,7 @@ == snap boot grid=120x67 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/builtins/cwd/notes.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/builtins/cwd/notes.txt Save Tty Collapse Del | 1 line 1 | 2 line 2 | 3 line 3 @@ -10,7 +10,7 @@ | 6 line 6 | 7 == snap window-group grid=120x67 cursor=7,10 -|9: /tmp/pardes-snap/builtins/cwd/+Help Save Tty Collapse Del +|9: /tmp/pardes-snap/builtins/cwd/+Help Save Tty Collapse Del |10: 1 pardes builtins under SPC w |11: 2 |12: 3 SPC w h Left C-w h, C-w left @@ -27,7 +27,7 @@ |16: == snap tutor-from-index grid=120x67 cursor=7,16 |10: 1 pardes builtins under SPC h Tutor -|15: /tmp/pardes-snap/builtins/cwd/+Tutor Save Tty Collapse Del +|15: /tmp/pardes-snap/builtins/cwd/+Tutor Save Tty Collapse Del |16: 1 |17: 2 PARDES TUTOR |18: 3 diff --git a/test/snapshots/builtins.snap b/test/snapshots/builtins.snap index 8ae22a62..fc0ab796 100644 --- a/test/snapshots/builtins.snap +++ b/test/snapshots/builtins.snap @@ -30,6 +30,8 @@ wheel up 110 50 wheel up 110 50 wheel up 110 50 wheel up 110 50 +wheel up 110 50 +wheel up 110 50 wait 10000 Look enter, right-click wait 10000 Exec tab, middle-click wait 10000 Filter diff --git a/test/snapshots/callstack-inline.golden b/test/snapshots/callstack-inline.golden new file mode 100644 index 00000000..32213223 --- /dev/null +++ b/test/snapshots/callstack-inline.golden @@ -0,0 +1,65 @@ +== snap hierarchy grid=110x40 cursor=7,14 +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/callstack-inline/cwd/setup.txt Save Tty Collapse Del +| 1 CallstackLayout inline +| 2 main.rs +| /tmp/pardes-snap/callstack-inline/cwd/main.rs Save Tty Collapse TreeContext Def Refs Del +| 1 mod lib; --:--:-- lsp rust-analyzer: ready +| 2 +| 3 fn main() { +| 4 let x = add(1, 2); +| 5 let y = add(3, 4); +| 6 let _ = x + y; +| 7 } +| /tmp/pardes-snap/callstack-inline/cwd/+Callstack Save Tty Collapse Del +| 1 ╰──┬ main.rs:3:4-7 fn main() { +| 2 ├─ main.rs:4:13-15 let x = add(1, 2); +| 3 ├─ main.rs:5:13-15 let y = add(3, 4); +| 4 ╰──┬ main.rs:3:4-7 fn main() { ↻ recursion +| 5 ├─ main.rs:4:13-15 let x = add(1, 2); +| 6 ╰─ main.rs:5:13-15 let y = add(3, 4); +| 7 +== style hierarchy grid=110x40 +|0: 0-1 d,#1d2824, 2-109 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-109 #becfc4,#314738, +|2: 0-1 d,#496656, 2-39 #b2c3b8,#1d2824, 40-49 #d3b0d9,#1d2824, 50-109 #b2c3b8,#1d2824, +|3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-109 #e5eee5,#0d1410, +|4: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-109 #e5eee5,#0d1410, +|5: 0-1 d,#496656, 2-39 #b2c3b8,#1d2824, 40-47 #d3b0d9,#1d2824, 48-109 #b2c3b8,#1d2824, +|6: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #c9a7ed,#0d1410, 11-73 #e5eee5,#0d1410, 74-74 #e5eee5,#1d2824, 75-109 #b2c3b8,#1d2824, +|7: 0-0 d,#608269, 1-4 d,#0d1410, 5-109 #59675c,#0d1410, +|8: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-9 #c9a7ed,#0d1410, 10-109 #e5eee5,#0d1410, +|9: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-14 #c9a7ed,#0d1410, 15-109 #e5eee5,#0d1410, +|10: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-14 #c9a7ed,#0d1410, 15-109 #e5eee5,#0d1410, +|11: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-14 #c9a7ed,#0d1410, 15-109 #e5eee5,#0d1410, +|12: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-109 #e5eee5,#0d1410, +|13: 0-1 d,#add38a, 2-39 #becfc4,#314738, 40-50 #dfbce5,#314738, 51-109 #becfc4,#314738, +|14: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-11 #92d1de,#0d1410, 12-25 #59675c,#0d1410, 26-28 #c9a7ed,#0d1410, 29-109 #e5eee5,#0d1410, +|15: 0-0 d,#608269, 1-4 d,#0d1410, 5-9 #59675c,#0d1410, 10-12 #92d1de,#0d1410, 13-32 #59675c,#0d1410, 33-36 #c9a7ed,#0d1410, 37-109 #e5eee5,#0d1410, +|16: 0-0 d,#608269, 1-4 d,#0d1410, 5-9 #59675c,#0d1410, 10-12 #92d1de,#0d1410, 13-32 #59675c,#0d1410, 33-36 #c9a7ed,#0d1410, 37-109 #e5eee5,#0d1410, +|17: 0-0 d,#608269, 1-4 d,#0d1410, 5-9 #59675c,#0d1410, 10-14 #92d1de,#0d1410, 15-28 #59675c,#0d1410, 29-31 #c9a7ed,#0d1410, 32-109 #e5eee5,#0d1410, +|18: 0-0 d,#608269, 1-4 d,#0d1410, 5-12 #59675c,#0d1410, 13-15 #92d1de,#0d1410, 16-35 #59675c,#0d1410, 36-39 #c9a7ed,#0d1410, 40-43 #e5eee5,#0d1410, 44-46 #f7e4a5,#5e4923, 47-109 #e5eee5,#0d1410, +|19: 0-0 d,#608269, 1-4 d,#0d1410, 5-12 #59675c,#0d1410, 13-15 #92d1de,#0d1410, 16-35 #59675c,#0d1410, 36-39 #c9a7ed,#0d1410, 40-43 #e5eee5,#0d1410, 44-46 #f7e4a5,#5e4923, 47-109 #e5eee5,#0d1410, +|20: 0-0 d,#608269, 1-4 d,#0d1410, 5-109 #59675c,#0d1410, +|21: 0-0 d,#608269, 1-109 d,#0d1410, +|22: 0-0 d,#608269, 1-109 d,#0d1410, +|23: 0-0 d,#608269, 1-109 d,#0d1410, +|24: 0-0 d,#608269, 1-109 d,#0d1410, +|25: 0-0 d,#608269, 1-109 d,#0d1410, +|26: 0-0 d,#608269, 1-109 d,#0d1410, +|27: 0-0 d,#608269, 1-109 d,#0d1410, +|28: 0-0 d,#608269, 1-109 d,#0d1410, +|29: 0-0 d,#608269, 1-109 d,#0d1410, +|30: 0-0 d,#608269, 1-109 d,#0d1410, +|31: 0-0 d,#608269, 1-109 d,#0d1410, +|32: 0-0 d,#608269, 1-109 d,#0d1410, +|33: 0-0 d,#608269, 1-109 d,#0d1410, +|34: 0-0 d,#608269, 1-109 d,#0d1410, +|35: 0-0 d,#608269, 1-109 d,#0d1410, +|36: 0-0 d,#608269, 1-109 d,#0d1410, +|37: 0-0 d,#608269, 1-109 d,#0d1410, +|38: 0-0 d,#608269, 1-109 d,#0d1410, +|39: 0-0 d,#608269, 1-109 d,#0d1410, +== snap caller grid=110x40 cursor=13,8 +|6: 1 mod lib; diff --git a/test/snapshots/callstack-inline.snap b/test/snapshots/callstack-inline.snap new file mode 100644 index 00000000..9acfa206 --- /dev/null +++ b/test/snapshots/callstack-inline.snap @@ -0,0 +1,30 @@ +# Inline remains an option; source colors, rounded guides and Look navigation are retained. +file main.rs mod lib;\n\nfn main() {\n let x = add(1, 2);\n let y = add(3, 4);\n let _ = x + y;\n}\n +file lib.rs // mock fixture\npub fn add(a: i32, b: i32) -> i32 {\n a + b\n}\n +file setup.txt CallstackLayout inline\nmain.rs\n +start 40 110 setup.txt +wait 8000 CallstackLayout inline +key g g +key x +key tab +stable 300 10000 +key esc +settle 100 +key g g +key j +key home +key enter +wait 8000 add(1, 2) +stable 700 20000 +key g c +wait 10000 Callstack +wait 10000 recursion +stable 700 15000 +snap hierarchy +snapstyle hierarchy +# LookNext selects the caller signature; Enter opens it in the source pane. +key space j n +key enter +wait 10000 fn main +stable 700 15000 +snap caller diff --git a/test/snapshots/callstack.golden b/test/snapshots/callstack.golden new file mode 100644 index 00000000..2970593d --- /dev/null +++ b/test/snapshots/callstack.golden @@ -0,0 +1,27 @@ +== snap hierarchy grid=110x40 cursor=7,11 +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/callstack/cwd/main.rs Save Tty Collapse TreeContext Def Refs Del +| 1 mod lib; --:--:-- lsp rust-analyzer: ready +| 2 +| 3 fn main() { +| 4 let x = add(1, 2); +| 5 let y = add(3, 4); +| 6 let _ = x + y; +| 7 } +| /tmp/pardes-snap/callstack/cwd/+Callstack Save Tty Collapse Del +| 1 ╰──┬ main.rs:3:4-7 +| 2 │ fn main() { +| 3 ├─ main.rs:4:13-15 +| 4 │ let x = add(1, 2); +| 5 ├─ main.rs:5:13-15 +| 6 │ let y = add(3, 4); +| 7 ╰──┬ main.rs:3:4-7 +| 8 │ fn main() { ↻ recursion +| 9 ├─ main.rs:4:13-15 +| 10 │ let x = add(1, 2); +| 11 ╰─ main.rs:5:13-15 +| 12 let y = add(3, 4); +| 13 +== snap caller grid=110x40 cursor=13,5 +|3: 1 mod lib; diff --git a/test/snapshots/callstack.snap b/test/snapshots/callstack.snap new file mode 100644 index 00000000..b32367af --- /dev/null +++ b/test/snapshots/callstack.snap @@ -0,0 +1,19 @@ +# Static call hierarchy in a dedicated pane; sites and declarations are Look targets. +file main.rs mod lib;\n\nfn main() {\n let x = add(1, 2);\n let y = add(3, 4);\n let _ = x + y;\n}\n +file lib.rs // mock fixture\npub fn add(a: i32, b: i32) -> i32 {\n a + b\n}\n +start 40 110 main.rs +wait 8000 add(1, 2) +stable 700 20000 +press left 13 6 +release left 13 6 +key g c +wait 10000 Callstack +wait 10000 recursion +stable 700 15000 +snap hierarchy +# LookNext selects the caller signature; Enter opens it in the source pane. +key space j n +key enter +wait 10000 fn main +stable 700 15000 +snap caller diff --git a/test/snapshots/chordcut.golden b/test/snapshots/chordcut.golden index 817c534c..280dd877 100644 --- a/test/snapshots/chordcut.golden +++ b/test/snapshots/chordcut.golden @@ -1,12 +1,12 @@ == snap opened grid=120x31 cursor=7,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/chordcut/cwd Tty+bash Save Mode Filter C /tmp/pardes-snap/chordcut/cwd Tty+bash Save Mode Filter C -| ollapse Del ollapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/chordcut/cwd Tty+bash Save Mode Filter Co /tmp/pardes-snap/chordcut/cwd Tty+bash Save Mode Filter Co +| llapse Del llapse Del | ls ls | f.txt g.txt f.txt g.txt | -| /tmp/pardes-snap/chordcut/cwd/f.txt Save Tty Collapse Del +| /tmp/pardes-snap/chordcut/cwd/f.txt Save Tty Collapse Del | 1 line 1 | 2 line 2 | 3 line 3 @@ -16,12 +16,12 @@ | | | -| /tmp/pardes-snap/chordcut/cwd Tty+bash Save Mode Filter C -| ollapse Del +| /tmp/pardes-snap/chordcut/cwd Tty+bash Save Mode Filter Co +| llapse Del | ls | f.txt g.txt == snap cut grid=120x31 cursor=7,9 -|7: * /tmp/pardes-snap/chordcut/cwd/f.txt Save Tty Collapse Del +|7: */tmp/pardes-snap/chordcut/cwd/f.txt Save Tty Collapse Del |9: 2 2 == snap copied grid=120x31 cursor=10,10 == snap pointpaste grid=120x31 cursor=16,11 @@ -32,27 +32,27 @@ |9: 2 2echo B''OO g.txt == snap execafter grid=120x31 cursor=25,9 |8: 1 line 1 Exec -|17: /tmp/pardes-snap/chordcut/cwd Tty+bash Save Mode Filter C /tmp/pardes-snap/chordcut/cwd (echo B''OO) exit 0 Kill Sa -|18: ollapse Del ve Collapse Del +|17: /tmp/pardes-snap/chordcut/cwd Tty+bash Save Mode Filter Co /tmp/pardes-snap/chordcut/cwd (echo B''OO) exit 0 Kill Sav +|18: llapse Del e Collapse Del |19: ls % echo B''OO |20: f.txt g.txt BOO |21: exit 0 == snap cancellook grid=120x31 cursor=25,9 |8: 1 line 1 == snap lookafter grid=120x31 cursor=7,23 -|22: /tmp/pardes-snap/chordcut/cwd/g.txt Save Tty Collapse Del +|22: /tmp/pardes-snap/chordcut/cwd/g.txt Save Tty Collapse Del |23: 1 line 1 |24: 2 line 2 |25: 3 == style chordsel grid=120x31 -|0: 0-119 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-59 #becfc4,#314738, 60-61 #becfc4,#887455, 62-62 #becfc4,#1d2824, 63-119 #b2c3b8,#1d2824, -|2: 0-1 d,#496656, 2-2 d,#1d2824, 3-32 #b2c3b8,#1d2824, 33-41 #d3b0d9,#1d2824, 42-59 #b2c3b8,#1d2824, 60-61 #b2c3b8,#496656, 62-92 #b2c3b8,#1d2824, 93-101 #d3b0d9,#1d2824, 102-119 #b2c3b8,#1d2824, -|3: 0-2 d,#1d2824, 3-119 #b2c3b8,#1d2824, +|0: 0-1 d,#1d2824, 2-119 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-59 #becfc4,#314738, 60-61 #becfc4,#887455, 62-119 #b2c3b8,#1d2824, +|2: 0-1 d,#496656, 2-31 #b2c3b8,#1d2824, 32-40 #d3b0d9,#1d2824, 41-59 #b2c3b8,#1d2824, 60-61 #b2c3b8,#496656, 62-91 #b2c3b8,#1d2824, 92-100 #d3b0d9,#1d2824, 101-119 #b2c3b8,#1d2824, +|3: 0-1 d,#1d2824, 2-119 #b2c3b8,#1d2824, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, |6: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, -|7: 0-0 d,#496656, 1-1 #000000,#f9cb70,b 2-2 #000000,#1d2824, 3-32 #b2c3b8,#1d2824, 33-38 #d3b0d9,#1d2824, 39-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, +|7: 0-0 d,#496656, 1-1 #000000,#f9cb70,b 2-31 #b2c3b8,#1d2824, 32-37 #d3b0d9,#1d2824, 38-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, |8: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, |9: 0-0 d,#608269, 1-4 d,#0d1410, 5-7 #59675c,#0d1410, 8-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, |10: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, @@ -62,12 +62,12 @@ |14: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, |15: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, |16: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, -|17: 0-1 d,#496656, 2-2 d,#1d2824, 3-32 #b2c3b8,#1d2824, 33-41 #d3b0d9,#1d2824, 42-59 #b2c3b8,#1d2824, 60-61 #b2c3b8,#496656, 62-119 #b2c3b8,#1d2824, -|18: 0-2 d,#1d2824, 3-119 #b2c3b8,#1d2824, +|17: 0-1 d,#496656, 2-31 #b2c3b8,#1d2824, 32-40 #d3b0d9,#1d2824, 41-59 #b2c3b8,#1d2824, 60-61 #b2c3b8,#496656, 62-119 #b2c3b8,#1d2824, +|18: 0-1 d,#1d2824, 2-119 #b2c3b8,#1d2824, |19: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, |20: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, |21: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-61 d,#0d1410, 62-119 #e5eee5,#0d1410, -|22: 0-1 d,#add38a, 2-2 d,#314738, 3-32 #becfc4,#314738, 33-38 #dfbce5,#314738, 39-59 #becfc4,#314738, 60-60 #becfc4,#608269, 61-119 #becfc4,#0d1410, +|22: 0-1 d,#add38a, 2-31 #becfc4,#314738, 32-37 #dfbce5,#314738, 38-59 #becfc4,#314738, 60-60 #becfc4,#608269, 61-119 #becfc4,#0d1410, |23: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #f5f7ee,#3c614a, 11-11 #f5f7ee,#0d1410, 12-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, |24: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, |25: 0-0 d,#608269, 1-4 d,#0d1410, 5-59 #59675c,#0d1410, 60-60 #59675c,#608269, 61-119 #59675c,#0d1410, @@ -80,7 +80,7 @@ |23: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, |24: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, == snap ttyprobe grid=120x31 cursor=42,23 -|17: $ /tmp/pardes-snap/chordcut/cwd Tty+bash Save Mode Filter C /tmp/pardes-snap/chordcut/cwd (echo B''OO) exit 0 Kill Sa +|17: $ /tmp/pardes-snap/chordcut/cwd Tty+bash Save Mode Filter Co /tmp/pardes-snap/chordcut/cwd (echo B''OO) exit 0 Kill Sav |19: $ ls % echo B''OO |21: $ stty -icanon -echo; printf '\x1b[?2004h\x1b[?1000h\x1b[? exit 0 |22: 1006h'; cat -v diff --git a/test/snapshots/cmdexit.golden b/test/snapshots/cmdexit.golden index 7d950a43..f2f38217 100644 --- a/test/snapshots/cmdexit.golden +++ b/test/snapshots/cmdexit.golden @@ -1,15 +1,15 @@ == snap opened grid=120x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/cmdexit/cwd/cmds.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/cmdexit/cwd/cmds.txt Save Tty Collapse Del | 1 sleep 30 & echo BG''STARTED | 2 exec /dev/null 2>&1; sleep 1; false == snap background grid=120x31 cursor=7,3 -|17: /tmp/pardes-snap/cmdexit/cwd (sleep 30 & echo BG''STARTED) exit 0 Kill Save Collapse Del +|17: /tmp/pardes-snap/cmdexit/cwd (sleep 30 & echo BG''STARTED) exit 0 Kill Save Collapse Del |18: % sleep 30 & echo BG''STARTED |19: BGSTARTED |20: exit 0 == snap letgo grid=120x31 cursor=7,3 -|24: /tmp/pardes-snap/cmdexit/cwd (exec /dev/null 2>&1; sleep 1; false) exit 1 Kill Save Collapse Del +|24: /tmp/pardes-snap/cmdexit/cwd (exec /dev/null 2>&1; sleep 1; false) exit 1 Kill Save Collapse Del |25: % exec /dev/null 2>&1; sleep 1; false |26: exit 1 diff --git a/test/snapshots/cmdword.golden b/test/snapshots/cmdword.golden index af2fbcb8..3b2f5cc9 100644 --- a/test/snapshots/cmdword.golden +++ b/test/snapshots/cmdword.golden @@ -1,28 +1,28 @@ == snap opened grid=120x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/cmdword/cwd/cmds.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/cmdword/cwd/cmds.txt Save Tty Collapse Del | 1 @`echo ZZ''E` @`echo ZZ''L` Look p.txt @`Look .` == snap atexec grid=120x31 cursor=7,3 -|17: /tmp/pardes-snap/cmdword/cwd (echo ZZ''E) exit 0 Kill Save Collapse Del +|17: /tmp/pardes-snap/cmdword/cwd (echo ZZ''E) exit 0 Kill Save Collapse Del |18: % echo ZZ''E |19: ZZE |20: exit 0 == snap atlook grid=120x31 cursor=2,24 -|17: /tmp/pardes-snap/cmdword/cwd (echo ZZ''L) exit 0 Kill Save Collapse Del +|17: /tmp/pardes-snap/cmdword/cwd (echo ZZ''L) exit 0 Kill Save Collapse Del |21: % echo ZZ''L |22: ZZL |23: exit 0 == snap lookword grid=120x31 cursor=7,6 -|5: /tmp/pardes-snap/cmdword/cwd/p.txt Save Tty Collapse Del +|5: /tmp/pardes-snap/cmdword/cwd/p.txt Save Tty Collapse Del |6: 1 just text == snap nested grid=120x31 cursor=4,11 -|8: /tmp/pardes-snap/cmdword/cwd Tty+bash Save Mode Filter Collapse Del +|8: /tmp/pardes-snap/cmdword/cwd Tty+bash Save Mode Filter Collapse Del |9: ls |10: cmds.txt p.txt zzmark.txt == snap execword grid=120x31 cursor=4,11 -|8: /tmp/pardes-snap/cmdword/cwd Tty+bash Save Mode Filter Collapse Del Exec +|8: /tmp/pardes-snap/cmdword/cwd Tty+bash Save Mode Filter Collapse Del Exec == snap tagcmd grid=120x31 cursor=4,11 -|8: /tmp/pardes-snap/cmdword/cwd Tty+bash Save Mode Filter Collapse Del Exec @`echo ZZ''T` +|8: /tmp/pardes-snap/cmdword/cwd Tty+bash Save Mode Filter Collapse Del Exec @`echo ZZ''T` |11: echo ZZ''T |12: ZZT diff --git a/test/snapshots/colgrip.golden b/test/snapshots/colgrip.golden index 26a0b1c0..e7881957 100644 --- a/test/snapshots/colgrip.golden +++ b/test/snapshots/colgrip.golden @@ -1,8 +1,8 @@ == style rest grid=100x24 -|0: 0-99 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#1d2824, 3-49 #b2c3b8,#1d2824, 50-51 #b2c3b8,#887455, 52-52 #b2c3b8,#314738, 53-99 #becfc4,#314738, -|2: 0-1 d,#496656, 2-2 d,#1d2824, 3-31 #b2c3b8,#1d2824, 32-37 #d3b0d9,#1d2824, 38-49 #b2c3b8,#1d2824, 50-51 #b2c3b8,#add38a, 52-52 #b2c3b8,#314738, 53-81 #becfc4,#314738, 82-90 #dfbce5,#314738, 91-99 #becfc4,#314738, -|3: 0-2 d,#1d2824, 3-49 #b2c3b8,#1d2824, 50-53 #b2c3b8,#314738, 54-99 #becfc4,#314738, +|0: 0-1 d,#1d2824, 2-99 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-49 #b2c3b8,#1d2824, 50-51 #b2c3b8,#887455, 52-99 #becfc4,#314738, +|2: 0-1 d,#496656, 2-30 #b2c3b8,#1d2824, 31-36 #d3b0d9,#1d2824, 37-49 #b2c3b8,#1d2824, 50-51 #b2c3b8,#add38a, 52-80 #becfc4,#314738, 81-89 #dfbce5,#314738, 90-99 #becfc4,#314738, +|3: 0-1 d,#1d2824, 2-49 #b2c3b8,#1d2824, 50-51 #b2c3b8,#314738, 52-99 #becfc4,#314738, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-49 #e5eee5,#0d1410, 50-50 #e5eee5,#608269, 51-99 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, |6: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-99 d,#0d1410, @@ -24,12 +24,12 @@ |22: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-99 d,#0d1410, |23: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-99 d,#0d1410, == style held grid=100x24 -|1: 0-1 d,#887455, 2-2 d,#1d2824, 3-49 #b2c3b8,#1d2824, 50-51 #b2c3b8,#f4c086, 52-52 #b2c3b8,#314738, 53-99 #becfc4,#314738, +|1: 0-1 d,#887455, 2-49 #b2c3b8,#1d2824, 50-51 #b2c3b8,#f4c086, 52-99 #becfc4,#314738, == snap resize-drag grid=100x24 cursor=54,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/colgrip/cwd/w.txt S╎ve Tty Col /tmp/pardes-snap/colgrip/cwd Tty+bash Save Mode -| lapse Del ╎ Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/colgrip/cwd/w.txt Sa╎e Tty Coll /tmp/pardes-snap/colgrip/cwd Tty+bash Save Mode +| apse Del ╎ Filter Collapse Del | 1 x ╎ ls | ╎ w.txt | ╎ @@ -51,9 +51,9 @@ | ╎ | ╎ == style resize-drag grid=100x24 -|1: 0-1 d,#887455, 2-2 d,#1d2824, 3-38 #b2c3b8,#1d2824, 39-49 #f4c086,#1d2824, 50-51 #f4c086,#f4c086, 52-52 #f4c086,#314738, 53-99 #becfc4,#314738, -|2: 0-1 d,#496656, 2-2 d,#1d2824, 3-31 #b2c3b8,#1d2824, 32-37 #d3b0d9,#1d2824, 38-38 #b2c3b8,#1d2824, 39-39 #f4c086,#1d2824, 40-49 #b2c3b8,#1d2824, 50-51 #b2c3b8,#add38a, 52-52 #b2c3b8,#314738, 53-81 #becfc4,#314738, 82-90 #dfbce5,#314738, 91-99 #becfc4,#314738, -|3: 0-2 d,#1d2824, 3-38 #b2c3b8,#1d2824, 39-49 #f4c086,#1d2824, 50-53 #f4c086,#314738, 54-99 #becfc4,#314738, +|1: 0-1 d,#887455, 2-38 #b2c3b8,#1d2824, 39-49 #f4c086,#1d2824, 50-51 #f4c086,#f4c086, 52-99 #becfc4,#314738, +|2: 0-1 d,#496656, 2-30 #b2c3b8,#1d2824, 31-36 #d3b0d9,#1d2824, 37-38 #b2c3b8,#1d2824, 39-39 #f4c086,#1d2824, 40-49 #b2c3b8,#1d2824, 50-51 #b2c3b8,#add38a, 52-80 #becfc4,#314738, 81-89 #dfbce5,#314738, 90-99 #becfc4,#314738, +|3: 0-1 d,#1d2824, 2-38 #b2c3b8,#1d2824, 39-49 #f4c086,#1d2824, 50-51 #f4c086,#314738, 52-99 #becfc4,#314738, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-38 #e5eee5,#0d1410, 39-49 #f4c086,#0d1410, 50-50 #f4c086,#608269, 51-51 #f4c086,#0d1410, 52-99 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-38 d,#0d1410, 39-49 #f4c086,#0d1410, 50-50 #f4c086,#608269, 51-51 #f4c086,#0d1410, 52-99 #e5eee5,#0d1410, |6: 0-0 d,#608269, 1-38 d,#0d1410, 39-49 #f4c086,#0d1410, 50-50 #f4c086,#608269, 51-99 #f4c086,#0d1410, @@ -75,9 +75,9 @@ |22: 0-0 d,#608269, 1-38 d,#0d1410, 39-49 #f4c086,#0d1410, 50-50 #f4c086,#608269, 51-99 #f4c086,#0d1410, |23: 0-0 d,#608269, 1-38 d,#0d1410, 39-49 #f4c086,#0d1410, 50-50 #f4c086,#608269, 51-99 #f4c086,#0d1410, == snap resize-done grid=100x24 cursor=44,6 -|1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -|2: /tmp/pardes-snap/colgrip/cwd/w.txt Sa /tmp/pardes-snap/colgrip/cwd Tty+bash Save Mode Filter Co -|3: ve Tty Collapse Del llapse Del +|1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/colgrip/cwd/w.txt Sav /tmp/pardes-snap/colgrip/cwd Tty+bash Save Mode Filter Col +|3: e Tty Collapse Del lapse Del |4: 1 x ls |5: w.txt |6: @@ -120,9 +120,9 @@ |22: ╎ |23: ╎ == style reorder-drag grid=100x24 -|1: 0-1 d,#887455, 2-2 d,#1d2824, 3-39 #b2c3b8,#1d2824, 40-41 #b2c3b8,#f4c086, 42-42 #b2c3b8,#314738, 43-99 #becfc4,#314738, -|2: 0-1 d,#496656, 2-2 d,#1d2824, 3-31 #b2c3b8,#1d2824, 32-37 #d3b0d9,#1d2824, 38-39 #b2c3b8,#1d2824, 40-41 #b2c3b8,#add38a, 42-42 #b2c3b8,#314738, 43-71 #becfc4,#314738, 72-80 #dfbce5,#314738, 81-99 #becfc4,#314738, -|3: 0-2 d,#1d2824, 3-39 #b2c3b8,#1d2824, 40-42 #b2c3b8,#314738, 43-99 #becfc4,#314738, +|1: 0-1 d,#887455, 2-39 #b2c3b8,#1d2824, 40-41 #b2c3b8,#f4c086, 42-99 #becfc4,#314738, +|2: 0-1 d,#496656, 2-30 #b2c3b8,#1d2824, 31-36 #d3b0d9,#1d2824, 37-39 #b2c3b8,#1d2824, 40-41 #b2c3b8,#add38a, 42-70 #becfc4,#314738, 71-79 #dfbce5,#314738, 80-99 #becfc4,#314738, +|3: 0-1 d,#1d2824, 2-39 #b2c3b8,#1d2824, 40-41 #b2c3b8,#314738, 42-99 #becfc4,#314738, |4: 0-0 d,#608269, 1-4 #f4c086,#0d1410, 5-6 #59675c,#0d1410, 7-39 #e5eee5,#0d1410, 40-40 #e5eee5,#608269, 41-99 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-39 #f4c086,#0d1410, 40-40 #f4c086,#608269, 41-41 #f4c086,#0d1410, 42-99 #e5eee5,#0d1410, |6: 0-0 d,#608269, 1-39 #f4c086,#0d1410, 40-40 #f4c086,#608269, 41-99 #f4c086,#0d1410, @@ -144,9 +144,9 @@ |22: 0-0 d,#608269, 1-39 #f4c086,#0d1410, 40-40 #f4c086,#608269, 41-99 #f4c086,#0d1410, |23: 0-0 d,#608269, 1-39 #f4c086,#0d1410, 40-40 #f4c086,#608269, 41-99 #f4c086,#0d1410, == snap reorder-done grid=100x24 cursor=4,6 -|1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -|2: /tmp/pardes-snap/colgrip/cwd Tty+bash Save Mode Filter Co /tmp/pardes-snap/colgrip/cwd/w.txt Sa -|3: llapse Del ve Tty Collapse Del +|1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/colgrip/cwd Tty+bash Save Mode Filter Col /tmp/pardes-snap/colgrip/cwd/w.txt Sav +|3: lapse Del e Tty Collapse Del |4: ls 1 x |5: w.txt |6: diff --git a/test/snapshots/collapse.golden b/test/snapshots/collapse.golden index 57aafc8f..13e1b1f2 100644 --- a/test/snapshots/collapse.golden +++ b/test/snapshots/collapse.golden @@ -1,7 +1,7 @@ == snap before grid=160x25 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/collapse/cwd/kept.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/collapse/cwd/kept.txt Save Tty Collapse Del | 1 KEEP-FIRST | 2 KEEP-SECOND | 3 KEEP-THIRD @@ -10,12 +10,12 @@ |4: |5: == 9p middle-collapsed-cursor grid=160x25 cursor=none -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -@0: 0-74 #b2c3b8,#1d2824,,tagline 75-159 d,#1d2824,,tagline -|1: New Tty Find Grep Joincol Delcol -@1: 0-1 #ffffff,#887455,,tagline 2-2 d,#314738,,tagline 3-34 #becfc4,#314738,,tagline 35-159 d,#314738,,tagline -|2: /tmp/pardes-snap/collapse/cwd/kept.txt Save Tty Collapse Del -@2: 0-1 #000000,#add38a,,tagline 2-2 d,#314738,,tagline 3-32 #becfc4,#314738,,tagline 33-40 #dfbce5,#314738,,tagline 41-62 #becfc4,#314738,,tagline 63-159 d,#314738,,tagline +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +@0: 0-76 #b2c3b8,#1d2824,,tagline 77-159 d,#1d2824,,tagline +|1: New Tty Find Grep Joincol Delcol +@1: 0-1 #ffffff,#887455,,tagline 2-33 #becfc4,#314738,,tagline 34-159 d,#314738,,tagline +|2: /tmp/pardes-snap/collapse/cwd/kept.txt Save Tty Collapse Del +@2: 0-1 #000000,#add38a,,tagline 2-31 #becfc4,#314738,,tagline 32-39 #dfbce5,#314738,,tagline 40-61 #becfc4,#314738,,tagline 62-159 d,#314738,,tagline |3: @3: 0-159 d,#486152,,body |4: @@ -64,7 +64,7 @@ |3: 1 KEEP-FIRST Collapse |4: 2 KEEP-SECOND |5: 3 KEEP-THIRD -== snap tab-collapsed grid=160x25 cursor=51,2 +== snap tab-collapsed grid=160x25 cursor=50,2 |3: |4: |5: diff --git a/test/snapshots/cornerdrag-left.golden b/test/snapshots/cornerdrag-left.golden index a5f36319..4d2d6d43 100644 --- a/test/snapshots/cornerdrag-left.golden +++ b/test/snapshots/cornerdrag-left.golden @@ -1,13 +1,13 @@ == snap right-split grid=100x31 cursor=54,11 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash S /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash S -| ave Mode Filter Collapse Del ave Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash Sa /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash Sa +| ve Mode Filter Collapse Del ve Mode Filter Collapse Del | ls ls | w.txt w.txt | -| /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash S -| ave Mode Filter Collapse Del +| /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash Sa +| ve Mode Filter Collapse Del | ls | w.txt | @@ -16,19 +16,19 @@ | | | -| /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash S -| ave Mode Filter Collapse Del +| /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash Sa +| ve Mode Filter Collapse Del | ls | w.txt == snap hover-corner grid=100x31 cursor=54,11 -|1: New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol -|2: /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash ╎ /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash S -|3: ave Mode Filter Collapse Del ╎ ave Mode Filter Collapse Del +|1: New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash S╎ /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash Sa +|3: ve Mode Filter Collapse Del ╎ ve Mode Filter Collapse Del |4: ls ╎ ls |5: w.txt ╎ w.txt |6: ╎ -|7: ╎ /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash S -|8: ╎ ave Mode Filter Collapse Del +|7: ╎ /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash Sa +|8: ╎ ve Mode Filter Collapse Del |9: ╎ ls |10: ╎ w.txt |11: ╎ @@ -37,8 +37,8 @@ |14: ╎ |15: ╎ |16: ╎ -|17: /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash ╎ -|18: ave Mode Filter Collapse Del ╎ +|17: /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash S╎ +|18: ve Mode Filter Collapse Del ╎ |19: ls ╎ |20: w.txt ╎ |21: ╎ @@ -53,14 +53,14 @@ |30: ╎ == snap hover-left-corner grid=100x31 cursor=54,11 == snap corner-drag grid=100x31 cursor=54,11 -|1: New Tty Find Grep Joincol ╎elcol New Tty Find Grep Joincol Delcol -|2: /tmp/pardes-snap/cornerdra╎-left/cwd Tty+bash S /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash S -|3: ave Mode Filter Collapse D╎l ave Mode Filter Collapse Del +|1: New Tty Find Grep Joincol D╎lcol New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/cornerdrag╎left/cwd Tty+bash Sa /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash Sa +|3: ve Mode Filter Collapse Del╎ ve Mode Filter Collapse Del |4: ls ╎ ls |5: w.txt ╎ w.txt |6: ╎ -|7: ╎ /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash S -|8: ╎ ave Mode Filter Collapse Del +|7: ╎ /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash Sa +|8: ╎ ve Mode Filter Collapse Del |9: ╎ ls |10: ╎ w.txt |11: ╎ @@ -69,8 +69,8 @@ |14: ╎ |15: ╎ |16: ╎ -|17: /tmp/pardes-snap/cornerdra╎-left/cwd Tty+bash S -|18: ave Mode Filter Collapse D╎l +|17: /tmp/pardes-snap/cornerdrag╎left/cwd Tty+bash Sa +|18: ve Mode Filter Collapse Del╎ |19: ls ╎ |20: w.txt ╎ |21: ╎ @@ -84,14 +84,14 @@ |29: ╎ |30: ╎ == snap corner-done grid=100x31 cursor=34,11 -|1: New Tty Find Grep Joincol D New Tty Find Grep Joincol Delcol -|2: /tmp/pardes-snap/cornerdrag /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash Save Mode Filter Coll -|3: -left/cwd Tty+bash Save Mod apse Del -|4: e Filter Collapse Del ls +|1: New Tty Find Grep Joincol De New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/cornerdrag- /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash Save Mode Filter Colla +|3: left/cwd Tty+bash Save Mode pse Del +|4: Filter Collapse Del ls |5: ls w.txt |6: w.txt -|7: /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash Save Mode Filter Coll -|8: apse Del +|7: /tmp/pardes-snap/cornerdrag-left/cwd Tty+bash Save Mode Filter Colla +|8: pse Del |9: ls |10: w.txt |11: @@ -100,9 +100,9 @@ |14: |15: |16: -|17: /tmp/pardes-snap/cornerdrag -|18: -left/cwd Tty+bash Save Mod -|19: e Filter Collapse Del +|17: /tmp/pardes-snap/cornerdrag- +|18: left/cwd Tty+bash Save Mode +|19: Filter Collapse Del |20: ls |21: w.txt |22: diff --git a/test/snapshots/cornerdrag.golden b/test/snapshots/cornerdrag.golden index 8dd21eff..246840bc 100644 --- a/test/snapshots/cornerdrag.golden +++ b/test/snapshots/cornerdrag.golden @@ -1,8 +1,8 @@ == snap hover-corner grid=100x31 cursor=4,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save ╎ /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save M -| ode Filter Collapse Del ╎ ode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save M╎ /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mo +| de Filter Collapse Del ╎ de Filter Collapse Del | ls ╎ ls | w.txt ╎ w.txt | ╎ @@ -16,8 +16,8 @@ | ╎ | ╎ | ╎ -| /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save ╎ -| ode Filter Collapse Del ╎ +| /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save M╎ +| de Filter Collapse Del ╎ | ls ╎ | w.txt ╎ | ╎ @@ -31,9 +31,9 @@ | ╎ | ╎ == snap edge-drag grid=100x31 cursor=4,6 -|1: New Tty Find Grep Joincol ╎elcol New Tty Find Grep Joincol Delcol -|2: /tmp/pardes-snap/cornerdra╎/cwd Tty+bash Save M /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save M -|3: ode Filter Collapse Del ╎ ode Filter Collapse Del +|1: New Tty Find Grep Joincol D╎lcol New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/cornerdrag╎cwd Tty+bash Save Mo /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mo +|3: de Filter Collapse Del ╎ de Filter Collapse Del |4: ls ╎ ls |5: w.txt ╎ w.txt |6: ╎ @@ -47,8 +47,8 @@ |14: ╎ |15: ╎ |16: ╎ -|17: /tmp/pardes-snap/cornerdra╎/cwd Tty+bash Save M -|18: ode Filter Collapse Del ╎ +|17: /tmp/pardes-snap/cornerdrag╎cwd Tty+bash Save Mo +|18: de Filter Collapse Del ╎ |19: ls ╎ |20: w.txt ╎ |21: ╎ @@ -62,10 +62,10 @@ |29: ╎ |30: ╎ == snap edge-done grid=100x31 cursor=4,7 -|1: New Tty Find Grep Joincol D New Tty Find Grep Joincol Delcol -|2: /tmp/pardes-snap/cornerdrag /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mode Filter Collapse -|3: /cwd Tty+bash Save Mode Fil Del -|4: ter Collapse Del ls +|1: New Tty Find Grep Joincol De New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/cornerdrag/ /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mode Filter Collapse D +|3: cwd Tty+bash Save Mode Filte el +|4: r Collapse Del ls |5: ls w.txt |6: w.txt |7: @@ -78,9 +78,9 @@ |14: |15: |16: -|17: /tmp/pardes-snap/cornerdrag -|18: /cwd Tty+bash Save Mode Fil -|19: ter Collapse Del +|17: /tmp/pardes-snap/cornerdrag/ +|18: cwd Tty+bash Save Mode Filte +|19: r Collapse Del |20: ls |21: w.txt |22: @@ -93,10 +93,10 @@ |29: |30: == snap corner-drag grid=100x31 cursor=4,7 -|1: New Tty Find Grep Joincol D New Tty Find Grep Joincol ╎elcol -|2: /tmp/pardes-snap/cornerdrag /tmp/pardes-snap/cornerdra╎/cwd Tty+bash Save Mode Filter Collapse -|3: /cwd Tty+bash Save Mode Fil Del ╎ -|4: ter Collapse Del ls ╎ +|1: New Tty Find Grep Joincol De New Tty Find Grep Joincol D╎lcol +|2: /tmp/pardes-snap/cornerdrag/ /tmp/pardes-snap/cornerdrag╎cwd Tty+bash Save Mode Filter Collapse D +|3: cwd Tty+bash Save Mode Filte el ╎ +|4: r Collapse Del ls ╎ |5: ls w.txt ╎ |6: w.txt ╎ |7: ╎ @@ -109,9 +109,9 @@ |14: ╎ |15: ╎ |16: ╎ -|17: /tmp/pardes-snap/cornerdrag ╎ -|18: /cwd Tty+bash Save Mode Fil ╎ -|19: ter Collapse Del ╎ +|17: /tmp/pardes-snap/cornerdrag/ ╎ +|18: cwd Tty+bash Save Mode Filte ╎ +|19: r Collapse Del ╎ |20: ls ╎ |21: w.txt ╎ |22: ╎ @@ -124,16 +124,16 @@ |29: ╎ |30: ╎ == snap corner-done grid=100x31 cursor=4,6 -|1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -|2: /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mode Filter /tmp/pardes-snap/cornerdrag/cwd Tty+b -|3: Collapse Del ash Save Mode Filter Collapse Del +|1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mode Filter /tmp/pardes-snap/cornerdrag/cwd Tty+ba +|3: Collapse Del sh Save Mode Filter Collapse Del |4: ls ls |5: w.txt w.txt |6: |7: |8: -|9: /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mode Filter -|10: Collapse Del +|9: /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mode Filter +|10: Collapse Del |11: ls |12: w.txt |13: @@ -155,16 +155,16 @@ |29: |30: == snap clamp-x grid=100x31 cursor=4,6 -|1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol D╎lcol -|2: /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mode Filter /tmp/pardes-snap/cornerdrag╎cwd Tty+b -|3: Collapse Del ash Save Mode Filter Collap╎e Del +|1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol De╎col +|2: /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mode Filter /tmp/pardes-snap/cornerdrag/╎wd Tty+ba +|3: Collapse Del sh Save Mode Filter Collapse╎Del |4: ls ls ╎ |5: w.txt w.txt ╎ |6: ╎ |7: ╎ |8: ╎ -|9: /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mode Filter ╎ -|10: Collapse Del ╎ +|9: /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mode Filter ╎ +|10: Collapse Del ╎ |11: ls ╎ |12: w.txt ╎ |13: ╎ @@ -186,16 +186,16 @@ |29: ╎ |30: ╎ == snap clamp-y grid=100x31 cursor=4,6 -|1: New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol -|2: /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mode Filte╎ /tmp/pardes-snap/cornerdrag/cwd Tty+b -|3: Collapse Del ╎ ash Save Mode Filter Collapse Del +|1: New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mode Filter╎ /tmp/pardes-snap/cornerdrag/cwd Tty+ba +|3: Collapse Del ╎ sh Save Mode Filter Collapse Del |4: ls ╎ ls |5: w.txt ╎ w.txt |6: ╎ |7: ╎ |8: ╎ -|9: /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mode Filte╎ -|10: Collapse Del ╎ +|9: /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mode Filter╎ +|10: Collapse Del ╎ |11: ls ╎ |12: w.txt ╎ |13: ╎ @@ -217,9 +217,9 @@ |29: ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ |30: ╎ == snap clamp-done grid=100x31 cursor=4,6 -|1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -|2: /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mode Filter /tmp/pardes-snap/cornerdrag/cwd Tty+b -|3: Collapse Del ash Save Mode Filter Collapse Del +|1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mode Filter /tmp/pardes-snap/cornerdrag/cwd Tty+ba +|3: Collapse Del sh Save Mode Filter Collapse Del |4: ls ls |5: w.txt w.txt |6: @@ -243,7 +243,7 @@ |24: |25: |26: -|27: /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mode Filter -|28: Collapse Del +|27: /tmp/pardes-snap/cornerdrag/cwd Tty+bash Save Mode Filter +|28: Collapse Del |29: w.txt |30: diff --git a/test/snapshots/cursorline.golden b/test/snapshots/cursorline.golden index 6b99a30a..277565b3 100644 --- a/test/snapshots/cursorline.golden +++ b/test/snapshots/cursorline.golden @@ -1,11 +1,11 @@ == snap top grid=150x31 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/cursorline/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/cursorline/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/cursorline/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/cursorline/cwd Tty+bash Save Mode Filter Collapse Del | ls ls | cur.txt cur.txt | -| /tmp/pardes-snap/cursorline/cwd/cur.txt Save Tty Collapse Del +| /tmp/pardes-snap/cursorline/cwd/cur.txt Save Tty Collapse Del | 1 line 1 | 2 line 2 | 3 line 3 @@ -16,17 +16,17 @@ | 8 line 8 | 9 line 9 | 10 line 10 -| /tmp/pardes-snap/cursorline/cwd Tty+bash Save Mode Filter Collapse Del +| /tmp/pardes-snap/cursorline/cwd Tty+bash Save Mode Filter Collapse Del | ls | cur.txt == style top grid=150x31 -|0: 0-149 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-74 #becfc4,#314738, 75-76 #becfc4,#887455, 77-77 #becfc4,#1d2824, 78-149 #b2c3b8,#1d2824, -|2: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-43 #d3b0d9,#1d2824, 44-74 #b2c3b8,#1d2824, 75-76 #b2c3b8,#496656, 77-109 #b2c3b8,#1d2824, 110-118 #d3b0d9,#1d2824, 119-149 #b2c3b8,#1d2824, +|0: 0-1 d,#1d2824, 2-149 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-74 #becfc4,#314738, 75-76 #becfc4,#887455, 77-149 #b2c3b8,#1d2824, +|2: 0-1 d,#496656, 2-33 #b2c3b8,#1d2824, 34-42 #d3b0d9,#1d2824, 43-74 #b2c3b8,#1d2824, 75-76 #b2c3b8,#496656, 77-108 #b2c3b8,#1d2824, 109-117 #d3b0d9,#1d2824, 118-149 #b2c3b8,#1d2824, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, -|6: 0-1 d,#add38a, 2-2 d,#314738, 3-34 #becfc4,#314738, 35-42 #dfbce5,#314738, 43-74 #becfc4,#314738, 75-75 #becfc4,#608269, 76-149 #becfc4,#0d1410, +|6: 0-1 d,#add38a, 2-33 #becfc4,#314738, 34-41 #dfbce5,#314738, 42-74 #becfc4,#314738, 75-75 #becfc4,#608269, 76-149 #becfc4,#0d1410, |7: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |8: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |9: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, @@ -37,7 +37,7 @@ |14: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |15: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |16: 0-0 d,#152019, 1-3 d,#0d1410, 4-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, -|17: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-43 #d3b0d9,#1d2824, 44-74 #b2c3b8,#1d2824, 75-75 #b2c3b8,#608269, 76-149 #b2c3b8,#0d1410, +|17: 0-1 d,#496656, 2-33 #b2c3b8,#1d2824, 34-42 #d3b0d9,#1d2824, 43-74 #b2c3b8,#1d2824, 75-75 #b2c3b8,#608269, 76-149 #b2c3b8,#0d1410, |18: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |19: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |20: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, diff --git a/test/snapshots/delask.golden b/test/snapshots/delask.golden index d1487a36..7d911239 100644 --- a/test/snapshots/delask.golden +++ b/test/snapshots/delask.golden @@ -1,7 +1,7 @@ == snap three grid=100x36 cursor=18,20 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/delask/cwd/top.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/delask/cwd/top.txt Save Tty Collapse Del | 1 top-marker | | @@ -18,7 +18,7 @@ | | | -| * /tmp/pardes-snap/delask/cwd/+New Save Tty Collapse Del +| */tmp/pardes-snap/delask/cwd/+New Save Tty Collapse Del | 1 middle-pane | | @@ -27,7 +27,7 @@ | | | -| * /tmp/pardes-snap/delask/cwd/+New Save Tty Collapse Del +| */tmp/pardes-snap/delask/cwd/+New Save Tty Collapse Del | 1 bottom-pane Up == snap asked grid=100x36 cursor=18,20 |20: 1 middle-pane Del: give space to k above j below @@ -40,7 +40,7 @@ |29: == snap typed grid=100x36 cursor=27,20 |20: 1 bottom-pane DelBelow -|28: * /tmp/pardes-snap/delask/cwd/+New Save Tty Collapse Del +|28: */tmp/pardes-snap/delask/cwd/+New Save Tty Collapse Del |29: 1 third-pane == snap below-took-click grid=100x36 cursor=17,20 |20: 1 third-pane @@ -48,7 +48,7 @@ |29: == snap four grid=100x36 cursor=7,29 |3: 1 top-marker New -|28: /tmp/pardes-snap/delask/cwd/+New Save Tty Collapse Del +|28: /tmp/pardes-snap/delask/cwd/+New Save Tty Collapse Del |29: 1 == snap mouse-del grid=100x36 cursor=7,29 |3: 1 top-marker diff --git a/test/snapshots/diffview.golden b/test/snapshots/diffview.golden index 868e5e85..b4ce7759 100644 --- a/test/snapshots/diffview.golden +++ b/test/snapshots/diffview.golden @@ -1,7 +1,7 @@ == snap diff-pane grid=100x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/diffview/cwd/change.diff Save Tty Diff Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/diffview/cwd/change.diff Save Tty Diff Collapse Del | 1 diff --git a/src/shape.zig b/src/shape.zig | 2 index 1111111..2222222 100644 | 3 --- a/src/shape.zig @@ -23,9 +23,9 @@ | 19 }; | 20 == style diff-colours grid=100x31 -|0: 0-99 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-99 #becfc4,#314738, -|2: 0-1 d,#add38a, 2-2 d,#314738, 3-32 #becfc4,#314738, 33-44 #dfbce5,#314738, 45-99 #becfc4,#314738, +|0: 0-1 d,#1d2824, 2-99 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-99 #becfc4,#314738, +|2: 0-1 d,#add38a, 2-31 #becfc4,#314738, 32-43 #dfbce5,#314738, 44-99 #becfc4,#314738, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-99 #b9f480,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #b9f480,#0d1410, |5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #b9f480,#0d1410, @@ -55,7 +55,7 @@ |29: 0-0 d,#608269, 1-99 d,#0d1410, |30: 0-0 d,#608269, 1-99 d,#0d1410, == snap look-added-line grid=100x31 cursor=55,22 -|16: /tmp/pardes-snap/diffview/cwd/src/shape.zig Save Tty Collapse Del TreeContext Def Refs +|16: /tmp/pardes-snap/diffview/cwd/src/shape.zig Save Tty Collapse TreeContext Def Refs Del |17: 1 const std = @import("std"); |18: 2 |19: 3 pub const Shape = union(enum) { @@ -70,9 +70,9 @@ |28: 12 }; |29: 13 == snap command-pane grid=100x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/diffview/cwd/cmds.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/diffview/cwd/cmds.txt Save Tty Collapse Del | 1 cat change.diff Exec | 2 | @@ -87,7 +87,7 @@ | | | -| /tmp/pardes-snap/diffview/cwd (cat change.diff) exit 0 Kill Save Collapse Del +| /tmp/pardes-snap/diffview/cwd (cat change.diff) exit 0 Kill Save Collapse Del | circle: f32, | - square: u8 = 7, | + square: f32, @@ -101,9 +101,9 @@ | }; | exit 0 == style command-colours grid=100x31 -|0: 0-99 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-99 #becfc4,#314738, -|2: 0-1 d,#add38a, 2-2 d,#314738, 3-32 #becfc4,#314738, 33-41 #dfbce5,#314738, 42-99 #becfc4,#314738, +|0: 0-1 d,#1d2824, 2-99 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-99 #becfc4,#314738, +|2: 0-1 d,#add38a, 2-31 #becfc4,#314738, 32-40 #dfbce5,#314738, 41-99 #becfc4,#314738, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-93 #e5eee5,#0d1410, 94-94 #e5eee5,#1d2824, 95-99 #b2c3b8,#1d2824, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |5: 0-0 d,#608269, 1-99 d,#0d1410, @@ -118,7 +118,7 @@ |14: 0-0 d,#608269, 1-99 d,#0d1410, |15: 0-0 d,#608269, 1-99 d,#0d1410, |16: 0-0 d,#608269, 1-99 d,#0d1410, -|17: 0-1 d,#496656, 2-2 d,#1d2824, 3-99 #b2c3b8,#1d2824, +|17: 0-1 d,#496656, 2-99 #b2c3b8,#1d2824, |18: 0-0 d,#152019, 1-6 d,#0d1410, 7-99 #e5eee5,#0d1410, |19: 0-0 d,#152019, 1-1 d,#0d1410, 2-2 #f1a39b,#302b25,b 3-6 #f1a39b,#302b25, 7-19 #e5eee5,#302b25, 20-20 #f8c082,#302b25, 21-99 #e5eee5,#302b25, |20: 0-0 d,#152019, 1-1 d,#0d1410, 2-2 #b6ce94,#263025,b 3-6 #b6ce94,#263025, 7-99 #e5eee5,#263025, @@ -134,7 +134,7 @@ |30: 0-0 d,#152019, 1-99 d,#0d1410, == snap command-look grid=100x31 cursor=23,10 |3: 1 cat change.diff -|5: /tmp/pardes-snap/diffview/cwd/src/shape.zig Save Tty Collapse Del TreeContext Def Refs +|5: /tmp/pardes-snap/diffview/cwd/src/shape.zig Save Tty Collapse TreeContext Def Refs Del |6: 1 const std = @import("std"); |7: 2 |8: 3 pub const Shape = union(enum) { diff --git a/test/snapshots/dirpane.golden b/test/snapshots/dirpane.golden index 3118079f..960c8913 100644 --- a/test/snapshots/dirpane.golden +++ b/test/snapshots/dirpane.golden @@ -1,13 +1,13 @@ == snap dir-open grid=80x24 cursor=7,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/dirpane/cwd/top.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/dirpane/cwd/top.txt Save Tty Collapse Del | 1 sub | -| /tmp/pardes-snap/dirpane/cwd/sub/ Get Tty Collapse Del +| /tmp/pardes-snap/dirpane/cwd/sub/ Get Tty Collapse Del | 1 .hidden beta-gamma.txt inner.txt | 2 alpha.txt deeper/ zeta | 3 == snap entry-open grid=80x24 cursor=7,9 -|8: /tmp/pardes-snap/dirpane/cwd/sub/inner.txt Save Tty Collapse Del +|8: /tmp/pardes-snap/dirpane/cwd/sub/inner.txt Save Tty Collapse Del |9: 1 inner-marker diff --git a/test/snapshots/doccol.golden b/test/snapshots/doccol.golden index 21424456..0d71dffa 100644 --- a/test/snapshots/doccol.golden +++ b/test/snapshots/doccol.golden @@ -1,25 +1,25 @@ == snap boot grid=100x31 cursor=7,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/doccol/cwd/a.txt Save Tty Coll /tmp/pardes-snap/doccol/cwd Tty+bash Save Mode -| apse Del Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/doccol/cwd/a.txt Save Tty Colla /tmp/pardes-snap/doccol/cwd Tty+bash Save Mode F +| pse Del ilter Collapse Del | 1 AAA ls | a.txt b.txt c.txt == snap two-docs grid=100x31 cursor=7,19 -|17: /tmp/pardes-snap/doccol/cwd/b.txt Save Tty Coll -|18: apse Del +|17: /tmp/pardes-snap/doccol/cwd/b.txt Save Tty Colla +|18: pse Del |19: 1 BBB |20: 2 B-TWO == snap moved grid=100x31 cursor=57,22 |17: |18: |19: -|20: /tmp/pardes-snap/doccol/cwd/b.txt Save Tty Coll -|21: apse Del +|20: /tmp/pardes-snap/doccol/cwd/b.txt Save Tty Colla +|21: pse Del |22: 1 BBB |23: 2 B-TWO == snap worked grid=100x31 cursor=59,23 == snap third grid=100x31 cursor=57,28 -|26: /tmp/pardes-snap/doccol/cwd/c.txt Save Tty Coll -|27: apse Del +|26: /tmp/pardes-snap/doccol/cwd/c.txt Save Tty Colla +|27: pse Del |28: 1 CCC diff --git a/test/snapshots/edit.golden b/test/snapshots/edit.golden index aa39ed9c..2ac4dfcf 100644 --- a/test/snapshots/edit.golden +++ b/test/snapshots/edit.golden @@ -1,8 +1,8 @@ == snap inserted grid=100x31 cursor=16,10 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/edit/cwd Tty+bash Save Mode Fi /tmp/pardes-snap/edit/cwd Tty+bash Save Mode Fi -| lter Collapse Del lter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/edit/cwd Tty+bash Save Mode Fil /tmp/pardes-snap/edit/cwd Tty+bash Save Mode Fil +| ter Collapse Del ter Collapse Del | ls ls | e.txt e.txt | @@ -16,15 +16,15 @@ | | | -| /tmp/pardes-snap/edit/cwd Tty+bash Save Mode Fi -| lter Collapse Del +| /tmp/pardes-snap/edit/cwd Tty+bash Save Mode Fil +| ter Collapse Del | ls | e.txt == style inserted grid=100x31 -|0: 0-99 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-49 #becfc4,#314738, 50-51 #becfc4,#887455, 52-52 #becfc4,#1d2824, 53-99 #b2c3b8,#1d2824, -|2: 0-1 d,#add38a, 2-2 d,#314738, 3-28 #becfc4,#314738, 29-37 #dfbce5,#314738, 38-49 #becfc4,#314738, 50-51 #becfc4,#496656, 52-52 #becfc4,#1d2824, 53-78 #b2c3b8,#1d2824, 79-87 #d3b0d9,#1d2824, 88-99 #b2c3b8,#1d2824, -|3: 0-2 d,#314738, 3-49 #becfc4,#314738, 50-52 #becfc4,#1d2824, 53-99 #b2c3b8,#1d2824, +|0: 0-1 d,#1d2824, 2-99 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-49 #becfc4,#314738, 50-51 #becfc4,#887455, 52-99 #b2c3b8,#1d2824, +|2: 0-1 d,#add38a, 2-27 #becfc4,#314738, 28-36 #dfbce5,#314738, 37-49 #becfc4,#314738, 50-51 #becfc4,#496656, 52-77 #b2c3b8,#1d2824, 78-86 #d3b0d9,#1d2824, 87-99 #b2c3b8,#1d2824, +|3: 0-1 d,#314738, 2-49 #becfc4,#314738, 50-51 #becfc4,#1d2824, 52-99 #b2c3b8,#1d2824, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 #e5eee5,#608269, 51-99 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 #e5eee5,#608269, 51-99 #e5eee5,#0d1410, |6: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-99 d,#0d1410, @@ -38,8 +38,8 @@ |14: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-99 d,#0d1410, |15: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-99 d,#0d1410, |16: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-99 d,#0d1410, -|17: 0-1 d,#496656, 2-2 d,#1d2824, 3-28 #b2c3b8,#1d2824, 29-37 #d3b0d9,#1d2824, 38-49 #b2c3b8,#1d2824, 50-50 #b2c3b8,#608269, 51-99 #b2c3b8,#0d1410, -|18: 0-2 d,#1d2824, 3-49 #b2c3b8,#1d2824, 50-50 #b2c3b8,#608269, 51-99 #b2c3b8,#0d1410, +|17: 0-1 d,#496656, 2-27 #b2c3b8,#1d2824, 28-36 #d3b0d9,#1d2824, 37-49 #b2c3b8,#1d2824, 50-50 #b2c3b8,#608269, 51-99 #b2c3b8,#0d1410, +|18: 0-1 d,#1d2824, 2-49 #b2c3b8,#1d2824, 50-50 #b2c3b8,#608269, 51-99 #b2c3b8,#0d1410, |19: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 #e5eee5,#608269, 51-99 #e5eee5,#0d1410, |20: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 #e5eee5,#608269, 51-99 #e5eee5,#0d1410, |21: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-99 d,#0d1410, diff --git a/test/snapshots/emptycol.golden b/test/snapshots/emptycol.golden index 9bac8492..bd00a2cd 100644 --- a/test/snapshots/emptycol.golden +++ b/test/snapshots/emptycol.golden @@ -1,17 +1,17 @@ -== snap newcol grid=100x24 cursor=53,1 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/emptycol/cwd/notes.txt Save Tt -| y Collapse Del +== snap newcol grid=100x24 cursor=52,1 +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/emptycol/cwd/notes.txt Save Tty +| Collapse Del | 1 one | 2 two == snap filled grid=100x24 cursor=54,6 -|2: /tmp/pardes-snap/emptycol/cwd/notes.txt Save Tt /tmp/pardes-snap/emptycol/cwd Tty+bash Save Mod -|3: y Collapse Del e Filter Collapse Del +|2: /tmp/pardes-snap/emptycol/cwd/notes.txt Save Tty /tmp/pardes-snap/emptycol/cwd Tty+bash Save Mode +|3: Collapse Del Filter Collapse Del |4: 1 one ls |5: 2 two notes.txt -== snap emptied grid=100x24 cursor=53,1 -|2: /tmp/pardes-snap/emptycol/cwd/notes.txt Save Tt -|3: y Collapse Del +== snap emptied grid=100x24 cursor=52,1 +|2: /tmp/pardes-snap/emptycol/cwd/notes.txt Save Tty +|3: Collapse Del |4: 1 one |5: 2 two diff --git a/test/snapshots/exec-bigdrag.golden b/test/snapshots/exec-bigdrag.golden index a2ac6610..f3cd71b1 100644 --- a/test/snapshots/exec-bigdrag.golden +++ b/test/snapshots/exec-bigdrag.golden @@ -1,7 +1,7 @@ == snap alive grid=200x61 cursor=119,38 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/exec-bigdrag/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/exec-bigdrag/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/exec-bigdrag/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/exec-bigdrag/cwd Tty+bash Save Mode Filter Collapse Del | ls 2 | big.txt bash: 91line: command not found | 802line 2803line 2804line 2805line 2806line 2807line 2808line 2809line 2810line 2811line 2812lin @@ -31,7 +31,7 @@ | 89line 2890line 2891line 2892line 2893line 2894line 2895line 2896line 2897line 2898line 2899line | 2 | bash: 89line: command not found -| /tmp/pardes-snap/exec-bigdrag/cwd Tty+bash Save Mode Filter Collapse Del 900line 2901line 2902line 2903line 2904line 2905line 2906line 2907line 2908line 2909line 2910lin +| /tmp/pardes-snap/exec-bigdrag/cwd Tty+bash Save Mode Filter Collapse Del 900line 2901line 2902line 2903line 2904line 2905line 2906line 2907line 2908line 2909line 2910lin | ls e | big.txt bash: 900line: command not found | 2911line 2912line 2913line 2914line 2915line 2916line 2917line 2918line 2919line 2920line 2921li diff --git a/test/snapshots/exec.golden b/test/snapshots/exec.golden index a9f8716e..df49336c 100644 --- a/test/snapshots/exec.golden +++ b/test/snapshots/exec.golden @@ -1,7 +1,7 @@ == snap exec grid=140x31 cursor=16,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/exec/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/exec/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/exec/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/exec/cwd Tty+bash Save Mode Filter Collapse Del | ls Exec ls | e.txt e.txt | @@ -16,7 +16,7 @@ | | | -| /tmp/pardes-snap/exec/cwd Tty+bash Save Mode Filter Collapse Del +| /tmp/pardes-snap/exec/cwd Tty+bash Save Mode Filter Collapse Del | ls | e.txt == snap kept grid=140x31 cursor=6,3 diff --git a/test/snapshots/fileedit.golden b/test/snapshots/fileedit.golden index 5ba6e18a..b484177b 100644 --- a/test/snapshots/fileedit.golden +++ b/test/snapshots/fileedit.golden @@ -1,11 +1,11 @@ == snap edited grid=150x31 cursor=17,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/fileedit/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/fileedit/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/fileedit/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/fileedit/cwd Tty+bash Save Mode Filter Collapse Del | ls ls | f.txt f.txt | -| * /tmp/pardes-snap/fileedit/cwd/f.txt Save Tty Collapse Del +| */tmp/pardes-snap/fileedit/cwd/f.txt Save Tty Collapse Del | 1 liEDIT''MEne 1 | 2 line 2 | 3 line 3 @@ -16,7 +16,7 @@ | 8 line 8 | 9 line 9 | 10 line 10 -| /tmp/pardes-snap/fileedit/cwd Tty+bash Save Mode Filter Collapse Del +| /tmp/pardes-snap/fileedit/cwd Tty+bash Save Mode Filter Collapse Del | ls | f.txt == snap deleted grid=150x31 cursor=7,8 diff --git a/test/snapshots/filewatch.golden b/test/snapshots/filewatch.golden index 36f51582..ebd68fee 100644 --- a/test/snapshots/filewatch.golden +++ b/test/snapshots/filewatch.golden @@ -1,11 +1,11 @@ == snap edited grid=210x31 cursor=15,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/filewatch/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/filewatch/cwd Tty+bash Save Mode Filter Collapse Del | ls | sub w.txt | -| * /tmp/pardes-snap/filewatch/cwd/w.txt Save Tty Collapse Del +| */tmp/pardes-snap/filewatch/cwd/w.txt Save Tty Collapse Del | 1 liMYEDITne 1 | 2 line 2 | 3 /tmp/pardes-snap/filewatch/cwd/sub/s.txt @@ -18,7 +18,7 @@ | 10 line 10 | 11 line 11 | 12 line 12 -| /tmp/pardes-snap/filewatch/cwd/sub/s.txt Save Tty Collapse Del +| /tmp/pardes-snap/filewatch/cwd/sub/s.txt Save Tty Collapse Del | 1 line 1 | 2 line 2 | 3 line 3 diff --git a/test/snapshots/find.golden b/test/snapshots/find.golden index c9c6b755..47480b83 100644 --- a/test/snapshots/find.golden +++ b/test/snapshots/find.golden @@ -1,7 +1,7 @@ == snap group grid=120x41 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/find/cwd/here.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/find/cwd/here.txt Save Tty Collapse Del | 1 Find SPC f == snap armed grid=120x41 cursor=119,4 |3: 1 Find Find @@ -11,25 +11,25 @@ |4: == snap results grid=120x41 cursor=7,3 |3: 1 Find -|5: /tmp/pardes-snap/find/cwd/+Search Save Tty Collapse Del +|5: /tmp/pardes-snap/find/cwd/+Search Save Tty Collapse Del |6: 1 sub/ZQMARK-beta.txt |7: 2 sub/nest/zqmark-gamma.txt |8: 3 zqmark-alpha.txt |9: 4 == snap first grid=120x41 cursor=7,10 -|9: /tmp/pardes-snap/find/cwd/sub/ZQMARK-beta.txt Save Tty Collapse Del +|9: /tmp/pardes-snap/find/cwd/sub/ZQMARK-beta.txt Save Tty Collapse Del |10: 1 beta body == style first grid=120x41 -|0: 0-119 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-119 #becfc4,#314738, -|2: 0-1 d,#496656, 2-2 d,#1d2824, 3-28 #b2c3b8,#1d2824, 29-37 #d3b0d9,#1d2824, 38-119 #b2c3b8,#1d2824, +|0: 0-1 d,#1d2824, 2-119 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-119 #becfc4,#314738, +|2: 0-1 d,#496656, 2-27 #b2c3b8,#1d2824, 28-36 #d3b0d9,#1d2824, 37-119 #b2c3b8,#1d2824, |3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-119 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-119 d,#0d1410, -|5: 0-1 d,#496656, 2-2 d,#1d2824, 3-28 #b2c3b8,#1d2824, 29-36 #d3b0d9,#1d2824, 37-119 #b2c3b8,#1d2824, +|5: 0-1 d,#496656, 2-27 #b2c3b8,#1d2824, 28-35 #d3b0d9,#1d2824, 36-119 #b2c3b8,#1d2824, |6: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-119 #e5eee5,#0d1410, |7: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-119 #e5eee5,#0d1410, |8: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-119 #e5eee5,#0d1410, -|9: 0-1 d,#add38a, 2-2 d,#314738, 3-32 #becfc4,#314738, 33-48 #dfbce5,#314738, 49-119 #becfc4,#314738, +|9: 0-1 d,#add38a, 2-31 #becfc4,#314738, 32-47 #dfbce5,#314738, 48-119 #becfc4,#314738, |10: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-119 #e5eee5,#0d1410, |11: 0-0 d,#608269, 1-119 d,#0d1410, |12: 0-0 d,#608269, 1-119 d,#0d1410, @@ -62,10 +62,10 @@ |39: 0-0 d,#608269, 1-119 d,#0d1410, |40: 0-0 d,#608269, 1-119 d,#0d1410, == snap second grid=120x41 cursor=7,13 -|12: /tmp/pardes-snap/find/cwd/sub/nest/zqmark-gamma.txt Save Tty Collapse Del +|12: /tmp/pardes-snap/find/cwd/sub/nest/zqmark-gamma.txt Save Tty Collapse Del |13: 1 gamma body == snap third grid=120x41 cursor=7,16 -|15: /tmp/pardes-snap/find/cwd/zqmark-alpha.txt Save Tty Collapse Del +|15: /tmp/pardes-snap/find/cwd/zqmark-alpha.txt Save Tty Collapse Del |16: 1 alpha body == snap back grid=120x41 cursor=7,13 == snap word grid=120x41 cursor=7,13 diff --git a/test/snapshots/fsearch.golden b/test/snapshots/fsearch.golden index 7ba94492..62c37c25 100644 --- a/test/snapshots/fsearch.golden +++ b/test/snapshots/fsearch.golden @@ -1,11 +1,11 @@ == snap opened grid=180x31 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/fsearch/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/fsearch/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/fsearch/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/fsearch/cwd Tty+bash Save Mode Filter Collapse Del | ls ls | g.txt g.txt | -| /tmp/pardes-snap/fsearch/cwd/g.txt Save Tty Collapse Del +| /tmp/pardes-snap/fsearch/cwd/g.txt Save Tty Collapse Del | 1 l1 | 2 MARK a | 3 l3 @@ -16,14 +16,14 @@ | 8 l8 | 9 l9 | 10 MARK c -| /tmp/pardes-snap/fsearch/cwd Tty+bash Save Mode Filter Collapse Del +| /tmp/pardes-snap/fsearch/cwd Tty+bash Save Mode Filter Collapse Del | ls | g.txt == snap typing grid=180x31 cursor=89,7 |7: 1 l1 /MARK == snap results grid=180x31 cursor=10,8 |7: 1 l1 -|21: /tmp/pardes-snap/fsearch/cwd/+Search Save Tty Collapse Del LocationsConfig +|21: /tmp/pardes-snap/fsearch/cwd/+Search Save Tty Collapse LocationsConfig Del |22: 1 g.txt:2:1-4 |23: 2 MARK a |24: 3 g.txt:6:1-4 @@ -32,13 +32,13 @@ |27: 6 MARK c |28: 7 == style results grid=180x31 -|0: 0-179 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-89 #becfc4,#314738, 90-91 #becfc4,#887455, 92-92 #becfc4,#1d2824, 93-179 #b2c3b8,#1d2824, -|2: 0-1 d,#496656, 2-2 d,#1d2824, 3-31 #b2c3b8,#1d2824, 32-40 #d3b0d9,#1d2824, 41-89 #b2c3b8,#1d2824, 90-91 #b2c3b8,#496656, 92-121 #b2c3b8,#1d2824, 122-130 #d3b0d9,#1d2824, 131-179 #b2c3b8,#1d2824, +|0: 0-1 d,#1d2824, 2-179 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-89 #becfc4,#314738, 90-91 #becfc4,#887455, 92-179 #b2c3b8,#1d2824, +|2: 0-1 d,#496656, 2-30 #b2c3b8,#1d2824, 31-39 #d3b0d9,#1d2824, 40-89 #b2c3b8,#1d2824, 90-91 #b2c3b8,#496656, 92-120 #b2c3b8,#1d2824, 121-129 #d3b0d9,#1d2824, 130-179 #b2c3b8,#1d2824, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|6: 0-1 d,#add38a, 2-2 d,#314738, 3-31 #becfc4,#314738, 32-37 #dfbce5,#314738, 38-89 #becfc4,#314738, 90-90 #becfc4,#608269, 91-179 #becfc4,#0d1410, +|6: 0-1 d,#add38a, 2-30 #becfc4,#314738, 31-36 #dfbce5,#314738, 37-89 #becfc4,#314738, 90-90 #becfc4,#608269, 91-179 #becfc4,#0d1410, |7: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |8: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #f5f7ee,#3c614a, 11-11 #f5f7ee,#0d1410, 12-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |9: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, @@ -49,11 +49,11 @@ |14: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |15: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |16: 0-0 d,#152019, 1-3 d,#0d1410, 4-6 #59675c,#0d1410, 7-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, -|17: 0-1 d,#496656, 2-2 d,#1d2824, 3-31 #b2c3b8,#1d2824, 32-40 #d3b0d9,#1d2824, 41-89 #b2c3b8,#1d2824, 90-90 #b2c3b8,#608269, 91-179 #b2c3b8,#0d1410, +|17: 0-1 d,#496656, 2-30 #b2c3b8,#1d2824, 31-39 #d3b0d9,#1d2824, 40-89 #b2c3b8,#1d2824, 90-90 #b2c3b8,#608269, 91-179 #b2c3b8,#0d1410, |18: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |19: 0-0 d,#608269, 1-1 d,#0d1410, 2-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |20: 0-0 d,#608269, 1-89 d,#0d1410, 90-90 d,#608269, 91-179 d,#0d1410, -|21: 0-1 d,#496656, 2-2 d,#1d2824, 3-31 #b2c3b8,#1d2824, 32-39 #d3b0d9,#1d2824, 40-89 #b2c3b8,#1d2824, 90-90 #b2c3b8,#608269, 91-179 #b2c3b8,#0d1410, +|21: 0-1 d,#496656, 2-30 #b2c3b8,#1d2824, 31-38 #d3b0d9,#1d2824, 39-89 #b2c3b8,#1d2824, 90-90 #b2c3b8,#608269, 91-179 #b2c3b8,#0d1410, |22: 0-0 d,#608269, 1-4 d,#0d1410, 5-89 #59675c,#0d1410, 90-90 #59675c,#608269, 91-179 #59675c,#0d1410, |23: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f7e4a5,#5e4923, 11-11 #f7e4a5,#0d1410, 12-89 #e5eee5,#0d1410, 90-90 #e5eee5,#608269, 91-179 #e5eee5,#0d1410, |24: 0-0 d,#608269, 1-4 d,#0d1410, 5-89 #59675c,#0d1410, 90-90 #59675c,#608269, 91-179 #59675c,#0d1410, @@ -88,7 +88,7 @@ |16: 10 MARK c == snap cancel grid=180x31 cursor=10,12 == snap nomatch grid=180x31 cursor=7,26 -|11: /tmp/pardes-snap/fsearch/cwd/+Search Save Tty Collapse Del LocationsConfig +|11: /tmp/pardes-snap/fsearch/cwd/+Search Save Tty Collapse LocationsConfig Del |12: 1 |13: |14: diff --git a/test/snapshots/ghostty-mid.golden b/test/snapshots/ghostty-mid.golden index 4bd8bf1f..6f61736e 100644 --- a/test/snapshots/ghostty-mid.golden +++ b/test/snapshots/ghostty-mid.golden @@ -1,8 +1,8 @@ == snap ghostty-mid grid=100x31 cursor=4,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/ghostty-mid/cwd Tty+bash Save /tmp/pardes-snap/ghostty-mid/cwd Tty+bash Save -| Mode Filter Collapse Del Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/ghostty-mid/cwd Tty+bash Save M /tmp/pardes-snap/ghostty-mid/cwd Tty+bash Save M +| ode Filter Collapse Del ode Filter Collapse Del | ZZPAD ls | ./g.sh g.txt | ./g.sh @@ -16,7 +16,7 @@ | | | -| /tmp/pardes-snap/ghostty-mid/cwd Tty+bash Save -| Mode Filter Collapse Del +| /tmp/pardes-snap/ghostty-mid/cwd Tty+bash Save M +| ode Filter Collapse Del | ls | g.txt diff --git a/test/snapshots/grep.golden b/test/snapshots/grep.golden index 687d7099..957096c3 100644 --- a/test/snapshots/grep.golden +++ b/test/snapshots/grep.golden @@ -1,11 +1,11 @@ == snap opened grid=180x31 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/grep/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/grep/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/grep/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/grep/cwd Tty+bash Save Mode Filter Collapse Del | ls ls | a.txt noise.txt sub a.txt noise.txt sub | -| /tmp/pardes-snap/grep/cwd/a.txt Save Tty Collapse Del +| /tmp/pardes-snap/grep/cwd/a.txt Save Tty Collapse Del | 1 hello TARGET one | 2 nothing here | 3 last TARGET line @@ -16,25 +16,25 @@ | | | -| /tmp/pardes-snap/grep/cwd Tty+bash Save Mode Filter Collapse Del +| /tmp/pardes-snap/grep/cwd Tty+bash Save Mode Filter Collapse Del | ls | a.txt noise.txt sub == snap typing grid=180x31 cursor=89,7 |7: 1 hello TARGET one Grep /TARGET == snap results grid=180x31 cursor=7,7 |7: 1 hello TARGET one -|21: /tmp/pardes-snap/grep/cwd/+Search Save Tty Collapse Del LocationsConfig +|21: /tmp/pardes-snap/grep/cwd/+Search Save Tty Collapse LocationsConfig Del |22: 1 a.txt:1:7-12 hello TARGET one |23: 2 a.txt:3:6-11 last TARGET line |24: 3 sub/b.txt:2:1-6 TARGET inside sub |25: 4 == snap first grid=180x31 cursor=18,7 == snap opened-hit grid=180x31 cursor=12,12 -|10: /tmp/pardes-snap/grep/cwd/sub/b.txt Save Tty Collapse Del +|10: /tmp/pardes-snap/grep/cwd/sub/b.txt Save Tty Collapse Del |11: 1 deep |12: 2 TARGET inside sub == snap nomatch grid=180x31 cursor=2,4 -|25: /tmp/pardes-snap/grep/cwd/sub/+Search Save Tty Collapse Del LocationsConfig +|25: /tmp/pardes-snap/grep/cwd/sub/+Search Save Tty Collapse LocationsConfig Del |26: 1 == snap chordsel grid=180x31 cursor=19,7 == snap chord grid=180x31 cursor=19,7 diff --git a/test/snapshots/headersweep-restored.golden b/test/snapshots/headersweep-restored.golden index 176520dd..522945bd 100644 --- a/test/snapshots/headersweep-restored.golden +++ b/test/snapshots/headersweep-restored.golden @@ -1,8 +1,8 @@ == style col-sweeping grid=120x21 -|0: 0-119 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-35 #becfc4,#314738, 36-43 #f5f7ee,#5b7e5a, 44-59 #becfc4,#314738, 60-61 #becfc4,#887455, 62-62 #becfc4,#1d2824, 63-119 #b2c3b8,#1d2824, -|2: 0-1 d,#add38a, 2-2 d,#314738, 3-44 #becfc4,#314738, 45-53 #dfbce5,#314738, 54-59 #becfc4,#314738, 60-61 #becfc4,#496656, 62-62 #becfc4,#1d2824, 63-104 #b2c3b8,#1d2824, 105-113 #d3b0d9,#1d2824, 114-119 #b2c3b8,#1d2824, -|3: 0-2 d,#314738, 3-59 #becfc4,#314738, 60-62 #becfc4,#1d2824, 63-119 #b2c3b8,#1d2824, +|0: 0-1 d,#1d2824, 2-119 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-34 #becfc4,#314738, 35-42 #f5f7ee,#5b7e5a, 43-59 #becfc4,#314738, 60-61 #becfc4,#887455, 62-119 #b2c3b8,#1d2824, +|2: 0-1 d,#add38a, 2-43 #becfc4,#314738, 44-52 #dfbce5,#314738, 53-59 #becfc4,#314738, 60-61 #becfc4,#496656, 62-103 #b2c3b8,#1d2824, 104-112 #d3b0d9,#1d2824, 113-119 #b2c3b8,#1d2824, +|3: 0-1 d,#314738, 2-59 #becfc4,#314738, 60-61 #becfc4,#1d2824, 62-119 #b2c3b8,#1d2824, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, |6: 0-0 d,#608269, 1-1 d,#0d1410, 2-23 #e5eee5,#0d1410,f 24-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-61 #e5eee5,#0d1410, 62-83 #e5eee5,#0d1410,f 84-119 #e5eee5,#0d1410, @@ -11,8 +11,8 @@ |9: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, |10: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, |11: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, -|12: 0-1 d,#496656, 2-2 d,#1d2824, 3-44 #b2c3b8,#1d2824, 45-53 #d3b0d9,#1d2824, 54-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, -|13: 0-2 d,#1d2824, 3-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, +|12: 0-1 d,#496656, 2-43 #b2c3b8,#1d2824, 44-52 #d3b0d9,#1d2824, 53-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, +|13: 0-1 d,#1d2824, 2-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, |14: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, |15: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, |16: 0-0 d,#608269, 1-1 d,#0d1410, 2-23 #e5eee5,#0d1410,f 24-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, @@ -21,10 +21,10 @@ |19: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, |20: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, == snap col-swept grid=120x21 cursor=4,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit Restore /tmp/pardes-snap/headersweep-restore -| New Tty Find Grep Joincol Delcol echo RE''STORED-COL New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/headersweep-restored/cwd Tty+bash Save M /tmp/pardes-snap/headersweep-restored/cwd Tty+bash Save M -| ode Filter Collapse Del ode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit Restore /tmp/pardes-snap/headersweep-resto +| New Tty Find Grep Joincol Delcol echo RE''STORED-COL New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/headersweep-restored/cwd Tty+bash Save Mo /tmp/pardes-snap/headersweep-restored/cwd Tty+bash Save Mo +| de Filter Collapse Del de Filter Collapse Del | $ ls $ ls | $ $ | ── restored history ── ── restored history ── @@ -33,22 +33,22 @@ | | | -| /tmp/pardes-snap/headersweep-restored/cwd Tty+bash Save M -| ode Filter Collapse Del +| /tmp/pardes-snap/headersweep-restored/cwd Tty+bash Save Mo +| de Filter Collapse Del | $ | ── restored history ── | -| /tmp/pardes-snap/headersweep-restored/cwd (echo RE''STORE -| D-COL) exit 0 Kill Save Collapse Del +| /tmp/pardes-snap/headersweep-restored/cwd (echo RE''STORED +| -COL) exit 0 Kill Save Collapse Del | exit 0 == style ws-sweeping grid=120x21 -|0: 0-100 #b2c3b8,#1d2824, 101-108 #f5f7ee,#5b7e5a, 109-119 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-59 #becfc4,#314738, 60-61 #becfc4,#887455, 62-62 #becfc4,#1d2824, 63-119 #b2c3b8,#1d2824, +|0: 0-1 d,#1d2824, 2-100 #b2c3b8,#1d2824, 101-108 #f5f7ee,#5b7e5a, 109-119 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-59 #becfc4,#314738, 60-61 #becfc4,#887455, 62-119 #b2c3b8,#1d2824, |15: 0-0 d,#608269, 1-1 d,#0d1410, 2-23 #e5eee5,#0d1410,f 24-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, |16: 0-0 d,#152019, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, -|17: 0-1 d,#496656, 2-2 d,#1d2824, 3-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, -|18: 0-2 d,#1d2824, 3-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, +|17: 0-1 d,#496656, 2-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, +|18: 0-1 d,#1d2824, 2-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, |19: 0-0 d,#152019, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, == snap ws-swept grid=120x21 cursor=4,7 -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit Restore /tmp/pardes-snap/headersweep-rest ec -|18: D-WS) exit 0 Kill Save Collapse Del +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit Restore /tmp/pardes-snap/headersweep-re ec +|18: -WS) exit 0 Kill Save Collapse Del diff --git a/test/snapshots/headersweep.golden b/test/snapshots/headersweep.golden index c22120ca..a178306f 100644 --- a/test/snapshots/headersweep.golden +++ b/test/snapshots/headersweep.golden @@ -1,7 +1,7 @@ == style col-sweeping grid=120x21 -|0: 0-119 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-35 #becfc4,#314738, 36-43 #f5f7ee,#5b7e5a, 44-59 #becfc4,#314738, 60-61 #becfc4,#887455, 62-62 #becfc4,#1d2824, 63-119 #b2c3b8,#1d2824, -|2: 0-1 d,#add38a, 2-2 d,#314738, 3-35 #becfc4,#314738, 36-44 #dfbce5,#314738, 45-59 #becfc4,#314738, 60-61 #becfc4,#496656, 62-62 #becfc4,#1d2824, 63-95 #b2c3b8,#1d2824, 96-104 #d3b0d9,#1d2824, 105-119 #b2c3b8,#1d2824, +|0: 0-1 d,#1d2824, 2-119 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-34 #becfc4,#314738, 35-42 #f5f7ee,#5b7e5a, 43-59 #becfc4,#314738, 60-61 #becfc4,#887455, 62-119 #b2c3b8,#1d2824, +|2: 0-1 d,#add38a, 2-34 #becfc4,#314738, 35-43 #dfbce5,#314738, 44-59 #becfc4,#314738, 60-61 #becfc4,#496656, 62-94 #b2c3b8,#1d2824, 95-103 #d3b0d9,#1d2824, 104-119 #b2c3b8,#1d2824, |3: 0-2 d,#314738, 3-59 #becfc4,#314738, 60-62 #becfc4,#1d2824, 63-119 #b2c3b8,#1d2824, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, @@ -11,7 +11,7 @@ |9: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, |10: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, |11: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, -|12: 0-1 d,#496656, 2-2 d,#1d2824, 3-35 #b2c3b8,#1d2824, 36-44 #d3b0d9,#1d2824, 45-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, +|12: 0-1 d,#496656, 2-34 #b2c3b8,#1d2824, 35-43 #d3b0d9,#1d2824, 44-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, |13: 0-2 d,#1d2824, 3-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, |14: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, |15: 0-0 d,#608269, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, @@ -21,10 +21,10 @@ |19: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, |20: 0-0 d,#608269, 1-59 d,#0d1410, 60-60 d,#608269, 61-119 d,#0d1410, == snap col-swept grid=120x21 cursor=4,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol echo SW''EPT-COL New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/headersweep/cwd Tty+bash Save Mode Filte /tmp/pardes-snap/headersweep/cwd Tty+bash Save Mode Filte -| r Collapse Del r Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol echo SW''EPT-COL New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/headersweep/cwd Tty+bash Save Mode Filter /tmp/pardes-snap/headersweep/cwd Tty+bash Save Mode Filter +| Collapse Del Collapse Del | ls ls | hay.txt hay.txt | @@ -33,31 +33,31 @@ | | | -| /tmp/pardes-snap/headersweep/cwd Tty+bash Save Mode Filte -| r Collapse Del +| /tmp/pardes-snap/headersweep/cwd Tty+bash Save Mode Filter +| Collapse Del | ls | hay.txt | -| /tmp/pardes-snap/headersweep/cwd (echo SW''EPT-COL) exit -| 0 Kill Save Collapse Del +| /tmp/pardes-snap/headersweep/cwd (echo SW''EPT-COL) exit 0 +| Kill Save Collapse Del | exit 0 == snap ws-swept grid=120x21 cursor=4,6 -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit echo SW''EPT-WS -|17: /tmp/pardes-snap/headersweep/cwd (echo SW''EPT-WS) exit 0 -|18: Kill Save Collapse Del +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit echo SW''EPT-WS +|17: /tmp/pardes-snap/headersweep/cwd (echo SW''EPT-WS) exit 0 +|18: Kill Save Collapse Del == snap ws-looked grid=120x21 cursor=7,9 -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit echo SW''EPT-WS xxhay.txtxx -|7: /tmp/pardes-snap/headersweep/cwd/hay.txt Save Tty Collaps -|8: e Del +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit echo SW''EPT-WS xxhay.txtxx +|7: /tmp/pardes-snap/headersweep/cwd/hay.txt Save Tty Collapse +|8: Del |9: 1 ZQNEEDLE == snap cancelled grid=120x21 cursor=7,9 == style selected grid=120x21 -|1: 0-1 d,#887455, 2-2 d,#1d2824, 3-59 #b2c3b8,#1d2824, 60-61 #b2c3b8,#887455, 62-62 #b2c3b8,#314738, 63-70 #becfc4,#314738, 71-79 #f5f7ee,#3c614a, 80-80 #f5f7ee,#314738, 81-119 #becfc4,#314738, -|2: 0-1 d,#496656, 2-2 d,#1d2824, 3-35 #b2c3b8,#1d2824, 36-44 #d3b0d9,#1d2824, 45-59 #b2c3b8,#1d2824, 60-61 #b2c3b8,#add38a, 62-62 #b2c3b8,#314738, 63-95 #becfc4,#314738, 96-104 #dfbce5,#314738, 105-119 #becfc4,#314738, +|1: 0-1 d,#887455, 2-59 #b2c3b8,#1d2824, 60-61 #b2c3b8,#887455, 62-69 #becfc4,#314738, 70-78 #f5f7ee,#3c614a, 79-79 #f5f7ee,#314738, 80-119 #becfc4,#314738, +|2: 0-1 d,#496656, 2-34 #b2c3b8,#1d2824, 35-43 #d3b0d9,#1d2824, 44-59 #b2c3b8,#1d2824, 60-61 #b2c3b8,#add38a, 62-94 #becfc4,#314738, 95-103 #dfbce5,#314738, 104-119 #becfc4,#314738, |3: 0-2 d,#1d2824, 3-59 #b2c3b8,#1d2824, 60-62 #b2c3b8,#314738, 63-119 #becfc4,#314738, -|7: 0-1 d,#496656, 2-2 d,#1d2824, 3-35 #b2c3b8,#1d2824, 36-43 #d3b0d9,#1d2824, 44-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, +|7: 0-1 d,#496656, 2-34 #b2c3b8,#1d2824, 35-42 #d3b0d9,#1d2824, 43-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, |8: 0-2 d,#1d2824, 3-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, |9: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, -|17: 0-1 d,#496656, 2-2 d,#1d2824, 3-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, -|18: 0-3 d,#1d2824, 4-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, +|17: 0-1 d,#496656, 2-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, +|18: 0-1 d,#1d2824, 2-59 #b2c3b8,#1d2824, 60-60 #b2c3b8,#608269, 61-119 #b2c3b8,#0d1410, |19: 0-0 d,#152019, 1-1 d,#0d1410, 2-59 #e5eee5,#0d1410, 60-60 #e5eee5,#608269, 61-119 #e5eee5,#0d1410, diff --git a/test/snapshots/hscroll.golden b/test/snapshots/hscroll.golden index e73bf4c3..23bb6279 100644 --- a/test/snapshots/hscroll.golden +++ b/test/snapshots/hscroll.golden @@ -1,13 +1,13 @@ == snap opened grid=90x31 cursor=7,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/hscroll/cwd Tty+bash Save /tmp/pardes-snap/hscroll/cwd Tty+bash Save -| Mode Filter Collapse Del Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/hscroll/cwd Tty+bash Save /tmp/pardes-snap/hscroll/cwd Tty+bash Save +| Mode Filter Collapse Del Mode Filter Collapse Del | ls ls | wide.txt wide.txt | -| /tmp/pardes-snap/hscroll/cwd/wide.txt Save -| Tty Collapse Del +| /tmp/pardes-snap/hscroll/cwd/wide.txt Save +| Tty Collapse Del | 1 short1 END_A_MARKER_WAY_OUT_RIGHT_padp | | @@ -16,8 +16,8 @@ | | | -| /tmp/pardes-snap/hscroll/cwd Tty+bash Save -| Mode Filter Collapse Del +| /tmp/pardes-snap/hscroll/cwd Tty+bash Save +| Mode Filter Collapse Del | ls | wide.txt == snap wheeled grid=90x31 cursor=7,9 diff --git a/test/snapshots/images.golden b/test/snapshots/images.golden index 0f15804b..51cb4922 100644 --- a/test/snapshots/images.golden +++ b/test/snapshots/images.golden @@ -1,12 +1,12 @@ == snap img-open grid=150x31 cursor=11,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/images/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/images/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/images/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/images/cwd Tty+bash Save Mode Filter Collapse Del | ls ls | pic.ppm pic.ppm | -| img petscii:on palette:commodore ascii:on /tmp/pardes-snap/images/cwd/pi -| c.ppm Tty Collapse Del +| img petscii:on palette:commodore ascii:on /tmp/pardes-snap/images/cwd/pic +| .ppm Tty Collapse Del | x🬱\╲🬌\~▄🬥4▟g*🬺🬶_🬆🬻 | >A8🬌Cq&.\H&🬹🬜C▛🬻 | >0p' | $ '\033_Ga=q,i=1,s=1,v=1,f=24,t=d;AAAA\033\\\033[>0p'Gi=1;OK diff --git a/test/snapshots/look-center.golden b/test/snapshots/look-center.golden index c861bb8f..fcc65ceb 100644 --- a/test/snapshots/look-center.golden +++ b/test/snapshots/look-center.golden @@ -1,11 +1,11 @@ == snap center-open grid=150x31 cursor=15,12 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/look-center/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/look-center/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/look-center/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/look-center/cwd Tty+bash Save Mode Filter Collapse Del | ls ls | big.txt big.txt | -| /tmp/pardes-snap/look-center/cwd/big.txt Save Tty Collapse Del +| /tmp/pardes-snap/look-center/cwd/big.txt Save Tty Collapse Del | 95 line 95 | 96 line 96 | 97 line 97 @@ -16,7 +16,7 @@ | 102 line 102 | 103 line 103 | 104 line 104 -| /tmp/pardes-snap/look-center/cwd Tty+bash Save Mode Filter Collapse Del +| /tmp/pardes-snap/look-center/cwd Tty+bash Save Mode Filter Collapse Del | ls | big.txt == snap center-dedup grid=150x31 cursor=15,12 diff --git a/test/snapshots/look-dir.golden b/test/snapshots/look-dir.golden index 29e67d5f..4acc0d79 100644 --- a/test/snapshots/look-dir.golden +++ b/test/snapshots/look-dir.golden @@ -1,13 +1,13 @@ == snap dir-open grid=100x31 cursor=4,11 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/look-dir/cwd Tty+bash Save Mod /tmp/pardes-snap/look-dir/cwd Tty+bash Save Mod -| e Filter Collapse Del e Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/look-dir/cwd Tty+bash Save Mode /tmp/pardes-snap/look-dir/cwd Tty+bash Save Mode +| Filter Collapse Del Filter Collapse Del | ls ls | sub top.txt sub top.txt | -| /tmp/pardes-snap/look-dir/cwd/sub Tty+bash Save -| Mode Filter Collapse Del +| /tmp/pardes-snap/look-dir/cwd/sub Tty+bash Save +| Mode Filter Collapse Del | ls | inner.txt | @@ -16,7 +16,7 @@ | | | -| /tmp/pardes-snap/look-dir/cwd Tty+bash Save Mod -| e Filter Collapse Del +| /tmp/pardes-snap/look-dir/cwd Tty+bash Save Mode +| Filter Collapse Del | ls | sub top.txt diff --git a/test/snapshots/look-file-1col.golden b/test/snapshots/look-file-1col.golden index 81ba4ded..53fc4237 100644 --- a/test/snapshots/look-file-1col.golden +++ b/test/snapshots/look-file-1col.golden @@ -1,11 +1,11 @@ == snap file-open-1col grid=100x31 cursor=14,19 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/look-file-1col/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/look-file-1col/cwd Tty+bash Save Mode Filter Collapse Del | ls | big.txt | -| /tmp/pardes-snap/look-file-1col/cwd/big.txt Save Tty Collapse Del +| /tmp/pardes-snap/look-file-1col/cwd/big.txt Save Tty Collapse Del | 28 line 28 | 29 line 29 | 30 line 30 diff --git a/test/snapshots/look-file.golden b/test/snapshots/look-file.golden index 4d4bbdfe..bf46f854 100644 --- a/test/snapshots/look-file.golden +++ b/test/snapshots/look-file.golden @@ -1,11 +1,11 @@ == snap file-open grid=150x31 cursor=14,12 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/look-file/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/look-file/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/look-file/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/look-file/cwd Tty+bash Save Mode Filter Collapse Del | ls ls | big.txt big.txt | -| /tmp/pardes-snap/look-file/cwd/big.txt Save Tty Collapse Del +| /tmp/pardes-snap/look-file/cwd/big.txt Save Tty Collapse Del | 35 line 35 | 36 line 36 | 37 line 37 @@ -16,17 +16,17 @@ | 42 line 42 | 43 line 43 | 44 line 44 -| /tmp/pardes-snap/look-file/cwd Tty+bash Save Mode Filter Collapse Del +| /tmp/pardes-snap/look-file/cwd Tty+bash Save Mode Filter Collapse Del | ls | big.txt == style file-open grid=150x31 -|0: 0-149 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-74 #becfc4,#314738, 75-76 #becfc4,#887455, 77-77 #becfc4,#1d2824, 78-149 #b2c3b8,#1d2824, -|2: 0-1 d,#496656, 2-2 d,#1d2824, 3-33 #b2c3b8,#1d2824, 34-42 #d3b0d9,#1d2824, 43-74 #b2c3b8,#1d2824, 75-76 #b2c3b8,#496656, 77-108 #b2c3b8,#1d2824, 109-117 #d3b0d9,#1d2824, 118-149 #b2c3b8,#1d2824, +|0: 0-1 d,#1d2824, 2-149 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-74 #becfc4,#314738, 75-76 #becfc4,#887455, 77-149 #b2c3b8,#1d2824, +|2: 0-1 d,#496656, 2-32 #b2c3b8,#1d2824, 33-41 #d3b0d9,#1d2824, 42-74 #b2c3b8,#1d2824, 75-76 #b2c3b8,#496656, 77-107 #b2c3b8,#1d2824, 108-116 #d3b0d9,#1d2824, 117-149 #b2c3b8,#1d2824, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, -|6: 0-1 d,#add38a, 2-2 d,#314738, 3-33 #becfc4,#314738, 34-41 #dfbce5,#314738, 42-74 #becfc4,#314738, 75-75 #becfc4,#608269, 76-149 #becfc4,#0d1410, +|6: 0-1 d,#add38a, 2-32 #becfc4,#314738, 33-40 #dfbce5,#314738, 41-74 #becfc4,#314738, 75-75 #becfc4,#608269, 76-149 #becfc4,#0d1410, |7: 0-0 d,#152019, 1-3 d,#0d1410, 4-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |8: 0-0 d,#152019, 1-3 d,#0d1410, 4-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |9: 0-0 d,#152019, 1-3 d,#0d1410, 4-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, @@ -37,7 +37,7 @@ |14: 0-0 d,#152019, 1-3 d,#0d1410, 4-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |15: 0-0 d,#152019, 1-3 d,#0d1410, 4-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |16: 0-0 d,#152019, 1-3 d,#0d1410, 4-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, -|17: 0-1 d,#496656, 2-2 d,#1d2824, 3-33 #b2c3b8,#1d2824, 34-42 #d3b0d9,#1d2824, 43-74 #b2c3b8,#1d2824, 75-75 #b2c3b8,#608269, 76-149 #b2c3b8,#0d1410, +|17: 0-1 d,#496656, 2-32 #b2c3b8,#1d2824, 33-41 #d3b0d9,#1d2824, 42-74 #b2c3b8,#1d2824, 75-75 #b2c3b8,#608269, 76-149 #b2c3b8,#0d1410, |18: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |19: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |20: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, diff --git a/test/snapshots/lookloaded.golden b/test/snapshots/lookloaded.golden index a968a6dc..62028dc6 100644 --- a/test/snapshots/lookloaded.golden +++ b/test/snapshots/lookloaded.golden @@ -1,13 +1,13 @@ == snap file-open grid=100x31 cursor=14,13 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lookloaded/cwd Tty+bash Save M /tmp/pardes-snap/lookloaded/cwd Tty+bash Save M -| ode Filter Collapse Del ode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/lookloaded/cwd Tty+bash Save Mo /tmp/pardes-snap/lookloaded/cwd Tty+bash Save Mo +| de Filter Collapse Del de Filter Collapse Del | ls ls | big.txt big.txt | -| /tmp/pardes-snap/lookloaded/cwd/big.txt Save Tt -| y Collapse Del +| /tmp/pardes-snap/lookloaded/cwd/big.txt Save Tty +| Collapse Del | 36 line 36 | 37 line 37 | 38 line 38 @@ -16,15 +16,15 @@ | 41 line 41 | 42 line 42 | 43 line 43 -| /tmp/pardes-snap/lookloaded/cwd Tty+bash Save M -| ode Filter Collapse Del +| /tmp/pardes-snap/lookloaded/cwd Tty+bash Save Mo +| de Filter Collapse Del | ls | big.txt == snap removed grid=100x31 cursor=54,8 |6: rm big.txt; echo GO''NE -|7: * /tmp/pardes-snap/lookloaded/cwd/big.txt Save Tt GONE +|7: */tmp/pardes-snap/lookloaded/cwd/big.txt Save Tty GONE == snap look-noFS grid=100x31 cursor=14,13 -|8: y Collapse Del big.txt:10 +|8: Collapse Del big.txt:10 |9: 6 line 6 |10: 7 line 7 |11: 8 line 8 diff --git a/test/snapshots/lookpanes.golden b/test/snapshots/lookpanes.golden index e0f55f5f..6689c710 100644 --- a/test/snapshots/lookpanes.golden +++ b/test/snapshots/lookpanes.golden @@ -1,48 +1,48 @@ == snap shells grid=130x51 cursor=122,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lookpanes/cwd/beta/bmark.txt Save Tty Collaps /tmp/pardes-snap/lookpanes/cwd Tty+bash Save Mode Filter Colla -| e Del pse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/lookpanes/cwd/beta/bmark.txt Save Tty Collapse /tmp/pardes-snap/lookpanes/cwd Tty+bash Save Mode Filter Collap +| Del se Del | 1 both.txt ls zqonly.txt pick.txt twin.txt | 2 b-marker alpha beta zzboot.txt | -| /tmp/pardes-snap/lookpanes/cwd/alpha Tty+bash Save Mode Filter -| Collapse Del +| /tmp/pardes-snap/lookpanes/cwd/alpha Tty+bash Save Mode Filter +| Collapse Del | ls | amark.txt both.txt pick.txt twin.txt zqonly.txt == snap other-dir grid=130x51 cursor=7,8 -|6: /tmp/pardes-snap/lookpanes/cwd/alpha/zqonly.txt Save Tty Colla -|7: pse Del /tmp/pardes-snap/lookpanes/cwd/alpha Tty+bash Save Mode Filter -|8: 1 ONLY-IN-ALPHA Collapse Del +|6: /tmp/pardes-snap/lookpanes/cwd/alpha/zqonly.txt Save Tty Collap +|7: se Del /tmp/pardes-snap/lookpanes/cwd/alpha Tty+bash Save Mode Filter +|8: 1 ONLY-IN-ALPHA Collapse Del == snap clicked-wins grid=130x51 cursor=7,12 -|10: /tmp/pardes-snap/lookpanes/cwd/beta/both.txt Save Tty Collapse amark.txt both.txt pick.txt twin.txt zqonly.txt -|11: Del +|10: /tmp/pardes-snap/lookpanes/cwd/beta/both.txt Save Tty Collapse amark.txt both.txt pick.txt twin.txt zqonly.txt +|11: Del |12: 1 BOTH-FROM-BETA == snap mru-alpha grid=130x51 cursor=72,14 -|12: 1 BOTH-FROM-BETA /tmp/pardes-snap/lookpanes/cwd/alpha/pick.txt Save Tty Collaps -|13: e Del +|12: 1 BOTH-FROM-BETA /tmp/pardes-snap/lookpanes/cwd/alpha/pick.txt Save Tty Collapse +|13: Del |14: 1 PICK-FROM-ALPHA == snap mru-beta grid=130x51 cursor=7,16 -|14: /tmp/pardes-snap/lookpanes/cwd/beta/twin.txt Save Tty Collapse 1 PICK-FROM-ALPHA -|15: Del +|14: /tmp/pardes-snap/lookpanes/cwd/beta/twin.txt Save Tty Collapse 1 PICK-FROM-ALPHA +|15: Del |16: 1 TWIN-FROM-BETA == style mru-beta grid=130x51 -|0: 0-129 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-64 #becfc4,#314738, 65-66 #becfc4,#887455, 67-67 #becfc4,#1d2824, 68-129 #b2c3b8,#1d2824, -|2: 0-1 d,#496656, 2-2 d,#1d2824, 3-38 #b2c3b8,#1d2824, 39-48 #d3b0d9,#1d2824, 49-64 #b2c3b8,#1d2824, 65-66 #b2c3b8,#496656, 67-98 #b2c3b8,#1d2824, 99-107 #d3b0d9,#1d2824, 108-129 #b2c3b8,#1d2824, +|0: 0-1 d,#1d2824, 2-129 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-64 #becfc4,#314738, 65-66 #becfc4,#887455, 67-129 #b2c3b8,#1d2824, +|2: 0-1 d,#496656, 2-37 #b2c3b8,#1d2824, 38-47 #d3b0d9,#1d2824, 48-64 #b2c3b8,#1d2824, 65-66 #b2c3b8,#496656, 67-97 #b2c3b8,#1d2824, 98-106 #d3b0d9,#1d2824, 107-129 #b2c3b8,#1d2824, |3: 0-2 d,#1d2824, 3-129 #b2c3b8,#1d2824, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-64 #e5eee5,#0d1410, 65-65 #e5eee5,#608269, 66-129 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-64 #e5eee5,#0d1410, 65-65 #e5eee5,#608269, 66-129 #e5eee5,#0d1410, -|6: 0-1 d,#496656, 2-2 d,#1d2824, 3-39 #b2c3b8,#1d2824, 40-50 #d3b0d9,#1d2824, 51-64 #b2c3b8,#1d2824, 65-65 #b2c3b8,#608269, 66-129 #b2c3b8,#0d1410, -|7: 0-2 d,#1d2824, 3-64 #b2c3b8,#1d2824, 65-66 #b2c3b8,#496656, 67-104 #b2c3b8,#1d2824, 105-113 #d3b0d9,#1d2824, 114-129 #b2c3b8,#1d2824, -|8: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-64 #e5eee5,#0d1410, 65-68 #e5eee5,#1d2824, 69-129 #b2c3b8,#1d2824, +|6: 0-1 d,#496656, 2-38 #b2c3b8,#1d2824, 39-49 #d3b0d9,#1d2824, 50-64 #b2c3b8,#1d2824, 65-65 #b2c3b8,#608269, 66-129 #b2c3b8,#0d1410, +|7: 0-1 d,#1d2824, 2-64 #b2c3b8,#1d2824, 65-66 #b2c3b8,#496656, 67-103 #b2c3b8,#1d2824, 104-112 #d3b0d9,#1d2824, 113-129 #b2c3b8,#1d2824, +|8: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-64 #e5eee5,#0d1410, 65-66 #e5eee5,#1d2824, 67-129 #b2c3b8,#1d2824, |9: 0-0 d,#608269, 1-64 d,#0d1410, 65-65 d,#608269, 66-66 d,#0d1410, 67-129 #e5eee5,#0d1410, -|10: 0-1 d,#496656, 2-2 d,#1d2824, 3-38 #b2c3b8,#1d2824, 39-47 #d3b0d9,#1d2824, 48-64 #b2c3b8,#1d2824, 65-65 #b2c3b8,#608269, 66-66 #b2c3b8,#0d1410, 67-129 #e5eee5,#0d1410, -|11: 0-3 d,#1d2824, 4-64 #b2c3b8,#1d2824, 65-65 #b2c3b8,#608269, 66-129 #b2c3b8,#0d1410, -|12: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-64 #e5eee5,#0d1410, 65-66 #e5eee5,#496656, 67-67 #e5eee5,#1d2824, 68-104 #b2c3b8,#1d2824, 105-113 #d3b0d9,#1d2824, 114-129 #b2c3b8,#1d2824, +|10: 0-1 d,#496656, 2-37 #b2c3b8,#1d2824, 38-46 #d3b0d9,#1d2824, 47-64 #b2c3b8,#1d2824, 65-65 #b2c3b8,#608269, 66-66 #b2c3b8,#0d1410, 67-129 #e5eee5,#0d1410, +|11: 0-1 d,#1d2824, 2-64 #b2c3b8,#1d2824, 65-65 #b2c3b8,#608269, 66-129 #b2c3b8,#0d1410, +|12: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-64 #e5eee5,#0d1410, 65-66 #e5eee5,#496656, 67-103 #b2c3b8,#1d2824, 104-112 #d3b0d9,#1d2824, 113-129 #b2c3b8,#1d2824, |13: 0-0 d,#608269, 1-64 d,#0d1410, 65-67 d,#1d2824, 68-129 #b2c3b8,#1d2824, -|14: 0-1 d,#add38a, 2-2 d,#314738, 3-38 #becfc4,#314738, 39-47 #dfbce5,#314738, 48-64 #becfc4,#314738, 65-65 #becfc4,#608269, 66-69 #becfc4,#0d1410, 70-71 #59675c,#0d1410, 72-129 #e5eee5,#0d1410, -|15: 0-3 d,#314738, 4-64 #becfc4,#314738, 65-65 #becfc4,#608269, 66-129 #becfc4,#0d1410, +|14: 0-1 d,#add38a, 2-37 #becfc4,#314738, 38-46 #dfbce5,#314738, 47-64 #becfc4,#314738, 65-65 #becfc4,#608269, 66-69 #becfc4,#0d1410, 70-71 #59675c,#0d1410, 72-129 #e5eee5,#0d1410, +|15: 0-1 d,#314738, 2-64 #becfc4,#314738, 65-65 #becfc4,#608269, 66-129 #becfc4,#0d1410, |16: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-64 #e5eee5,#0d1410, 65-65 #e5eee5,#608269, 66-129 #e5eee5,#0d1410, |17: 0-0 d,#608269, 1-64 d,#0d1410, 65-65 d,#608269, 66-129 d,#0d1410, |18: 0-0 d,#608269, 1-64 d,#0d1410, 65-65 d,#608269, 66-129 d,#0d1410, diff --git a/test/snapshots/lookrange.golden b/test/snapshots/lookrange.golden index f57ee457..4a286faa 100644 --- a/test/snapshots/lookrange.golden +++ b/test/snapshots/lookrange.golden @@ -1,13 +1,13 @@ == snap opened grid=150x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lookrange/cwd/look.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/lookrange/cwd/look.txt Save Tty Collapse Del | 1 r.txt:3-5 | 2 r.txt:7:4-9 | 3 r.txt:3:2-5:3 | 4 r.txt:8:6-99:9 == snap wholelines grid=150x31 cursor=11,12 -|7: /tmp/pardes-snap/lookrange/cwd/r.txt Save Tty Collapse Del +|7: /tmp/pardes-snap/lookrange/cwd/r.txt Save Tty Collapse Del |8: 1 aaaa |9: 2 bbbb |10: 3 cccc dccc @@ -18,14 +18,14 @@ |15: 8 hhhh NEEDLE |16: 9 iiii == style wholelines grid=150x31 -|0: 0-149 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-149 #becfc4,#314738, -|2: 0-1 d,#496656, 2-2 d,#1d2824, 3-33 #b2c3b8,#1d2824, 34-42 #d3b0d9,#1d2824, 43-149 #b2c3b8,#1d2824, +|0: 0-1 d,#1d2824, 2-149 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-149 #becfc4,#314738, +|2: 0-1 d,#496656, 2-32 #b2c3b8,#1d2824, 33-41 #d3b0d9,#1d2824, 42-149 #b2c3b8,#1d2824, |3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, |6: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, -|7: 0-1 d,#add38a, 2-2 d,#314738, 3-33 #becfc4,#314738, 34-39 #dfbce5,#314738, 40-149 #becfc4,#314738, +|7: 0-1 d,#add38a, 2-32 #becfc4,#314738, 33-38 #dfbce5,#314738, 39-149 #becfc4,#314738, |8: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, |9: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, |10: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #f5f7ee,#3c614a, @@ -69,7 +69,7 @@ |15: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-11 #e5eee5,#0d1410, 12-149 #f5f7ee,#3c614a, |16: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #f5f7ee,#3c614a, 11-149 #f5f7ee,#0d1410, == snap hit1 grid=150x31 cursor=15,14 -|17: /tmp/pardes-snap/lookrange/cwd/+Search Save Tty Collapse Del LocationsConfig +|17: /tmp/pardes-snap/lookrange/cwd/+Search Save Tty Collapse LocationsConfig Del |18: 1 r.txt:7:4-9 |19: 2 gg NEEDLE gg |20: 3 r.txt:8:6-11 @@ -79,7 +79,7 @@ |14: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-9 #e5eee5,#0d1410, 10-15 #f5f7ee,#3c614a, 16-16 #f5f7ee,#0d1410, 17-149 #e5eee5,#0d1410, |15: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, |16: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, -|17: 0-1 d,#496656, 2-2 d,#1d2824, 3-33 #b2c3b8,#1d2824, 34-41 #d3b0d9,#1d2824, 42-149 #b2c3b8,#1d2824, +|17: 0-1 d,#496656, 2-32 #b2c3b8,#1d2824, 33-40 #d3b0d9,#1d2824, 41-149 #b2c3b8,#1d2824, |18: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, |19: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-9 #e5eee5,#0d1410, 10-15 #f7e4a5,#5e4923, 16-16 #f7e4a5,#0d1410, 17-149 #e5eee5,#0d1410, |20: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, diff --git a/test/snapshots/lsp-client-edit.golden b/test/snapshots/lsp-client-edit.golden index c9d93379..b4a16b22 100644 --- a/test/snapshots/lsp-client-edit.golden +++ b/test/snapshots/lsp-client-edit.golden @@ -1,7 +1,7 @@ == snap formatted grid=100x25 cursor=7,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| * /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext Def Refs +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| */tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse TreeContext Def Refs Del | 1 // formatted by mock formatted 1 range(s) | 2 mod lib; | 3 @@ -12,7 +12,7 @@ | 8 } | 9 == snap unformatted grid=100x25 cursor=7,3 -|2: /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext Def Refs +|2: /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse TreeContext Def Refs Del |3: 1 mod lib; |4: 2 |5: 3 fn main() { @@ -23,12 +23,12 @@ |10: 8 |11: == snap renamed grid=100x25 cursor=12,5 -|2: * /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext Def Refs +|2: */tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse TreeContext Def Refs Del |3: 1 mod lib; renamed 2 range(s) |6: 4 let x = sum(1, 2); |7: 5 let y = sum(3, 4); == snap unrenamed grid=100x25 cursor=12,5 -|2: /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse Del TreeContext Def Refs +|2: /tmp/pardes-snap/lsp-client-edit/cwd/main.rs Save Tty Collapse TreeContext Def Refs Del |3: 1 mod lib; |6: 4 let x = add(1, 2); |7: 5 let y = add(3, 4); diff --git a/test/snapshots/lsp-client.golden b/test/snapshots/lsp-client.golden index 13771394..c9fad7b7 100644 --- a/test/snapshots/lsp-client.golden +++ b/test/snapshots/lsp-client.golden @@ -1,7 +1,7 @@ == snap gd-jumped grid=100x25 cursor=16,12 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lsp-client/cwd/main.rs Save Tty Collapse Del TreeContext Def Refs +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/lsp-client/cwd/main.rs Save Tty Collapse TreeContext Def Refs Del | 1 mod lib; --:--:-- lsp rust-analyzer: ready | 2 | 3 fn main() { @@ -9,7 +9,7 @@ | 5 let y = add(3, 4); | 6 let _ = x + y; | 7 } -| /tmp/pardes-snap/lsp-client/cwd/lib.rs Save Tty Collapse Del TreeContext Def Refs +| /tmp/pardes-snap/lsp-client/cwd/lib.rs Save Tty Collapse TreeContext Def Refs Del | 1 // mock fixture | 2 pub fn add(a: i32, b: i32) -> i32 { | 3 a + b @@ -17,7 +17,7 @@ | 5 == snap gr-list grid=100x25 cursor=21,6 |3: 1 mod lib; -|15: /tmp/pardes-snap/lsp-client/cwd/+Search Save Tty Collapse Del LocationsConfig +|15: /tmp/pardes-snap/lsp-client/cwd/+Search Save Tty Collapse LocationsConfig Del |16: 1 lib.rs:2:8-10 |17: 2 pub fn add(a: i32, b: i32) -> i32 { |18: 3 main.rs:4:13-15 diff --git a/test/snapshots/lsp-rename-files.golden b/test/snapshots/lsp-rename-files.golden index 4f71424e..1d239d34 100644 --- a/test/snapshots/lsp-rename-files.golden +++ b/test/snapshots/lsp-rename-files.golden @@ -1,12 +1,12 @@ == snap opened grid=100x25 cursor=7,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lsp-rename-files/cwd/lib.rs Save Tty Collapse Del TreeContext Def Refs +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/lsp-rename-files/cwd/lib.rs Save Tty Collapse TreeContext Def Refs Del | 1 // main.rs | 2 pub fn add(a: i32, b: i32) -> i32 { | 3 a + b | 4 } -| /tmp/pardes-snap/lsp-rename-files/cwd/main.rs Save Tty Collapse Del TreeContext Def Refs +| /tmp/pardes-snap/lsp-rename-files/cwd/main.rs Save Tty Collapse TreeContext Def Refs Del | 1 mod lib; | 2 | 3 fn main() { @@ -17,7 +17,7 @@ | 8 == snap previewed grid=100x25 cursor=14,4 |3: 1 // main.rs Rename: 3 edit(s) across files, previewed, not applied -|15: /tmp/pardes-snap/lsp-rename-files/cwd/+Search Save Tty Collapse Del LocationsConfig +|15: /tmp/pardes-snap/lsp-rename-files/cwd/+Search Save Tty Collapse LocationsConfig Del |16: 1 lib.rs:2:8-10 |17: 2 sum |18: 3 main.rs:4:13-15 diff --git a/test/snapshots/lsp-rename.golden b/test/snapshots/lsp-rename.golden index 6b85822c..f5dc718d 100644 --- a/test/snapshots/lsp-rename.golden +++ b/test/snapshots/lsp-rename.golden @@ -1,7 +1,7 @@ == snap renamed grid=110x25 cursor=17,10 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| * /tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse Del TreeContext Def Refs +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| */tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse TreeContext Def Refs Del | 1 const std = @import("std"); renamed 2 range(s) | 2 | 3 fn renamed_helper(x: u32) u32 { @@ -18,11 +18,11 @@ | 14 } | 15 == snap undone grid=110x25 cursor=17,10 -|2: /tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse Del TreeContext Def Refs +|2: /tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse TreeContext Def Refs Del |3: 1 const std = @import("std"); |5: 3 fn helper(x: u32) u32 { |10: 8 _ = helper(41); == snap redone grid=110x25 cursor=17,10 -|2: * /tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse Del TreeContext Def Refs +|2: */tmp/pardes-snap/lsp-rename/cwd/rename.zig Save Tty Collapse TreeContext Def Refs Del |5: 3 fn renamed_helper(x: u32) u32 { |10: 8 _ = renamed_helper(41); diff --git a/test/snapshots/lsp.golden b/test/snapshots/lsp.golden index 2225de00..de52523c 100644 --- a/test/snapshots/lsp.golden +++ b/test/snapshots/lsp.golden @@ -1,7 +1,7 @@ == snap opened grid=120x41 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lsp/cwd/a.zig Save Tty Collapse Del TreeContext Def Refs +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/lsp/cwd/a.zig Save Tty Collapse TreeContext Def Refs Del | 1 const std = @import("std"); | 2 | 3 fn helper(x: u32) u32 { @@ -17,13 +17,13 @@ |3: 1 const std = @import("std"); --:--:-- lsp zls ready — /tmp/pardes-snap/lsp/cwd == snap hover grid=120x41 cursor=15,5 |3: 1 const std = @import("std"); Hover -|12: /tmp/pardes-snap/lsp/cwd/+Hover Save Tty Collapse Del +|12: /tmp/pardes-snap/lsp/cwd/+Hover Save Tty Collapse Del |13: 1 fn helper(x: u32) u32 |14: 2 (fn (u32) u32) |15: 3 == snap symbols grid=120x41 cursor=15,5 |3: 1 const std = @import("std"); Symbols -|15: /tmp/pardes-snap/lsp/cwd/+Search Save Tty Collapse Del LocationsConfig +|15: /tmp/pardes-snap/lsp/cwd/+Search Save Tty Collapse LocationsConfig Del |16: 1 a.zig:1:7-9 |17: 2 std |18: 3 a.zig:3:4-9 diff --git a/test/snapshots/lspcomplete.golden b/test/snapshots/lspcomplete.golden index 85c26e30..dd1e5c7e 100644 --- a/test/snapshots/lspcomplete.golden +++ b/test/snapshots/lspcomplete.golden @@ -1,7 +1,7 @@ == snap opened grid=120x41 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext Def Refs +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse TreeContext Def Refs Del | 1 const Shade = enum { | 2 verdigris, | 3 cinnabar, @@ -16,7 +16,7 @@ | 12 // note. see below | 13 == snap indent grid=120x41 cursor=11,12 -|2: ^* /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext Def Refs +|2: ^*/tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse TreeContext Def Refs Del |12: 10 } == snap commentindent grid=120x41 cursor=19,14 |3: 1 const Shade = enum { --:--:-- lsp zls ready — /tmp/pardes-snap/lspcomplete/cwd @@ -25,23 +25,23 @@ |3: 1 const Shade = enum { |10: 8 . == snap completion grid=120x41 cursor=16,10 -|15: /tmp/pardes-snap/lspcomplete/cwd/+Search Save Tty Collapse Del +|15: /tmp/pardes-snap/lspcomplete/cwd/+Search Save Tty Collapse Del |16: 1 a.zig:8:10 verdigris |17: 2 a.zig:8:10 cinnabar |18: 3 == snap refill grid=120x41 cursor=16,10 == snap step grid=120x41 cursor=16,10 -|2: * /tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse Del TreeContext Def Refs +|2: */tmp/pardes-snap/lspcomplete/cwd/a.zig Save Tty Collapse TreeContext Def Refs Del == snap txtindent grid=120x41 cursor=15,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -|^* /tmp/pardes-snap/lspcomplete/cwd/notes.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +|^*/tmp/pardes-snap/lspcomplete/cwd/notes.txt Save Tty Collapse Del | 1 abc. def ghi | 2 == snap nosemi grid=100x19 cursor=29,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -|^* /tmp/pardes-snap/lspcomplete/cwd/c.zig Save Tty Collapse Del TreeContext Def Refs +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +|^*/tmp/pardes-snap/lspcomplete/cwd/c.zig Save Tty Collapse TreeContext Def Refs Del | 1 const Shade = enum { --:--:-- lsp zls ready — /tmp/pardes-snap/lspcomplete/cwd | 2 verdigris, | 3 cinnabar, @@ -50,14 +50,14 @@ | 6 pub fn nosemi() void { | 7 const z: Shade = . | 8 } -| /tmp/pardes-snap/lspcomplete/cwd/+Search Save Tty Collapse Del +| /tmp/pardes-snap/lspcomplete/cwd/+Search Save Tty Collapse Del | 1 c.zig:7:23 verdigris Shade | 2 c.zig:7:23 cinnabar Shade | 3 == snap nobrace grid=100x19 cursor=16,10 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -|^* /tmp/pardes-snap/lspcomplete/cwd/d.zig Save Tty Collapse Del TreeContext Def Refs +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +|^*/tmp/pardes-snap/lspcomplete/cwd/d.zig Save Tty Collapse TreeContext Def Refs Del | 1 const Shade = enum { --:--:-- lsp zls ready — /tmp/pardes-snap/lspcomplete/cwd | 2 verdigris, | 3 cinnabar, @@ -65,7 +65,7 @@ | 5 | 6 pub fn nobrace(s: Shade) void { | 7 switch (s) { -| /tmp/pardes-snap/lspcomplete/cwd/+Search Save Tty Collapse Del +| /tmp/pardes-snap/lspcomplete/cwd/+Search Save Tty Collapse Del | 1 d.zig:8:10 verdigris | 2 d.zig:8:10 cinnabar | 3 diff --git a/test/snapshots/lspcompletemoved.golden b/test/snapshots/lspcompletemoved.golden index 403c6931..7b3ed250 100644 --- a/test/snapshots/lspcompletemoved.golden +++ b/test/snapshots/lspcompletemoved.golden @@ -1,7 +1,7 @@ == snap typedthrough grid=120x21 cursor=16,14 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -|^* /tmp/pardes-snap/lspcompletemoved/cwd/a.zig Save Tty Collapse Del TreeContext Def Refs +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +|^*/tmp/pardes-snap/lspcompletemoved/cwd/a.zig Save Tty Collapse TreeContext Def Refs Del | 1 const Shade = enum { --:--:-- lsp zls ready — /tmp/pardes-snap/lspcompletemoved/cwd | 2 verdigris, | 3 cinnabar, diff --git a/test/snapshots/lspdebug.golden b/test/snapshots/lspdebug.golden index 4beda019..5c415033 100644 --- a/test/snapshots/lspdebug.golden +++ b/test/snapshots/lspdebug.golden @@ -1,7 +1,7 @@ == snap opened grid=120x45 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lspdebug/cwd/z.zig Save Tty Collapse Del TreeContext Def Refs +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/lspdebug/cwd/z.zig Save Tty Collapse TreeContext Def Refs Del | 1 const std = @import("std"); | 2 | 3 fn helper() u32 { diff --git a/test/snapshots/lsprelpath.golden b/test/snapshots/lsprelpath.golden index a3760316..d961d6bd 100644 --- a/test/snapshots/lsprelpath.golden +++ b/test/snapshots/lsprelpath.golden @@ -1,7 +1,7 @@ == snap absrow grid=100x35 cursor=21,16 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lsprelpath/cwd/sub/parent.zig Save Tty Collapse Del TreeContext Def Refs +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/lsprelpath/cwd/sub/parent.zig Save Tty Collapse TreeContext Def Refs Del | 1 const shade = @import("../shad --:--:-- lsp zls ready — /tmp/pardes-snap/lsprelpath/cwd/sub | 2 | 3 pub fn pick(s: shade.Shade) u8 { @@ -9,12 +9,12 @@ | 5 | 6 }; | 7 } -| /tmp/pardes-snap/lsprelpath/cwd/sub/+Search Save Tty Collapse Del LocationsConfig +| /tmp/pardes-snap/lsprelpath/cwd/sub/+Search Save Tty Collapse LocationsConfig Del | 1 /tmp/pardes-snap/lsprelpath/cwd/shade.zig:1:11-15 | 2 pub const Shade = enum { | 3 parent.zig:3:22-26 | 4 pub fn pick(s: shade.Shade) u8 { -| /tmp/pardes-snap/lsprelpath/cwd/shade.zig Save Tty Collapse Del TreeContext Def Refs +| /tmp/pardes-snap/lsprelpath/cwd/shade.zig Save Tty Collapse TreeContext Def Refs Del | 1 pub const Shade = enum { | 2 verdigris, | 3 cinnabar, @@ -23,9 +23,9 @@ == snap abslook grid=100x35 cursor=32,5 |3: 1 const shade = @import("../shade.zig"); == style abslook grid=100x35 -|0: 0-99 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-99 #becfc4,#314738, -|2: 0-1 d,#add38a, 2-2 d,#314738, 3-38 #becfc4,#314738, 39-49 #dfbce5,#314738, 50-99 #becfc4,#314738, +|0: 0-1 d,#1d2824, 2-99 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-99 #becfc4,#314738, +|2: 0-1 d,#add38a, 2-37 #becfc4,#314738, 38-48 #dfbce5,#314738, 49-99 #becfc4,#314738, |3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-20 #e5eee5,#0d1410, 21-27 #c9a7ed,#0d1410, 28-28 #e5eee5,#0d1410, 29-42 #b8d88a,#0d1410, 43-99 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |5: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-27 #e5eee5,#0d1410, 28-32 #f5f7ee,#3c614a, 33-99 #e5eee5,#0d1410, @@ -33,12 +33,12 @@ |7: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |8: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, |9: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, -|10: 0-1 d,#496656, 2-2 d,#1d2824, 3-38 #b2c3b8,#1d2824, 39-46 #d3b0d9,#1d2824, 47-99 #b2c3b8,#1d2824, +|10: 0-1 d,#496656, 2-37 #b2c3b8,#1d2824, 38-45 #d3b0d9,#1d2824, 46-99 #b2c3b8,#1d2824, |11: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |12: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-21 #f7e4a5,#5e4923, 22-22 #f7e4a5,#0d1410, 23-24 #e5eee5,#0d1410, 25-29 #c9a7ed,#0d1410, 30-99 #e5eee5,#0d1410, |13: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |14: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-27 #e5eee5,#0d1410, 28-32 #f7e4a5,#5e4923, 33-99 #e5eee5,#0d1410, -|15: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-44 #d3b0d9,#1d2824, 45-99 #b2c3b8,#1d2824, +|15: 0-1 d,#496656, 2-33 #b2c3b8,#1d2824, 34-43 #d3b0d9,#1d2824, 44-99 #b2c3b8,#1d2824, |16: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-21 #f5f7ee,#3c614a, 22-22 #f5f7ee,#0d1410, 23-24 #e5eee5,#0d1410, 25-29 #c9a7ed,#0d1410, 30-99 #e5eee5,#0d1410, |17: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, |18: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, @@ -59,9 +59,9 @@ |33: 0-0 d,#608269, 1-99 d,#0d1410, |34: 0-0 d,#608269, 1-99 d,#0d1410, == snap subrow grid=100x35 cursor=20,16 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/lsprelpath/cwd/sub/subdir.zig Save Tty Collapse Del TreeContext Def Refs +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/lsprelpath/cwd/sub/subdir.zig Save Tty Collapse TreeContext Def Refs Del | 1 const tint = @import("inner/ti --:--:-- lsp zls ready — /tmp/pardes-snap/lsprelpath/cwd/sub | 2 | 3 pub fn hue(t: tint.Tint) u8 { @@ -69,12 +69,12 @@ | 5 | 6 }; | 7 } -| /tmp/pardes-snap/lsprelpath/cwd/sub/+Search Save Tty Collapse Del LocationsConfig +| /tmp/pardes-snap/lsprelpath/cwd/sub/+Search Save Tty Collapse LocationsConfig Del | 1 inner/tint.zig:1:11-14 | 2 pub const Tint = enum { | 3 subdir.zig:3:20-23 | 4 pub fn hue(t: tint.Tint) u8 { -| /tmp/pardes-snap/lsprelpath/cwd/sub/inner/tint.zig Save Tty Collapse Del TreeContext Def Refs +| /tmp/pardes-snap/lsprelpath/cwd/sub/inner/tint.zig Save Tty Collapse TreeContext Def Refs Del | 1 pub const Tint = enum { | 2 ochre, | 3 indigo, @@ -83,9 +83,9 @@ == snap sublook grid=100x35 cursor=29,5 |3: 1 const tint = @import("inner/tint.zig"); == style sublook grid=100x35 -|0: 0-99 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-99 #becfc4,#314738, -|2: 0-1 d,#add38a, 2-2 d,#314738, 3-38 #becfc4,#314738, 39-49 #dfbce5,#314738, 50-99 #becfc4,#314738, +|0: 0-1 d,#1d2824, 2-99 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-99 #becfc4,#314738, +|2: 0-1 d,#add38a, 2-37 #becfc4,#314738, 38-48 #dfbce5,#314738, 49-99 #becfc4,#314738, |3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-19 #e5eee5,#0d1410, 20-26 #c9a7ed,#0d1410, 27-27 #e5eee5,#0d1410, 28-43 #b8d88a,#0d1410, 44-99 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |5: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-25 #e5eee5,#0d1410, 26-29 #f5f7ee,#3c614a, 30-99 #e5eee5,#0d1410, @@ -93,12 +93,12 @@ |7: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |8: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, |9: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-99 #e5eee5,#0d1410, -|10: 0-1 d,#496656, 2-2 d,#1d2824, 3-38 #b2c3b8,#1d2824, 39-46 #d3b0d9,#1d2824, 47-99 #b2c3b8,#1d2824, +|10: 0-1 d,#496656, 2-37 #b2c3b8,#1d2824, 38-45 #d3b0d9,#1d2824, 46-99 #b2c3b8,#1d2824, |11: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |12: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-20 #f7e4a5,#5e4923, 21-21 #f7e4a5,#0d1410, 22-23 #e5eee5,#0d1410, 24-28 #c9a7ed,#0d1410, 29-99 #e5eee5,#0d1410, |13: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |14: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-25 #e5eee5,#0d1410, 26-29 #f7e4a5,#5e4923, 30-99 #e5eee5,#0d1410, -|15: 0-1 d,#496656, 2-2 d,#1d2824, 3-44 #b2c3b8,#1d2824, 45-53 #d3b0d9,#1d2824, 54-99 #b2c3b8,#1d2824, +|15: 0-1 d,#496656, 2-43 #b2c3b8,#1d2824, 44-52 #d3b0d9,#1d2824, 53-99 #b2c3b8,#1d2824, |16: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-16 #e5eee5,#0d1410, 17-20 #f5f7ee,#3c614a, 21-21 #f5f7ee,#0d1410, 22-23 #e5eee5,#0d1410, 24-28 #c9a7ed,#0d1410, 29-99 #e5eee5,#0d1410, |17: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, |18: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-99 #e5eee5,#0d1410, diff --git a/test/snapshots/markup.golden b/test/snapshots/markup.golden index 6991cdf6..0d086770 100644 --- a/test/snapshots/markup.golden +++ b/test/snapshots/markup.golden @@ -1,7 +1,7 @@ == snap typst grid=92x25 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/markup/cwd/paper.typ Save Tty Collapse Del TreeContext +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/markup/cwd/paper.typ Save Tty Collapse TreeContext Del | 1 = Typst heading | 2 | 3 Prose with *bold* and _italic_ words, a `raw` span, @@ -12,9 +12,9 @@ | 8 ``` | 9 == style typst grid=92x25 -|0: 0-91 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-91 #becfc4,#314738, -|2: 0-1 d,#add38a, 2-2 d,#314738, 3-30 #becfc4,#314738, 31-40 #dfbce5,#314738, 41-91 #becfc4,#314738, +|0: 0-1 d,#1d2824, 2-91 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-91 #becfc4,#314738, +|2: 0-1 d,#add38a, 2-29 #becfc4,#314738, 30-39 #dfbce5,#314738, 40-91 #becfc4,#314738, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-91 #c9a7ed,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-91 #59675c,#0d1410, |5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-24 #b9f480,#0d1410, 25-28 #e5eee5,#0d1410, 29-37 #f8c082,#0d1410, 38-46 #e5eee5,#0d1410, 47-52 #b8d88a,#0d1410, 53-91 #e5eee5,#0d1410, @@ -38,9 +38,9 @@ |23: 0-0 d,#608269, 1-91 d,#0d1410, |24: 0-0 d,#608269, 1-91 d,#0d1410, == snap markdown grid=92x25 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/markup/cwd/notes.md Save Tty Collapse Del TreeContext +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/markup/cwd/notes.md Save Tty Collapse TreeContext Del | 1 # Markdown heading with *italic* | 2 | 3 Prose with **bold**, *italic* and an `inline` span. @@ -50,9 +50,9 @@ | 7 ``` | 8 == style markdown grid=92x25 -|0: 0-91 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-91 #becfc4,#314738, -|2: 0-1 d,#add38a, 2-2 d,#314738, 3-30 #becfc4,#314738, 31-39 #dfbce5,#314738, 40-91 #becfc4,#314738, +|0: 0-1 d,#1d2824, 2-91 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-91 #becfc4,#314738, +|2: 0-1 d,#add38a, 2-29 #becfc4,#314738, 30-38 #dfbce5,#314738, 39-91 #becfc4,#314738, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-8 #e5eee5,#0d1410, 9-30 #c9a7ed,#0d1410, 31-91 #f8c082,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-91 #59675c,#0d1410, |5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-25 #b9f480,#0d1410, 26-27 #e5eee5,#0d1410, 28-36 #f8c082,#0d1410, 37-43 #e5eee5,#0d1410, 44-52 #b8d88a,#0d1410, 53-91 #e5eee5,#0d1410, diff --git a/test/snapshots/mini.golden b/test/snapshots/mini.golden index 8d0205f7..cba3c6d0 100644 --- a/test/snapshots/mini.golden +++ b/test/snapshots/mini.golden @@ -1,21 +1,21 @@ == snap opened grid=90x23 cursor=7,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del | 1 @`Mini demo.zig` Mini | -| /tmp/pardes-snap/mini/cwd/Mini demo.zig Save Tty Collapse Del +| /tmp/pardes-snap/mini/cwd/Mini demo.zig Save Tty Collapse Del | 1 ⠭⠍⣥⢩⣭⡭⣭⣬⣌⢭⣭⠌⠬⠅⠍⠁ | 2 ⣂⢀⣉⣉⢉⣈⢁⣀⣀⢀⣀⣀⣀⢀⣀⣀⣀⣀⣀ | 3 ⠉⠉⠁⠉⠉⠉⠈⠈⠉⠉⠉⠉⠉⠉ | 4 == style opened grid=90x23 -|0: 0-89 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-89 #becfc4,#314738, -|2: 0-1 d,#496656, 2-2 d,#1d2824, 3-28 #b2c3b8,#1d2824, 29-41 #d3b0d9,#1d2824, 42-89 #b2c3b8,#1d2824, +|0: 0-1 d,#1d2824, 2-89 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-89 #becfc4,#314738, +|2: 0-1 d,#496656, 2-27 #b2c3b8,#1d2824, 28-40 #d3b0d9,#1d2824, 41-89 #b2c3b8,#1d2824, |3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-83 #e5eee5,#0d1410, 84-84 #e5eee5,#1d2824, 85-89 #b2c3b8,#1d2824, |4: 0-0 d,#608269, 1-89 d,#0d1410, -|5: 0-1 d,#add38a, 2-2 d,#314738, 3-28 #becfc4,#314738, 29-42 #dfbce5,#314738, 43-89 #becfc4,#314738, +|5: 0-1 d,#add38a, 2-27 #becfc4,#314738, 28-41 #dfbce5,#314738, 42-89 #becfc4,#314738, |6: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-8 #e5eee5,#0d1410, 9-9 #c9a7ed,#0d1410, 10-12 #e5eee5,#0d1410, 13-15 #c9a7ed,#0d1410, 16-21 #b8d88a,#0d1410, 22-89 #e5eee5,#0d1410, |7: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-8 #b9f480,#0d1410, 9-11 #c9a7ed,#0d1410, 12-89 #b9f480,#0d1410, |8: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-19 #f8c082,#0d1410, 20-89 #e5eee5,#0d1410, @@ -34,18 +34,18 @@ |21: 0-0 d,#608269, 1-89 d,#0d1410, |22: 0-0 d,#608269, 1-89 d,#0d1410, == 9p opened grid=90x23 cursor=7,6,block -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -@0: 0-74 #b2c3b8,#1d2824,,tagline 75-89 d,#1d2824,,tagline -|1: New Tty Find Grep Joincol Delcol -@1: 0-1 #ffffff,#887455,,tagline 2-2 d,#314738,,tagline 3-34 #becfc4,#314738,,tagline 35-89 d,#314738,,tagline -|2: /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del -@2: 0-1 #ffffff,#496656,,tagline 2-2 d,#1d2824,,tagline 3-28 #b2c3b8,#1d2824,,tagline 29-40 #d3b0d9,#1d2824,,tagline 41-62 #b2c3b8,#1d2824,,tagline 63-89 d,#1d2824,,tagline +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +@0: 0-76 #b2c3b8,#1d2824,,tagline 77-89 d,#1d2824,,tagline +|1: New Tty Find Grep Joincol Delcol +@1: 0-1 #ffffff,#887455,,tagline 2-33 #becfc4,#314738,,tagline 34-89 d,#314738,,tagline +|2: /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del +@2: 0-1 #ffffff,#496656,,tagline 2-27 #b2c3b8,#1d2824,,tagline 28-39 #d3b0d9,#1d2824,,tagline 40-61 #b2c3b8,#1d2824,,tagline 62-89 d,#1d2824,,tagline |3: 1 @`Mini demo.zig` Mini @3: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-22 #e5eee5,#0d1410,,body 23-83 d,#0d1410,,body 84-84 d,#1d2824,,tagline 85-88 #b2c3b8,#1d2824,,tagline 89-89 d,#1d2824,,tagline |4: @4: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body -|5: /tmp/pardes-snap/mini/cwd/Mini demo.zig Save Tty Collapse Del -@5: 0-1 #000000,#add38a,,tagline 2-2 d,#314738,,tagline 3-28 #becfc4,#314738,,tagline 29-41 #dfbce5,#314738,,tagline 42-63 #becfc4,#314738,,tagline 64-89 d,#314738,,tagline +|5: /tmp/pardes-snap/mini/cwd/Mini demo.zig Save Tty Collapse Del +@5: 0-1 #000000,#add38a,,tagline 2-27 #becfc4,#314738,,tagline 28-40 #dfbce5,#314738,,tagline 41-62 #becfc4,#314738,,tagline 63-89 d,#314738,,tagline |6: 1 ⠭⠍⣥⢩⣭⡭⣭⣬⣌⢭⣭⠌⠬⠅⠍⠁ +6: 7="⠭" 8="⠍" 9="⣥" 10="⢩" 11="⣭" 12="⡭" 13="⣭" 14="⣬" 15="⣌" 16="⢭" 17="⣭" 18="⠌" 19="⠬" 20="⠅" 21="⠍" 22="⠁" @6: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-8 #e5eee5,#0d1410,,body 9-9 #c9a7ed,#0d1410,,body 10-12 #e5eee5,#0d1410,,body 13-15 #c9a7ed,#0d1410,,body 16-21 #b8d88a,#0d1410,,body 22-22 #e5eee5,#0d1410,,body 23-89 d,#0d1410,,body @@ -105,32 +105,32 @@ |7: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-8 #b9f480,#0d1410, 9-11 #c9a7ed,#0d1410, 12-89 #b9f480,#0d1410, |8: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-17 #e5eee5,#0d1410, 18-19 #f8c082,#0d1410, 20-89 #e5eee5,#0d1410, == snap resized grid=105x27 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del | 1 @`Mini demo.zig` | | -| /tmp/pardes-snap/mini/cwd/Mini demo.zig Save Tty Collapse Del +| /tmp/pardes-snap/mini/cwd/Mini demo.zig Save Tty Collapse Del | 1 ⠭⠍⣥⢩⣭⡭⣭⣬⣌⢭⣭⠌⠬⠅⠍⠁ Colors | 2 ⣂⢀⣉⣉⢉⣈⢁⣀⣀⢀⣀⣀⣀⢀⣀⣀⣀⣀⣀ | 3 ⠉⠉⠁⠉⠉⠉⠈⠈⠉⠉⠉⠉⠉⠉ | 4 == 9p resized grid=105x27 cursor=7,7,block -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -@0: 0-74 #b2c3b8,#1d2824,,tagline 75-104 d,#1d2824,,tagline -|1: New Tty Find Grep Joincol Delcol -@1: 0-1 #ffffff,#887455,,tagline 2-2 d,#314738,,tagline 3-34 #becfc4,#314738,,tagline 35-104 d,#314738,,tagline -|2: /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del -@2: 0-1 #ffffff,#496656,,tagline 2-2 d,#1d2824,,tagline 3-28 #b2c3b8,#1d2824,,tagline 29-40 #d3b0d9,#1d2824,,tagline 41-62 #b2c3b8,#1d2824,,tagline 63-104 d,#1d2824,,tagline +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +@0: 0-76 #b2c3b8,#1d2824,,tagline 77-104 d,#1d2824,,tagline +|1: New Tty Find Grep Joincol Delcol +@1: 0-1 #ffffff,#887455,,tagline 2-33 #becfc4,#314738,,tagline 34-104 d,#314738,,tagline +|2: /tmp/pardes-snap/mini/cwd/commands.txt Save Tty Collapse Del +@2: 0-1 #ffffff,#496656,,tagline 2-27 #b2c3b8,#1d2824,,tagline 28-39 #d3b0d9,#1d2824,,tagline 40-61 #b2c3b8,#1d2824,,tagline 62-104 d,#1d2824,,tagline |3: 1 @`Mini demo.zig` @3: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-22 #e5eee5,#0d1410,,body 23-104 d,#0d1410,,body |4: @4: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body |5: @5: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body -|6: /tmp/pardes-snap/mini/cwd/Mini demo.zig Save Tty Collapse Del -@6: 0-1 #000000,#add38a,,tagline 2-2 d,#314738,,tagline 3-28 #becfc4,#314738,,tagline 29-41 #dfbce5,#314738,,tagline 42-63 #becfc4,#314738,,tagline 64-104 d,#314738,,tagline +|6: /tmp/pardes-snap/mini/cwd/Mini demo.zig Save Tty Collapse Del +@6: 0-1 #000000,#add38a,,tagline 2-27 #becfc4,#314738,,tagline 28-40 #dfbce5,#314738,,tagline 41-62 #becfc4,#314738,,tagline 63-104 d,#314738,,tagline |7: 1 ⠭⠍⣥⢩⣭⡭⣭⣬⣌⢭⣭⠌⠬⠅⠍⠁ Colors +7: 7="⠭" 8="⠍" 9="⣥" 10="⢩" 11="⣭" 12="⡭" 13="⣭" 14="⣬" 15="⣌" 16="⢭" 17="⣭" 18="⠌" 19="⠬" 20="⠅" 21="⠍" 22="⠁" @7: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-8 #e5eee5,#0d1410,,body 9-9 #c9a7ed,#0d1410,,body 10-12 #e5eee5,#0d1410,,body 13-15 #c9a7ed,#0d1410,,body 16-21 #b8d88a,#0d1410,,body 22-22 #e5eee5,#0d1410,,body 23-96 d,#0d1410,,body 97-97 d,#1d2824,,tagline 98-103 #b2c3b8,#1d2824,,tagline 104-104 d,#1d2824,,tagline diff --git a/test/snapshots/modal.golden b/test/snapshots/modal.golden index 6dc6376d..9ebc72e9 100644 --- a/test/snapshots/modal.golden +++ b/test/snapshots/modal.golden @@ -1,8 +1,8 @@ == snap top grid=100x31 cursor=2,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/modal/cwd Tty+bash Save Mode F /tmp/pardes-snap/modal/cwd Tty+bash Save Mode F -| ilter Collapse Del ilter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/modal/cwd Tty+bash Save Mode Fi /tmp/pardes-snap/modal/cwd Tty+bash Save Mode Fi +| lter Collapse Del lter Collapse Del | ls ls | words.txt words.txt | printf 'one two three\nfour five six\nseven ei @@ -16,17 +16,17 @@ | | | -| /tmp/pardes-snap/modal/cwd Tty+bash Save Mode F -| ilter Collapse Del +| /tmp/pardes-snap/modal/cwd Tty+bash Save Mode Fi +| lter Collapse Del | ls | words.txt == snap moved grid=100x31 cursor=8,6 == snap xsel grid=100x31 cursor=48,6 == style xsel grid=100x31 -|0: 0-99 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-49 #becfc4,#314738, 50-51 #becfc4,#887455, 52-52 #becfc4,#1d2824, 53-99 #b2c3b8,#1d2824, -|2: 0-1 d,#add38a, 2-2 d,#314738, 3-29 #becfc4,#314738, 30-38 #dfbce5,#314738, 39-49 #becfc4,#314738, 50-51 #becfc4,#496656, 52-52 #becfc4,#1d2824, 53-79 #b2c3b8,#1d2824, 80-88 #d3b0d9,#1d2824, 89-99 #b2c3b8,#1d2824, -|3: 0-2 d,#314738, 3-49 #becfc4,#314738, 50-52 #becfc4,#1d2824, 53-99 #b2c3b8,#1d2824, +|0: 0-1 d,#1d2824, 2-99 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-49 #becfc4,#314738, 50-51 #becfc4,#887455, 52-99 #b2c3b8,#1d2824, +|2: 0-1 d,#add38a, 2-28 #becfc4,#314738, 29-37 #dfbce5,#314738, 38-49 #becfc4,#314738, 50-51 #becfc4,#496656, 52-78 #b2c3b8,#1d2824, 79-87 #d3b0d9,#1d2824, 88-99 #b2c3b8,#1d2824, +|3: 0-1 d,#314738, 2-49 #becfc4,#314738, 50-51 #becfc4,#1d2824, 52-99 #b2c3b8,#1d2824, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 #e5eee5,#608269, 51-99 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 #e5eee5,#608269, 51-99 #e5eee5,#0d1410, |6: 0-0 d,#608269, 1-1 d,#0d1410, 2-48 #f5f7ee,#3c614a, 49-49 #f5f7ee,#0d1410, 50-50 #f5f7ee,#608269, 51-99 #f5f7ee,#0d1410, @@ -40,8 +40,8 @@ |14: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-99 d,#0d1410, |15: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-99 d,#0d1410, |16: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-99 d,#0d1410, -|17: 0-1 d,#496656, 2-2 d,#1d2824, 3-29 #b2c3b8,#1d2824, 30-38 #d3b0d9,#1d2824, 39-49 #b2c3b8,#1d2824, 50-50 #b2c3b8,#608269, 51-99 #b2c3b8,#0d1410, -|18: 0-2 d,#1d2824, 3-49 #b2c3b8,#1d2824, 50-50 #b2c3b8,#608269, 51-99 #b2c3b8,#0d1410, +|17: 0-1 d,#496656, 2-28 #b2c3b8,#1d2824, 29-37 #d3b0d9,#1d2824, 38-49 #b2c3b8,#1d2824, 50-50 #b2c3b8,#608269, 51-99 #b2c3b8,#0d1410, +|18: 0-1 d,#1d2824, 2-49 #b2c3b8,#1d2824, 50-50 #b2c3b8,#608269, 51-99 #b2c3b8,#0d1410, |19: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 #e5eee5,#608269, 51-99 #e5eee5,#0d1410, |20: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 #e5eee5,#608269, 51-99 #e5eee5,#0d1410, |21: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-99 d,#0d1410, diff --git a/test/snapshots/msg.golden b/test/snapshots/msg.golden index caa234d3..24018546 100644 --- a/test/snapshots/msg.golden +++ b/test/snapshots/msg.golden @@ -1,7 +1,7 @@ == snap opened grid=70x15 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/msg/cwd/a.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Deb +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/msg/cwd/a.txt Save Tty Collapse Del | 1 line 1 | 2 line 2 | 3 line 3 @@ -12,9 +12,9 @@ == snap saved grid=70x15 cursor=7,3 |3: 1 line 1 --:--:-- saved /tmp/pardes-snap/msg/cwd/a.txt == snap repainted grid=70x17 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/msg/cwd/a.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Deb +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/msg/cwd/a.txt Save Tty Collapse Del | 1 line 1 --:--:-- saved /tmp/pardes-snap/msg/cwd/a.txt | 2 line 2 | 3 line 3 @@ -45,7 +45,7 @@ |3: 1 AGAIN |4: 2 == snap msgbuiltin grid=70x17 cursor=29,5 -|2: * /tmp/pardes-snap/msg/cwd/a.txt Save Tty Collapse Del +|2: */tmp/pardes-snap/msg/cwd/a.txt Save Tty Collapse Del |3: 1 AGAIN hand-written report |5: 3 Msg hand-written report == snap msgtail grid=70x17 cursor=32,7 diff --git a/test/snapshots/multicursor.golden b/test/snapshots/multicursor.golden index 0b3bbcb2..48ccefbf 100644 --- a/test/snapshots/multicursor.golden +++ b/test/snapshots/multicursor.golden @@ -1,11 +1,11 @@ == snap three-cursors grid=150x31 cursor=7,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/multicursor/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/multicursor/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/multicursor/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/multicursor/cwd Tty+bash Save Mode Filter Collapse Del | ls ls | f.txt f.txt | -| /tmp/pardes-snap/multicursor/cwd/f.txt Save Tty Collapse Del +| /tmp/pardes-snap/multicursor/cwd/f.txt Save Tty Collapse Del | 1 line 1 | 2 line 2 | 3 line 3 @@ -16,17 +16,17 @@ | 8 line 8 | 9 line 9 | 10 line 10 -| /tmp/pardes-snap/multicursor/cwd Tty+bash Save Mode Filter Collapse Del +| /tmp/pardes-snap/multicursor/cwd Tty+bash Save Mode Filter Collapse Del | ls | f.txt == style three-cursors grid=150x31 -|0: 0-149 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-74 #becfc4,#314738, 75-76 #becfc4,#887455, 77-77 #becfc4,#1d2824, 78-149 #b2c3b8,#1d2824, -|2: 0-1 d,#496656, 2-2 d,#1d2824, 3-35 #b2c3b8,#1d2824, 36-44 #d3b0d9,#1d2824, 45-74 #b2c3b8,#1d2824, 75-76 #b2c3b8,#496656, 77-110 #b2c3b8,#1d2824, 111-119 #d3b0d9,#1d2824, 120-149 #b2c3b8,#1d2824, +|0: 0-1 d,#1d2824, 2-149 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-74 #becfc4,#314738, 75-76 #becfc4,#887455, 77-149 #b2c3b8,#1d2824, +|2: 0-1 d,#496656, 2-34 #b2c3b8,#1d2824, 35-43 #d3b0d9,#1d2824, 44-74 #b2c3b8,#1d2824, 75-76 #b2c3b8,#496656, 77-109 #b2c3b8,#1d2824, 110-118 #d3b0d9,#1d2824, 119-149 #b2c3b8,#1d2824, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, -|6: 0-1 d,#add38a, 2-2 d,#314738, 3-35 #becfc4,#314738, 36-41 #dfbce5,#314738, 42-74 #becfc4,#314738, 75-75 #becfc4,#608269, 76-149 #becfc4,#0d1410, +|6: 0-1 d,#add38a, 2-34 #becfc4,#314738, 35-40 #dfbce5,#314738, 41-74 #becfc4,#314738, 75-75 #becfc4,#608269, 76-149 #becfc4,#0d1410, |7: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-7 #3c614a,#f5f7ee, 8-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |8: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-7 #3c614a,#f5f7ee, 8-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |9: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, @@ -37,7 +37,7 @@ |14: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |15: 0-0 d,#152019, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |16: 0-0 d,#152019, 1-3 d,#0d1410, 4-6 #59675c,#0d1410, 7-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, -|17: 0-1 d,#496656, 2-2 d,#1d2824, 3-35 #b2c3b8,#1d2824, 36-44 #d3b0d9,#1d2824, 45-74 #b2c3b8,#1d2824, 75-75 #b2c3b8,#608269, 76-149 #b2c3b8,#0d1410, +|17: 0-1 d,#496656, 2-34 #b2c3b8,#1d2824, 35-43 #d3b0d9,#1d2824, 44-74 #b2c3b8,#1d2824, 75-75 #b2c3b8,#608269, 76-149 #b2c3b8,#0d1410, |18: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |19: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |20: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, @@ -52,13 +52,13 @@ |29: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, |30: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, == snap edited-at-three grid=150x31 cursor=9,9 -|6: * /tmp/pardes-snap/multicursor/cwd/f.txt Save Tty Collapse Del +|6: */tmp/pardes-snap/multicursor/cwd/f.txt Save Tty Collapse Del |7: 1 >>line 1 |8: 2 >>line 2 |9: 3 >>line 3 == snap three-selections grid=150x31 cursor=8,9 == style three-selections grid=150x31 -|6: 0-0 d,#add38a, 1-1 #000000,#f9cb70,b 2-2 #000000,#314738, 3-35 #becfc4,#314738, 36-41 #dfbce5,#314738, 42-74 #becfc4,#314738, 75-75 #becfc4,#608269, 76-149 #becfc4,#0d1410, +|6: 0-0 d,#add38a, 1-1 #000000,#f9cb70,b 2-34 #becfc4,#314738, 35-40 #dfbce5,#314738, 41-74 #becfc4,#314738, 75-75 #becfc4,#608269, 76-149 #becfc4,#0d1410, |7: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-7 #f5f7ee,#243a2d, 8-8 #3c614a,#f5f7ee, 9-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |8: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-7 #f5f7ee,#243a2d, 8-8 #3c614a,#f5f7ee, 9-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |9: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-8 #f5f7ee,#3c614a, 9-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, diff --git a/test/snapshots/nested-optout.golden b/test/snapshots/nested-optout.golden index 3539a16c..0cb3b742 100644 --- a/test/snapshots/nested-optout.golden +++ b/test/snapshots/nested-optout.golden @@ -1,10 +1,10 @@ == snap optout-file grid=100x31 cursor=9,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -|$ /tmp/pardes-snap/nested-optout/cwd Tty+bash Save Mode Filter Collapse Del | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/nested-optout/cwd/nested.txt Save Tty Collapse Del +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/nested-optout/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/nested-optout/cwd/nested.txt Save Tty Collapse Del | 1 optout-marker | 2 second-optout-line | 3 @@ -20,15 +20,15 @@ | | | -| /tmp/pardes-snap/nested-optout/cwd/+New Save Tty Collapse Del +| /tmp/pardes-snap/nested-optout/cwd/+New Save Tty Collapse Del | 1 == snap inner-shell grid=100x31 cursor=6,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -|$ /tmp/pardes-snap/nested-optout/cwd Tty+bash Save Mode Filter Collapse Del | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| $ /tmp/pardes-snap/nested-optout/cwd/innerdir Tty+bash Save Mode Filter Collapse Del +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/nested-optout/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| $ /tmp/pardes-snap/nested-optout/cwd/innerdir Tty+bash Save Mode Filter Collapse Del | $ | | @@ -39,16 +39,16 @@ | | | -| /tmp/pardes-snap/nested-optout/cwd/innerdir/+New Save Tty Collapse Del +| /tmp/pardes-snap/nested-optout/cwd/innerdir/+New Save Tty Collapse Del | 1 | | | -| /tmp/pardes-snap/nested-optout/cwd/+New Save Tty Collapse Del +| /tmp/pardes-snap/nested-optout/cwd/+New Save Tty Collapse Del | 1 == snap inner-launch grid=100x31 cursor=11,9 -|6: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -|7: New Tty Find Grep Joincol Delcol -|8: /tmp/pardes-snap/nested-optout/cwd/innerdir/deeper.txt Save Tty Collapse Del +|6: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +|7: New Tty Find Grep Joincol Delcol +|8: /tmp/pardes-snap/nested-optout/cwd/innerdir/deeper.txt Save Tty Collapse Del |9: 1 deepest-marker |10: 2 diff --git a/test/snapshots/nested.golden b/test/snapshots/nested.golden index 44ab4b82..466c34ae 100644 --- a/test/snapshots/nested.golden +++ b/test/snapshots/nested.golden @@ -1,10 +1,10 @@ == snap file-arg grid=100x31 cursor=7,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -|$ /tmp/pardes-snap/nested/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/nested/cwd Tty+bash Save Mode Filter Collapse Del | $ $(readlink /proc/$PPID/exe) nested.txt | $ -| /tmp/pardes-snap/nested/cwd/nested.txt Save Tty Collapse Del +| /tmp/pardes-snap/nested/cwd/nested.txt Save Tty Collapse Del | 1 hello-from-nested | 2 second-nested-line | 3 @@ -20,12 +20,12 @@ | | | -| /tmp/pardes-snap/nested/cwd/+New Save Tty Collapse Del +| /tmp/pardes-snap/nested/cwd/+New Save Tty Collapse Del | 1 == snap no-arg grid=100x31 cursor=4,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -|$ /tmp/pardes-snap/nested/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/nested/cwd Tty+bash Save Mode Filter Collapse Del | $ $(readlink /proc/$PPID/exe) | pardes: this shell is already inside pardes, and a pardes inside a pardes | is spicy. Name a file or a directory and the outer session opens it, or @@ -44,15 +44,15 @@ | | | -| /tmp/pardes-snap/nested/cwd/+New Save Tty Collapse Del +| /tmp/pardes-snap/nested/cwd/+New Save Tty Collapse Del | 1 == snap dir-arg grid=100x31 cursor=7,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -|$ /tmp/pardes-snap/nested/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/nested/cwd Tty+bash Save Mode Filter Collapse Del | $ $(readlink /proc/$PPID/exe) nestdir | $ -| /tmp/pardes-snap/nested/cwd/nestdir/ Get Tty Collapse Del +| /tmp/pardes-snap/nested/cwd/nestdir/ Get Tty Collapse Del | 1 inside-nested.txt | 2 | @@ -68,5 +68,5 @@ | | | -| /tmp/pardes-snap/nested/cwd/+New Save Tty Collapse Del +| /tmp/pardes-snap/nested/cwd/+New Save Tty Collapse Del | 1 diff --git a/test/snapshots/ninep.golden b/test/snapshots/ninep.golden index e524fa30..d10c7181 100644 --- a/test/snapshots/ninep.golden +++ b/test/snapshots/ninep.golden @@ -1,7 +1,7 @@ == snap opened grid=90x15 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext Def Refs +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse TreeContext Def Refs Del | 1 const greeting = "café λ 界 é"; | 2 | 3 pub fn choose(ok: bool) u32 { @@ -10,9 +10,9 @@ | 6 } | 7 == style opened grid=90x15 -|0: 0-89 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-89 #becfc4,#314738, -|2: 0-1 d,#add38a, 2-2 d,#314738, 3-29 #becfc4,#314738, 30-38 #dfbce5,#314738, 39-89 #becfc4,#314738, +|0: 0-1 d,#1d2824, 2-89 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-89 #becfc4,#314738, +|2: 0-1 d,#add38a, 2-28 #becfc4,#314738, 29-37 #dfbce5,#314738, 38-89 #becfc4,#314738, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-23 #e5eee5,#0d1410, 24-32 #b8d88a,#0d1410, 33-33 d,d, 34-34 d,#0d1410, 35-36 #b8d88a,#0d1410, 37-89 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-89 #59675c,#0d1410, |5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-89 #e5eee5,#0d1410, @@ -26,12 +26,12 @@ |13: 0-0 d,#608269, 1-89 d,#0d1410, |14: 0-0 d,#608269, 1-89 d,#0d1410, == 9p opened grid=90x15 cursor=7,3,block -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -@0: 0-74 #b2c3b8,#1d2824,,tagline 75-89 d,#1d2824,,tagline -|1: New Tty Find Grep Joincol Delcol -@1: 0-1 #ffffff,#887455,,tagline 2-2 d,#314738,,tagline 3-34 #becfc4,#314738,,tagline 35-89 d,#314738,,tagline -|2: /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext Def Refs -@2: 0-1 #000000,#add38a,,tagline 2-2 d,#314738,,tagline 3-29 #becfc4,#314738,,tagline 30-37 #dfbce5,#314738,,tagline 38-80 #becfc4,#314738,,tagline 81-89 d,#314738,,tagline +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +@0: 0-76 #b2c3b8,#1d2824,,tagline 77-89 d,#1d2824,,tagline +|1: New Tty Find Grep Joincol Delcol +@1: 0-1 #ffffff,#887455,,tagline 2-33 #becfc4,#314738,,tagline 34-89 d,#314738,,tagline +|2: /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse TreeContext Def Refs Del +@2: 0-1 #000000,#add38a,,tagline 2-28 #becfc4,#314738,,tagline 29-36 #dfbce5,#314738,,tagline 37-79 #becfc4,#314738,,tagline 80-89 d,#314738,,tagline |3: 1 const greeting = "café λ 界 é"; +3: 28="é" 30="λ" 32="界" 33="" 35="é" @3: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #616f64,#0d1410,b,body 7-23 #e5eee5,#0d1410,,body 24-36 #b8d88a,#0d1410,,body 37-37 #e5eee5,#0d1410,,body 38-89 d,#0d1410,,body @@ -73,7 +73,7 @@ |7: 5 return 7; @7: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-19 #e5eee5,#0d1410,,body 20-89 d,#0d1410,,body == snap edited-with-colors-off grid=90x15 cursor=7,4 -|2: * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext Def Refs +|2: */tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse TreeContext Def Refs Del |3: 1 // café λ 界 |4: 2 const greeting = "café λ 界 é"; |5: 3 @@ -83,8 +83,8 @@ |9: 7 } |10: 8 == 9p edited-with-colors-off grid=90x15 cursor=7,4,block -|2: * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext Def Refs -@2: 0-0 #000000,#add38a,,tagline 1-1 #000000,#f9cb70,b,tagline 2-2 d,#314738,,tagline 3-29 #becfc4,#314738,,tagline 30-37 #dfbce5,#314738,,tagline 38-80 #becfc4,#314738,,tagline 81-89 d,#314738,,tagline +|2: */tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse TreeContext Def Refs Del +@2: 0-0 #000000,#add38a,,tagline 1-1 #000000,#f9cb70,b,tagline 2-28 #becfc4,#314738,,tagline 29-36 #dfbce5,#314738,,tagline 37-79 #becfc4,#314738,,tagline 80-89 d,#314738,,tagline |3: 1 // café λ 界 +3: 13="é" 15="λ" 17="界" 18="" @3: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-18 #e5eee5,#0d1410,,body 19-89 d,#0d1410,,body @@ -104,7 +104,7 @@ |10: 8 @10: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-89 d,#0d1410,,body == style colors-on grid=90x15 -|2: 0-0 d,#add38a, 1-1 #000000,#f9cb70,b 2-2 #000000,#314738, 3-29 #becfc4,#314738, 30-38 #dfbce5,#314738, 39-89 #becfc4,#314738, +|2: 0-0 d,#add38a, 1-1 #000000,#f9cb70,b 2-28 #becfc4,#314738, 29-37 #dfbce5,#314738, 38-89 #becfc4,#314738, |3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-17 #b9f480,#0d1410, 18-18 d,d, 19-81 d,#0d1410, 82-82 d,#1d2824, 83-89 #b2c3b8,#1d2824, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-23 #e5eee5,#0d1410, 24-32 #b8d88a,#0d1410, 33-33 d,d, 34-34 d,#0d1410, 35-36 #b8d88a,#0d1410, 37-89 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-4 d,#0d1410, 5-89 #59675c,#0d1410, @@ -127,9 +127,9 @@ |8: 6 return 7; @8: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-10 #e5eee5,#0d1410,,body 11-16 #c9a7ed,#0d1410,,body 17-17 #e5eee5,#0d1410,,body 18-18 #f8c082,#0d1410,,body 19-19 #e5eee5,#0d1410,,body 20-89 d,#0d1410,,body == style resized grid=105x20 -|0: 0-104 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-104 #becfc4,#314738, -|2: 0-0 d,#add38a, 1-1 #000000,#f9cb70,b 2-2 #000000,#314738, 3-29 #becfc4,#314738, 30-38 #dfbce5,#314738, 39-104 #becfc4,#314738, +|0: 0-1 d,#1d2824, 2-104 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-104 #becfc4,#314738, +|2: 0-0 d,#add38a, 1-1 #000000,#f9cb70,b 2-28 #becfc4,#314738, 29-37 #dfbce5,#314738, 38-104 #becfc4,#314738, |3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-17 #b9f480,#0d1410, 18-18 d,d, 19-96 d,#0d1410, 97-97 d,#1d2824, 98-104 #b2c3b8,#1d2824, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-23 #e5eee5,#0d1410, 24-32 #b8d88a,#0d1410, 33-33 d,d, 34-34 d,#0d1410, 35-36 #b8d88a,#0d1410, 37-104 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-4 d,#0d1410, 5-104 #59675c,#0d1410, @@ -148,12 +148,12 @@ |18: 0-0 d,#608269, 1-104 d,#0d1410, |19: 0-0 d,#608269, 1-104 d,#0d1410, == 9p resized grid=105x20 cursor=7,4,block -|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -@0: 0-74 #b2c3b8,#1d2824,,tagline 75-104 d,#1d2824,,tagline -|1: New Tty Find Grep Joincol Delcol -@1: 0-1 #ffffff,#887455,,tagline 2-2 d,#314738,,tagline 3-34 #becfc4,#314738,,tagline 35-104 d,#314738,,tagline -|2: * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext Def Refs -@2: 0-0 #000000,#add38a,,tagline 1-1 #000000,#f9cb70,b,tagline 2-2 d,#314738,,tagline 3-29 #becfc4,#314738,,tagline 30-37 #dfbce5,#314738,,tagline 38-80 #becfc4,#314738,,tagline 81-104 d,#314738,,tagline +|0: Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +@0: 0-76 #b2c3b8,#1d2824,,tagline 77-104 d,#1d2824,,tagline +|1: New Tty Find Grep Joincol Delcol +@1: 0-1 #ffffff,#887455,,tagline 2-33 #becfc4,#314738,,tagline 34-104 d,#314738,,tagline +|2: */tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse TreeContext Def Refs Del +@2: 0-0 #000000,#add38a,,tagline 1-1 #000000,#f9cb70,b,tagline 2-28 #becfc4,#314738,,tagline 29-36 #dfbce5,#314738,,tagline 37-79 #becfc4,#314738,,tagline 80-104 d,#314738,,tagline |3: 1 // café λ 界 Colors +3: 13="é" 15="λ" 17="界" 18="" @3: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-18 #b9f480,#0d1410,,body 19-96 d,#0d1410,,body 97-97 d,#1d2824,,tagline 98-103 #b2c3b8,#1d2824,,tagline 104-104 d,#1d2824,,tagline @@ -191,9 +191,9 @@ |19: @19: 0-0 d,#608269,,body 1-1 d,#0d1410,,body 2-6 #59675c,#0d1410,,body 7-104 d,#0d1410,,body == snap resized grid=105x20 cursor=7,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| * /tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse Del TreeContext Def Refs +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| */tmp/pardes-snap/ninep/cwd/demo.zig Save Tty Collapse TreeContext Def Refs Del | 1 // café λ 界 Colors | 2 const greeting = "café λ 界 é"; | 3 diff --git a/test/snapshots/pagercolor.golden b/test/snapshots/pagercolor.golden index abd264d1..e84359d8 100644 --- a/test/snapshots/pagercolor.golden +++ b/test/snapshots/pagercolor.golden @@ -1,7 +1,7 @@ == snap pager grid=100x50 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -|$ /tmp/pardes-snap/pagercolor/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/pagercolor/cwd Tty+bash Save Mode Filter Collapse Del | $ printf '\033]0;title\007\033[31mred\033[m \033[1;32mbold green\033[m \033[38;2;200;100;0mrgb\033 | [m \033[4mul\033[m N\bNA\bAM\bME\bE _\bu_\bs plain\n' | $(readlink /proc/$PPID/exe) - | $ @@ -33,7 +33,7 @@ | | | -| /tmp/pardes-snap/pagercolor/cwd/+New Save Tty Collapse Del +| /tmp/pardes-snap/pagercolor/cwd/+New Save Tty Collapse Del | 1 | | @@ -41,12 +41,12 @@ | | | -| /tmp/pardes-snap/pagercolor/cwd/+Pager Save Tty Filter Collapse Del +| /tmp/pardes-snap/pagercolor/cwd/+Pager Save Tty Filter Collapse Del | red bold green rgb ul NAME us plain == style pager-colours grid=100x50 -|0: 0-99 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-99 #becfc4,#314738, -|2: 0-1 #000000,#add38a, 2-2 #000000,#314738, 3-34 #becfc4,#314738, 35-43 #dfbce5,#314738, 44-99 #becfc4,#314738, +|0: 0-1 d,#1d2824, 2-99 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-99 #becfc4,#314738, +|2: 0-1 #000000,#add38a, 2-33 #becfc4,#314738, 34-42 #dfbce5,#314738, 43-99 #becfc4,#314738, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, @@ -78,7 +78,7 @@ |31: 0-0 d,#608269, 1-99 d,#0d1410, |32: 0-0 d,#608269, 1-99 d,#0d1410, |33: 0-0 d,#608269, 1-99 d,#0d1410, -|34: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-39 #d3b0d9,#1d2824, 40-99 #b2c3b8,#1d2824, +|34: 0-1 d,#496656, 2-33 #b2c3b8,#1d2824, 34-38 #d3b0d9,#1d2824, 39-99 #b2c3b8,#1d2824, |35: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, |36: 0-0 d,#608269, 1-99 d,#0d1410, |37: 0-0 d,#608269, 1-99 d,#0d1410, @@ -86,7 +86,7 @@ |39: 0-0 d,#608269, 1-99 d,#0d1410, |40: 0-0 d,#608269, 1-99 d,#0d1410, |41: 0-0 d,#608269, 1-99 d,#0d1410, -|42: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-41 #d3b0d9,#1d2824, 42-99 #b2c3b8,#1d2824, +|42: 0-1 d,#496656, 2-33 #b2c3b8,#1d2824, 34-40 #d3b0d9,#1d2824, 41-99 #b2c3b8,#1d2824, |43: 0-0 d,#608269, 1-1 d,#0d1410, 2-5 #f1a39b,#0d1410, 6-15 #b6ce94,#0d1410,b 16-16 #b6ce94,#0d1410, 17-20 #c5917e,#0d1410, 21-22 #e5eee5,#0d1410,u 23-23 #e5eee5,#0d1410, 24-27 #e5eee5,#0d1410,b 28-28 #e5eee5,#0d1410, 29-30 #e5eee5,#0d1410,u 31-99 #e5eee5,#0d1410, |44: 0-0 d,#608269, 1-99 d,#0d1410, |45: 0-0 d,#608269, 1-99 d,#0d1410, @@ -99,19 +99,33 @@ |6: 3[m\n\033[1m+++ b/x\033[m\n\033[36m@@ -1 +1 @@\033[m\n\033[31m-old\033[m\n\033[32m+new\033[m\n' | |7: $(readlink /proc/$PPID/exe) - |8: $ -|9: /tmp/pardes-snap/pagercolor/cwd/+Diff Save Tty Diff Collapse Del LocationsConfig +|9: /tmp/pardes-snap/pagercolor/cwd/+Diff Save Tty Diff Collapse LocationsConfig Del |10: commit 0123abc |11: x:1 |12: -old |13: +new -|49: /tmp/pardes-snap/pagercolor/cwd/+Pager Save Tty Filter Diff Collapse Del +|34: +|35: +|38: /tmp/pardes-snap/pagercolor/cwd/+New Save Tty Collapse Del +|39: 1 +|42: +|43: +|46: /tmp/pardes-snap/pagercolor/cwd/+Pager Save Tty Filter Collapse Del +|47: red bold green rgb ul NAME us plain == style pager-diff-colours grid=100x50 |6: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, |7: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, |8: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, -|9: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-40 #d3b0d9,#1d2824, 41-99 #b2c3b8,#1d2824, +|9: 0-1 d,#496656, 2-33 #b2c3b8,#1d2824, 34-39 #d3b0d9,#1d2824, 40-99 #b2c3b8,#1d2824, |10: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #e5eee5,#0d1410, |11: 0-0 d,#608269, 1-1 d,#0d1410, 2-99 #59675c,#0d1410, |12: 0-0 d,#608269, 1-1 d,#0d1410, 2-2 #f1a39b,#1a1d18,b 3-99 #f8c082,#1a1d18, |13: 0-0 d,#608269, 1-1 d,#0d1410, 2-2 #b6ce94,#171f18,b 3-99 #b8d88a,#171f18, -|49: 0-1 d,#496656, 2-2 d,#1d2824, 3-34 #b2c3b8,#1d2824, 35-41 #d3b0d9,#1d2824, 42-99 #b2c3b8,#1d2824, +|34: 0-0 d,#608269, 1-99 d,#0d1410, +|35: 0-0 d,#608269, 1-99 d,#0d1410, +|38: 0-1 d,#496656, 2-33 #b2c3b8,#1d2824, 34-38 #d3b0d9,#1d2824, 39-99 #b2c3b8,#1d2824, +|39: 0-0 d,#608269, 1-4 d,#0d1410, 5-99 #59675c,#0d1410, +|42: 0-0 d,#608269, 1-99 d,#0d1410, +|43: 0-0 d,#608269, 1-99 d,#0d1410, +|46: 0-1 d,#496656, 2-33 #b2c3b8,#1d2824, 34-40 #d3b0d9,#1d2824, 41-99 #b2c3b8,#1d2824, +|47: 0-0 d,#608269, 1-1 d,#0d1410, 2-5 #f1a39b,#0d1410, 6-15 #b6ce94,#0d1410,b 16-16 #b6ce94,#0d1410, 17-20 #c5917e,#0d1410, 21-22 #e5eee5,#0d1410,u 23-23 #e5eee5,#0d1410, 24-27 #e5eee5,#0d1410,b 28-28 #e5eee5,#0d1410, 29-30 #e5eee5,#0d1410,u 31-99 #e5eee5,#0d1410, diff --git a/test/snapshots/pipe.golden b/test/snapshots/pipe.golden index 2fd54c27..8818499e 100644 --- a/test/snapshots/pipe.golden +++ b/test/snapshots/pipe.golden @@ -1,12 +1,12 @@ == snap prompt grid=180x13 cursor=179,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/pipe/cwd/pipe.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/pipe/cwd/pipe.txt Save Tty Collapse Del | 1 alpha beta |tr a-z A-Z | 2 gamma delta == snap filtered grid=180x13 cursor=17,3 -|2: * /tmp/pardes-snap/pipe/cwd/pipe.txt Save Tty Collapse Del +|2: */tmp/pardes-snap/pipe/cwd/pipe.txt Save Tty Collapse Del |3: 1 ALPHA BETA == snap undone grid=180x13 cursor=17,3 -|2: /tmp/pardes-snap/pipe/cwd/pipe.txt Save Tty Collapse Del +|2: /tmp/pardes-snap/pipe/cwd/pipe.txt Save Tty Collapse Del |3: 1 alpha beta diff --git a/test/snapshots/psearch.golden b/test/snapshots/psearch.golden index e830a206..2a845a34 100644 --- a/test/snapshots/psearch.golden +++ b/test/snapshots/psearch.golden @@ -1,7 +1,7 @@ == snap output grid=140x31 cursor=4,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/psearch/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/psearch/cwd Tty+bash Save Mode Filter Collapse Del | printf 'x MA''RK a\nzz\nx MA''RK b\nzz\nx MA''RK c\n' | x MARK a | zz @@ -20,13 +20,13 @@ | | | -| /tmp/pardes-snap/psearch/cwd/+New Save Tty Collapse Del +| /tmp/pardes-snap/psearch/cwd/+New Save Tty Collapse Del | 1 == snap typing grid=140x31 cursor=139,3 |3: printf 'x MA''RK a\nzz\nx MA''RK b\nzz\nx MA''RK c\n' /MARK == snap results grid=140x31 cursor=7,4 |3: printf 'x MA''RK a\nzz\nx MA''RK b\nzz\nx MA''RK c\n' -|10: /tmp/pardes-snap/psearch/cwd/+Search Save Tty Collapse Del LocationsConfig +|10: /tmp/pardes-snap/psearch/cwd/+Search Save Tty Collapse LocationsConfig Del |11: 1 @p1:2:3-6 |12: 2 x MARK a |13: 3 @p1:4:3-6 @@ -35,9 +35,9 @@ |16: 6 x MARK c |17: 7 == style results grid=140x31 -|0: 0-139 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-139 #becfc4,#314738, -|2: 0-1 d,#add38a, 2-2 d,#314738, 3-31 #becfc4,#314738, 32-40 #dfbce5,#314738, 41-139 #becfc4,#314738, +|0: 0-1 d,#1d2824, 2-139 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-139 #becfc4,#314738, +|2: 0-1 d,#add38a, 2-30 #becfc4,#314738, 31-39 #dfbce5,#314738, 40-139 #becfc4,#314738, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-3 #e5eee5,#0d1410, 4-7 #f5f7ee,#3c614a, 8-8 #f5f7ee,#0d1410, 9-139 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, @@ -45,7 +45,7 @@ |7: 0-0 d,#608269, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, |8: 0-0 d,#608269, 1-1 d,#0d1410, 2-139 #e5eee5,#0d1410, |9: 0-0 d,#608269, 1-139 d,#0d1410, -|10: 0-1 d,#496656, 2-2 d,#1d2824, 3-31 #b2c3b8,#1d2824, 32-39 #d3b0d9,#1d2824, 40-139 #b2c3b8,#1d2824, +|10: 0-1 d,#496656, 2-30 #b2c3b8,#1d2824, 31-38 #d3b0d9,#1d2824, 39-139 #b2c3b8,#1d2824, |11: 0-0 d,#608269, 1-4 d,#0d1410, 5-139 #59675c,#0d1410, |12: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-8 #e5eee5,#0d1410, 9-12 #f7e4a5,#5e4923, 13-13 #f7e4a5,#0d1410, 14-139 #e5eee5,#0d1410, |13: 0-0 d,#608269, 1-4 d,#0d1410, 5-139 #59675c,#0d1410, @@ -56,7 +56,7 @@ |18: 0-0 d,#608269, 1-139 d,#0d1410, |19: 0-0 d,#608269, 1-139 d,#0d1410, |20: 0-0 d,#608269, 1-139 d,#0d1410, -|21: 0-1 d,#496656, 2-2 d,#1d2824, 3-31 #b2c3b8,#1d2824, 32-36 #d3b0d9,#1d2824, 37-139 #b2c3b8,#1d2824, +|21: 0-1 d,#496656, 2-30 #b2c3b8,#1d2824, 31-35 #d3b0d9,#1d2824, 36-139 #b2c3b8,#1d2824, |22: 0-0 d,#608269, 1-4 d,#0d1410, 5-139 #59675c,#0d1410, |23: 0-0 d,#608269, 1-139 d,#0d1410, |24: 0-0 d,#608269, 1-139 d,#0d1410, @@ -69,13 +69,13 @@ == snap second grid=140x31 cursor=7,6 == snap back grid=140x31 cursor=7,4 == snap nomatch grid=140x31 cursor=7,13 -|24: /tmp/pardes-snap/psearch/cwd/+Search Save Tty Collapse Del LocationsConfig +|24: /tmp/pardes-snap/psearch/cwd/+Search Save Tty Collapse LocationsConfig Del |25: 1 == snap ttyinert grid=140x31 cursor=4,9 -|2: $ /tmp/pardes-snap/psearch/cwd Tty+bash Save Mode Filter Collapse Del +|2: $ /tmp/pardes-snap/psearch/cwd Tty+bash Save Mode Filter Collapse Del |3: $ printf 'x MA''RK a\nzz\nx MA''RK b\nzz\nx MA''RK c\n' |9: $ == snap rightsearch grid=140x31 cursor=7,6 -|2: /tmp/pardes-snap/psearch/cwd Tty+bash Save Mode Filter Collapse Del +|2: /tmp/pardes-snap/psearch/cwd Tty+bash Save Mode Filter Collapse Del |3: printf 'x MA''RK a\nzz\nx MA''RK b\nzz\nx MA''RK c\n' |9: diff --git a/test/snapshots/reflow.golden b/test/snapshots/reflow.golden index 17c42d0d..db4b5a77 100644 --- a/test/snapshots/reflow.golden +++ b/test/snapshots/reflow.golden @@ -1,7 +1,7 @@ == snap widened grid=200x25 cursor=4,16 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -|$ /tmp/pardes-snap/reflow/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/reflow/cwd Tty+bash Save Mode Filter Collapse Del | yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy | yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy | yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy @@ -16,5 +16,5 @@ | yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy | yyyyyyyyyyyyyyyyyyyyyyyyyyyyyydone | $ -| /tmp/pardes-snap/reflow/cwd/+New Save Tty Collapse Del +| /tmp/pardes-snap/reflow/cwd/+New Save Tty Collapse Del | 1 diff --git a/test/snapshots/respawn.golden b/test/snapshots/respawn.golden index 1e6425d2..4810f9d3 100644 --- a/test/snapshots/respawn.golden +++ b/test/snapshots/respawn.golden @@ -1,10 +1,10 @@ == snap respawn grid=140x31 cursor=4,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/respawn/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/respawn/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/respawn/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/respawn/cwd Tty+bash Save Mode Filter Collapse Del | ls ls | -|$ /tmp/pardes-snap/respawn/cwd Tty+bash Save Mode Filter Collapse Del +|$ /tmp/pardes-snap/respawn/cwd Tty+bash Save Mode Filter Collapse Del | $ ls | $ echo RESP''AWNOK | RESPAWNOK diff --git a/test/snapshots/restore.golden b/test/snapshots/restore.golden index 0bb53676..a8e39308 100644 --- a/test/snapshots/restore.golden +++ b/test/snapshots/restore.golden @@ -1,12 +1,12 @@ == snap dumped grid=100x31 cursor=4,6 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit Restore /tmp/pardes-snap -| New Tty Find Grep Joincol Delcol -|$ /tmp/pardes-snap/restore/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit Restore /tmp/pardes-sn +| New Tty Find Grep Joincol Delcol +|$ /tmp/pardes-snap/restore/cwd Tty+bash Save Mode Filter Collapse Del | $ ls Dump | $ echo KEEP''ME | KEEPME | $ == snap restored grid=100x31 cursor=4,8 -|2: /tmp/pardes-snap/restore/cwd Tty+bash Save Mode Filter Collapse Del +|2: /tmp/pardes-snap/restore/cwd Tty+bash Save Mode Filter Collapse Del |3: $ ls |7: ── restored history ── diff --git a/test/snapshots/rsearch.golden b/test/snapshots/rsearch.golden index 870831b4..d69feb7a 100644 --- a/test/snapshots/rsearch.golden +++ b/test/snapshots/rsearch.golden @@ -1,17 +1,17 @@ == snap opened grid=210x31 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/rsearch/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/rsearch/cwd Tty+bash Save Mode Filter Collapse Del | ls | code.txt sub | -| /tmp/pardes-snap/rsearch/cwd/code.txt Save Tty Collapse Del +| /tmp/pardes-snap/rsearch/cwd/code.txt Save Tty Collapse Del | 1 run count_x now | 2 open sub/dep.txt:3 here | 3 count_x again | 4 pick two words == snap search grid=210x31 cursor=13,9 -|11: /tmp/pardes-snap/rsearch/cwd/+Search Save Tty Collapse Del LocationsConfig +|11: /tmp/pardes-snap/rsearch/cwd/+Search Save Tty Collapse LocationsConfig Del |12: 1 code.txt:1:5-11 |13: 2 run count_x now |14: 3 code.txt:3:1-7 @@ -24,7 +24,7 @@ |15: |16: == snap path-open grid=210x31 cursor=16,17 -|14: /tmp/pardes-snap/rsearch/cwd/sub/dep.txt Save Tty Collapse Del +|14: /tmp/pardes-snap/rsearch/cwd/sub/dep.txt Save Tty Collapse Del |15: 1 d1 |16: 2 d2 |17: 3 DEPTARGET diff --git a/test/snapshots/savepane.golden b/test/snapshots/savepane.golden index bea7146b..256b0074 100644 --- a/test/snapshots/savepane.golden +++ b/test/snapshots/savepane.golden @@ -1,7 +1,7 @@ == snap scratch grid=100x31 cursor=20,18 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/savepane/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/savepane/cwd Tty+bash Save Mode Filter Collapse Del | ls | | @@ -16,13 +16,13 @@ | | | -| * /tmp/pardes-snap/savepane/cwd/+New Save Tty Collapse Del +| */tmp/pardes-snap/savepane/cwd/+New Save Tty Collapse Del | 1 scratch bytes == snap prompt grid=100x31 cursor=99,19 |18: 1 scratch bytes Save |19: Save /tmp/pardes-snap/savepane/cwd/ == snap saved grid=100x31 cursor=20,18 -|17: /tmp/pardes-snap/savepane/cwd/saved.txt Save Tty Collapse Del +|17: /tmp/pardes-snap/savepane/cwd/saved.txt Save Tty Collapse Del |18: 1 scratch bytes --:--:-- saved /tmp/pardes-snap/savepane/cwd/saved.txt |19: == file bytes diff --git a/test/snapshots/scroll.golden b/test/snapshots/scroll.golden index 44b6b264..25bcd6ac 100644 --- a/test/snapshots/scroll.golden +++ b/test/snapshots/scroll.golden @@ -1,8 +1,8 @@ == snap bottom grid=100x31 cursor=4,16 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/scroll/cwd Tty+bash Save Mode /tmp/pardes-snap/scroll/cwd Tty+bash Save Mode -| Filter Collapse Del Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/scroll/cwd Tty+bash Save Mode F /tmp/pardes-snap/scroll/cwd Tty+bash Save Mode F +| ilter Collapse Del ilter Collapse Del | 189 ls | 190 s.txt | 191 @@ -16,8 +16,8 @@ | 199 | 200 | -| /tmp/pardes-snap/scroll/cwd Tty+bash Save Mode -| Filter Collapse Del +| /tmp/pardes-snap/scroll/cwd Tty+bash Save Mode F +| ilter Collapse Del | ls | s.txt == snap wheel3 grid=100x31 cursor=4,16 @@ -77,10 +77,10 @@ |15: 193 |16: 194 == style wheel-down grid=100x31 -|0: 0-99 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-49 #becfc4,#314738, 50-51 #becfc4,#887455, 52-52 #becfc4,#1d2824, 53-99 #b2c3b8,#1d2824, -|2: 0-1 d,#add38a, 2-2 d,#314738, 3-30 #becfc4,#314738, 31-39 #dfbce5,#314738, 40-49 #becfc4,#314738, 50-51 #becfc4,#496656, 52-52 #becfc4,#1d2824, 53-80 #b2c3b8,#1d2824, 81-89 #d3b0d9,#1d2824, 90-99 #b2c3b8,#1d2824, -|3: 0-2 d,#314738, 3-49 #becfc4,#314738, 50-52 #becfc4,#1d2824, 53-99 #b2c3b8,#1d2824, +|0: 0-1 d,#1d2824, 2-99 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-49 #becfc4,#314738, 50-51 #becfc4,#887455, 52-99 #b2c3b8,#1d2824, +|2: 0-1 d,#add38a, 2-29 #becfc4,#314738, 30-38 #dfbce5,#314738, 39-49 #becfc4,#314738, 50-51 #becfc4,#496656, 52-79 #b2c3b8,#1d2824, 80-88 #d3b0d9,#1d2824, 89-99 #b2c3b8,#1d2824, +|3: 0-1 d,#314738, 2-49 #becfc4,#314738, 50-51 #becfc4,#1d2824, 52-99 #b2c3b8,#1d2824, |4: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 #e5eee5,#608269, 51-99 #e5eee5,#0d1410, |5: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 #e5eee5,#608269, 51-99 #e5eee5,#0d1410, |6: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 #e5eee5,#608269, 51-99 #e5eee5,#0d1410, @@ -94,8 +94,8 @@ |14: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 #e5eee5,#608269, 51-99 #e5eee5,#0d1410, |15: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 #e5eee5,#608269, 51-99 #e5eee5,#0d1410, |16: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 #e5eee5,#608269, 51-99 #e5eee5,#0d1410, -|17: 0-1 d,#496656, 2-2 d,#1d2824, 3-30 #b2c3b8,#1d2824, 31-39 #d3b0d9,#1d2824, 40-49 #b2c3b8,#1d2824, 50-50 #b2c3b8,#608269, 51-99 #b2c3b8,#0d1410, -|18: 0-2 d,#1d2824, 3-49 #b2c3b8,#1d2824, 50-50 #b2c3b8,#608269, 51-99 #b2c3b8,#0d1410, +|17: 0-1 d,#496656, 2-29 #b2c3b8,#1d2824, 30-38 #d3b0d9,#1d2824, 39-49 #b2c3b8,#1d2824, 50-50 #b2c3b8,#608269, 51-99 #b2c3b8,#0d1410, +|18: 0-1 d,#1d2824, 2-49 #b2c3b8,#1d2824, 50-50 #b2c3b8,#608269, 51-99 #b2c3b8,#0d1410, |19: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 #e5eee5,#608269, 51-99 #e5eee5,#0d1410, |20: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 #e5eee5,#608269, 51-99 #e5eee5,#0d1410, |21: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-99 d,#0d1410, diff --git a/test/snapshots/scrolloff.golden b/test/snapshots/scrolloff.golden index 299df49d..b56d2c36 100644 --- a/test/snapshots/scrolloff.golden +++ b/test/snapshots/scrolloff.golden @@ -1,11 +1,11 @@ == snap top grid=210x16 cursor=7,7 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/scrolloff/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/scrolloff/cwd Tty+bash Save Mode Filter Collapse Del | ls | g.txt | -| /tmp/pardes-snap/scrolloff/cwd/g.txt Save Tty Collapse Del +| /tmp/pardes-snap/scrolloff/cwd/g.txt Save Tty Collapse Del | 1 line 1 | 2 line 2 | 3 line 3 diff --git a/test/snapshots/selarg.golden b/test/snapshots/selarg.golden index 741864ef..33338c6e 100644 --- a/test/snapshots/selarg.golden +++ b/test/snapshots/selarg.golden @@ -1,8 +1,8 @@ == snap kept grid=100x31 cursor=6,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/selarg/cwd Tty+bash Save Mode /tmp/pardes-snap/selarg/cwd Tty+bash Save Mode -| Filter Collapse Del Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/selarg/cwd Tty+bash Save Mode F /tmp/pardes-snap/selarg/cwd Tty+bash Save Mode F +| ilter Collapse Del ilter Collapse Del | ZZARG ZZVEE ./c.sh | | @@ -16,8 +16,8 @@ | | | -| /tmp/pardes-snap/selarg/cwd Tty+bash Save Mode -| Filter Collapse Del +| /tmp/pardes-snap/selarg/cwd Tty+bash Save Mode F +| ilter Collapse Del | ls | s.txt == snap crosspane grid=100x31 cursor=6,4 diff --git a/test/snapshots/selregex.golden b/test/snapshots/selregex.golden index 480ad8a2..3fdab698 100644 --- a/test/snapshots/selregex.golden +++ b/test/snapshots/selregex.golden @@ -1,7 +1,7 @@ == snap prompt-armed grid=160x25 cursor=159,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse Del TreeContext Def Refs +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse TreeContext Def Refs Del | 1 const one = 1; Select / | 2 const two = 2; | 3 const three = 3; @@ -9,9 +9,9 @@ == snap preview grid=160x25 cursor=159,3 |3: 1 const one = 1; Select /const == style preview grid=160x25 -|0: 0-159 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-159 #becfc4,#314738, -|2: 0-1 d,#add38a, 2-2 d,#314738, 3-32 #becfc4,#314738, 33-38 #dfbce5,#314738, 39-159 #becfc4,#314738, +|0: 0-1 d,#1d2824, 2-159 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-159 #becfc4,#314738, +|2: 0-1 d,#add38a, 2-31 #becfc4,#314738, 32-37 #dfbce5,#314738, 38-159 #becfc4,#314738, |3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#3c614a, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-143 #e5eee5,#0d1410, 144-145 #e5eee5,#1d2824, 146-159 #b2c3b8,#1d2824, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-159 #e5eee5,#0d1410, @@ -51,12 +51,12 @@ |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-159 #e5eee5,#0d1410, == snap commented grid=160x25 cursor=14,3 -|2: * /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse Del TreeContext Def Refs +|2: */tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse TreeContext Def Refs Del |3: 1 // const one = 1; |4: 2 // const two = 2; |5: 3 // const three = 3; == snap uncommented grid=160x25 cursor=11,3 -|2: /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse Del TreeContext Def Refs +|2: /tmp/pardes-snap/selregex/cwd/m.zig Save Tty Collapse TreeContext Def Refs Del |3: 1 const one = 1; |4: 2 const two = 2; |5: 3 const three = 3; diff --git a/test/snapshots/shellset.golden b/test/snapshots/shellset.golden index 9d566be7..21875eca 100644 --- a/test/snapshots/shellset.golden +++ b/test/snapshots/shellset.golden @@ -1,13 +1,13 @@ == snap boot grid=90x21 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/shellset/cwd/cmd.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/shellset/cwd/cmd.txt Save Tty Collapse Del | 1 Shell zznosuchshell == snap builtin-ran grid=90x21 cursor=25,3 |3: Shell: shell "zznosuchshell" not found (a name on the usual paths, or a path to one) == snap fallback-shell grid=90x21 cursor=49,6 -|1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -|2: /tmp/pardes-snap/shellset/cwd/cmd.txt Save /tmp/pardes-snap/shellset/cwd Tty+bash Sav -|3: Tty Collapse Del e Mode Filter Collapse Del +|1: New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/shellset/cwd/cmd.txt Save /tmp/pardes-snap/shellset/cwd Tty+bash Save +|3: Tty Collapse Del Mode Filter Collapse Del |4: 1 Shell zznosuchshell ls |5: cmd.txt zmarkfile.txt diff --git a/test/snapshots/shrinktag.golden b/test/snapshots/shrinktag.golden index 6e64d89b..dc27a579 100644 --- a/test/snapshots/shrinktag.golden +++ b/test/snapshots/shrinktag.golden @@ -1,8 +1,8 @@ == snap before grid=100x31 cursor=4,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/shrinktag/cwd Tty+bash Save Mo /tmp/pardes-snap/shrinktag/cwd Tty+bash Save Mo -| de Filter Collapse Del de Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/shrinktag/cwd Tty+bash Save Mod /tmp/pardes-snap/shrinktag/cwd Tty+bash Save Mod +| e Filter Collapse Del e Filter Collapse Del | ls ls | w.txt w.txt | @@ -16,15 +16,15 @@ | | | -| /tmp/pardes-snap/shrinktag/cwd Tty+bash Save Mo -| de Filter Collapse Del +| /tmp/pardes-snap/shrinktag/cwd Tty+bash Save Mod +| e Filter Collapse Del | ls | w.txt == snap shrunk grid=100x31 cursor=4,9 |4: w.txt ls |5: w.txt -|6: /tmp/pardes-snap/shrinktag/cwd Tty+bash Save Mo -|7: de Filter Collapse Del +|6: /tmp/pardes-snap/shrinktag/cwd Tty+bash Save Mod +|7: e Filter Collapse Del |8: ls |9: w.txt |17: @@ -40,8 +40,8 @@ |7: |8: echo one; echo two |9: -|17: /tmp/pardes-snap/shrinktag/cwd Tty+bash Save Mo -|18: de Filter Collapse Del +|17: /tmp/pardes-snap/shrinktag/cwd Tty+bash Save Mod +|18: e Filter Collapse Del |19: ls |20: w.txt == snap bottom-shrunk grid=100x31 cursor=4,9 @@ -49,6 +49,6 @@ |18: |19: |20: -|27: /tmp/pardes-snap/shrinktag/cwd Tty+bash Save Mo -|28: de Filter Collapse Del +|27: /tmp/pardes-snap/shrinktag/cwd Tty+bash Save Mod +|28: e Filter Collapse Del |29: w.txt diff --git a/test/snapshots/splitparent.golden b/test/snapshots/splitparent.golden index f83bbb66..0e870a37 100644 --- a/test/snapshots/splitparent.golden +++ b/test/snapshots/splitparent.golden @@ -1,35 +1,35 @@ == snap shrunk grid=100x31 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/splitparent/cwd Tty+bash Save /tmp/pardes-snap/splitparent/cwd Tty+bash Save -| Mode Filter Collapse Del Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/splitparent/cwd Tty+bash Save M /tmp/pardes-snap/splitparent/cwd Tty+bash Save M +| ode Filter Collapse Del ode Filter Collapse Del | ls ls | -| /tmp/pardes-snap/splitparent/cwd Tty+bash Save -| Mode Filter Collapse Del +| /tmp/pardes-snap/splitparent/cwd Tty+bash Save M +| ode Filter Collapse Del | ls == snap swap-parent grid=100x31 cursor=4,13 -|10: /tmp/pardes-snap/splitparent/cwd Tty+bash Save -|11: Mode Filter Collapse Del +|10: /tmp/pardes-snap/splitparent/cwd Tty+bash Save M +|11: ode Filter Collapse Del |12: ls == snap tallest grid=100x6 cursor=4,5 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/splitparent/cwd Tty+bash Save /tmp/pardes-snap/splitparent/cwd Tty+bash Save -| /tmp/pardes-snap/splitparent/cwd Tty+bash Save Mode Filter Collapse Del -| /tmp/pardes-snap/splitparent/cwd Tty+bash Save ls +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/splitparent/cwd Tty+bash Save M /tmp/pardes-snap/splitparent/cwd Tty+bash Save M +| /tmp/pardes-snap/splitparent/cwd Tty+bash Save M ode Filter Collapse Del +| /tmp/pardes-snap/splitparent/cwd Tty+bash Save M ls | e in that column: each keeps its tag and 2 rows == snap regrown grid=100x31 cursor=4,13 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/splitparent/cwd Tty+bash Save /tmp/pardes-snap/splitparent/cwd Tty+bash Save -| Mode Filter Collapse Del Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/splitparent/cwd Tty+bash Save M /tmp/pardes-snap/splitparent/cwd Tty+bash Save M +| ode Filter Collapse Del ode Filter Collapse Del | ls ls | -| /tmp/pardes-snap/splitparent/cwd Tty+bash Save -| Mode Filter Collapse Del +| /tmp/pardes-snap/splitparent/cwd Tty+bash Save M +| ode Filter Collapse Del | ls | -| /tmp/pardes-snap/splitparent/cwd Tty+bash Save -| Mode Filter Collapse Del +| /tmp/pardes-snap/splitparent/cwd Tty+bash Save M +| ode Filter Collapse Del | e in that column: each keeps its tag and 2 rows diff --git a/test/snapshots/stepgrain.golden b/test/snapshots/stepgrain.golden index 7c445492..3101b920 100644 --- a/test/snapshots/stepgrain.golden +++ b/test/snapshots/stepgrain.golden @@ -1,10 +1,10 @@ == snap results grid=150x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/stepgrain/cwd/a.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/stepgrain/cwd/a.txt Save Tty Collapse Del | 1 hello ZQMARK one | 2 see also sub/b.txt for ZQMARK two -| /tmp/pardes-snap/stepgrain/cwd/+Search Save Tty Collapse Del LocationsConfig +| /tmp/pardes-snap/stepgrain/cwd/+Search Save Tty Collapse LocationsConfig Del | 1 a.txt:1:7-12 | 2 hello ZQMARK one | 3 a.txt:2:24-29 @@ -14,12 +14,12 @@ | 7 == snap step-row1 grid=150x31 cursor=7,6 == style step-row1 grid=150x31 -|0: 0-149 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-149 #becfc4,#314738, -|2: 0-1 d,#496656, 2-2 d,#1d2824, 3-33 #b2c3b8,#1d2824, 34-39 #d3b0d9,#1d2824, 40-149 #b2c3b8,#1d2824, +|0: 0-1 d,#1d2824, 2-149 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-149 #becfc4,#314738, +|2: 0-1 d,#496656, 2-32 #b2c3b8,#1d2824, 33-38 #d3b0d9,#1d2824, 39-149 #b2c3b8,#1d2824, |3: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-149 #e5eee5,#0d1410, -|5: 0-1 d,#add38a, 2-2 d,#314738, 3-33 #becfc4,#314738, 34-41 #dfbce5,#314738, 42-149 #becfc4,#314738, +|5: 0-1 d,#add38a, 2-32 #becfc4,#314738, 33-40 #dfbce5,#314738, 41-149 #becfc4,#314738, |6: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-18 #f5f7ee,#3c614a, 19-149 #f5f7ee,#0d1410, |7: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-12 #e5eee5,#0d1410, 13-18 #f7e4a5,#5e4923, 19-19 #f7e4a5,#0d1410, 20-149 #e5eee5,#0d1410, |8: 0-0 d,#608269, 1-4 d,#0d1410, 5-149 #59675c,#0d1410, @@ -52,7 +52,7 @@ == snap step-row3 grid=150x31 cursor=7,10 == snap step-wrap grid=150x31 cursor=7,6 == snap blank-in-path grid=150x31 cursor=7,6 -|5: /tmp/pardes-snap/stepgrain/cwd/+Search Save Tty Collapse Del +|5: /tmp/pardes-snap/stepgrain/cwd/+Search Save Tty Collapse Del |6: 1 two words.txt |7: 2 |8: @@ -69,5 +69,5 @@ |11: 0-0 d,#608269, 1-149 d,#0d1410, |12: 0-0 d,#608269, 1-149 d,#0d1410, == snap blank-opened grid=150x31 cursor=7,9 -|8: /tmp/pardes-snap/stepgrain/cwd/two words.txt Save Tty Collapse Del +|8: /tmp/pardes-snap/stepgrain/cwd/two words.txt Save Tty Collapse Del |9: 1 diff --git a/test/snapshots/syntax.golden b/test/snapshots/syntax.golden index 43bfe485..c4f44b86 100644 --- a/test/snapshots/syntax.golden +++ b/test/snapshots/syntax.golden @@ -1,12 +1,12 @@ == snap zig-open grid=150x31 cursor=7,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/syntax/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/syntax/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/syntax/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/syntax/cwd Tty+bash Save Mode Filter Collapse Del | ls ls | demo.zig demo.zig | -| /tmp/pardes-snap/syntax/cwd/demo.zig Save Tty Collapse Del TreeContext D -| ef Refs +| /tmp/pardes-snap/syntax/cwd/demo.zig Save Tty Collapse TreeContext Def Re +| fs Del | 1 const std = @import("std"); // greet | 2 pub fn main() void { | 3 var x: u32 = 42; @@ -16,18 +16,18 @@ | | | -| /tmp/pardes-snap/syntax/cwd Tty+bash Save Mode Filter Collapse Del +| /tmp/pardes-snap/syntax/cwd Tty+bash Save Mode Filter Collapse Del | ls | demo.zig == style zig-open grid=150x31 -|0: 0-149 #b2c3b8,#1d2824, -|1: 0-1 d,#887455, 2-2 d,#314738, 3-74 #becfc4,#314738, 75-76 #becfc4,#887455, 77-77 #becfc4,#1d2824, 78-149 #b2c3b8,#1d2824, -|2: 0-1 d,#496656, 2-2 d,#1d2824, 3-30 #b2c3b8,#1d2824, 31-39 #d3b0d9,#1d2824, 40-74 #b2c3b8,#1d2824, 75-76 #b2c3b8,#496656, 77-105 #b2c3b8,#1d2824, 106-114 #d3b0d9,#1d2824, 115-149 #b2c3b8,#1d2824, +|0: 0-1 d,#1d2824, 2-149 #b2c3b8,#1d2824, +|1: 0-1 d,#887455, 2-74 #becfc4,#314738, 75-76 #becfc4,#887455, 77-149 #b2c3b8,#1d2824, +|2: 0-1 d,#496656, 2-29 #b2c3b8,#1d2824, 30-38 #d3b0d9,#1d2824, 39-74 #b2c3b8,#1d2824, 75-76 #b2c3b8,#496656, 77-104 #b2c3b8,#1d2824, 105-113 #d3b0d9,#1d2824, 114-149 #b2c3b8,#1d2824, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, -|6: 0-1 d,#add38a, 2-2 d,#314738, 3-30 #becfc4,#314738, 31-39 #dfbce5,#314738, 40-74 #becfc4,#314738, 75-75 #becfc4,#608269, 76-149 #becfc4,#0d1410, -|7: 0-2 d,#314738, 3-74 #becfc4,#314738, 75-75 #becfc4,#608269, 76-149 #becfc4,#0d1410, +|6: 0-1 d,#add38a, 2-29 #becfc4,#314738, 30-38 #dfbce5,#314738, 39-74 #becfc4,#314738, 75-75 #becfc4,#608269, 76-149 #becfc4,#0d1410, +|7: 0-1 d,#314738, 2-74 #becfc4,#314738, 75-75 #becfc4,#608269, 76-149 #becfc4,#0d1410, |8: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-18 #e5eee5,#0d1410, 19-25 #c9a7ed,#0d1410, 26-26 #e5eee5,#0d1410, 27-31 #b8d88a,#0d1410, 32-34 #e5eee5,#0d1410, 35-74 #b9f480,#0d1410, 75-75 #b9f480,#608269, 76-149 #b9f480,#0d1410, |9: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-13 #c9a7ed,#0d1410, 14-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |10: 0-0 d,#608269, 1-4 d,#0d1410, 5-10 #59675c,#0d1410, 11-23 #e5eee5,#0d1410, 24-25 #f8c082,#0d1410, 26-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, @@ -37,7 +37,7 @@ |14: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, |15: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, |16: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, -|17: 0-1 d,#496656, 2-2 d,#1d2824, 3-30 #b2c3b8,#1d2824, 31-39 #d3b0d9,#1d2824, 40-74 #b2c3b8,#1d2824, 75-75 #b2c3b8,#608269, 76-149 #b2c3b8,#0d1410, +|17: 0-1 d,#496656, 2-29 #b2c3b8,#1d2824, 30-38 #d3b0d9,#1d2824, 39-74 #b2c3b8,#1d2824, 75-75 #b2c3b8,#608269, 76-149 #b2c3b8,#0d1410, |18: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |19: 0-0 d,#608269, 1-1 d,#0d1410, 2-74 #e5eee5,#0d1410, 75-75 #e5eee5,#608269, 76-149 #e5eee5,#0d1410, |20: 0-0 d,#608269, 1-74 d,#0d1410, 75-75 d,#608269, 76-149 d,#0d1410, diff --git a/test/snapshots/tag.golden b/test/snapshots/tag.golden index 0d20859a..6e86f042 100644 --- a/test/snapshots/tag.golden +++ b/test/snapshots/tag.golden @@ -1,7 +1,7 @@ -== snap tag-focus grid=150x31 cursor=36,2 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/tag/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/tag/cwd Tty+bash Save Mode Filter Collapse Del +== snap tag-focus grid=150x31 cursor=35,2 +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/tag/cwd Tty+bash Save Mode Filter Collapse Del /tmp/pardes-snap/tag/cwd Tty+bash Save Mode Filter Collapse Del | ls ls | t.txt t.txt | @@ -16,15 +16,15 @@ | | | -| /tmp/pardes-snap/tag/cwd Tty+bash Save Mode Filter Collapse Del +| /tmp/pardes-snap/tag/cwd Tty+bash Save Mode Filter Collapse Del | ls | t.txt -== snap tag-typed grid=150x31 cursor=42,2 -|2: /tmp/pardes-snap/tag/cwd Tty+bash t.txt Save Mode Filter Collapse Del /tmp/pardes-snap/tag/cwd Tty+bash Save Mode Filter Collapse Del -== snap tag-del grid=150x31 cursor=38,2 -|2: /tmp/pardes-snap/tag/cwd Tty+bash t Save Mode Filter Collapse Del /tmp/pardes-snap/tag/cwd Tty+bash Save Mode Filter Collapse Del +== snap tag-typed grid=150x31 cursor=41,2 +|2: /tmp/pardes-snap/tag/cwd Tty+bash t.txt Save Mode Filter Collapse Del /tmp/pardes-snap/tag/cwd Tty+bash Save Mode Filter Collapse Del +== snap tag-del grid=150x31 cursor=37,2 +|2: /tmp/pardes-snap/tag/cwd Tty+bash t Save Mode Filter Collapse Del /tmp/pardes-snap/tag/cwd Tty+bash Save Mode Filter Collapse Del == snap tag-exit grid=150x31 cursor=4,5 -|2: /tmp/pardes-snap/tag/cwd Tty+bash t.txt Save Mode Filter Collapse Del /tmp/pardes-snap/tag/cwd Tty+bash Save Mode Filter Collapse Del +|2: /tmp/pardes-snap/tag/cwd Tty+bash t.txt Save Mode Filter Collapse Del /tmp/pardes-snap/tag/cwd Tty+bash Save Mode Filter Collapse Del == snap tag-look grid=150x31 cursor=7,7 -|6: /tmp/pardes-snap/tag/cwd/t.txt Save Tty Collapse Del +|6: /tmp/pardes-snap/tag/cwd/t.txt Save Tty Collapse Del |7: 1 ZZLOOKED diff --git a/test/snapshots/tagalign.golden b/test/snapshots/tagalign.golden index a557ff95..0fa4807a 100644 --- a/test/snapshots/tagalign.golden +++ b/test/snapshots/tagalign.golden @@ -1,60 +1,58 @@ == snap aligned grid=100x31 cursor=4,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty Collapse Del | 1 alpha | 2 beta | 3 gamma -| /tmp/pardes-snap/tagalign/cwd Tty+bash Save Mode Filter Collapse Del +| /tmp/pardes-snap/tagalign/cwd Tty+bash Save Mode Filter Collapse Del | ls | deep == snap fits grid=87x31 cursor=4,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty Co -| llapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty Col +| lapse Del | 1 alpha | 2 beta -| /tmp/pardes-snap/tagalign/cwd Tty+bash Save Mode Filter Collapse Del +| /tmp/pardes-snap/tagalign/cwd Tty+bash Save Mode Filter Collapse Del | ls | deep == snap overby1 grid=86x31 cursor=4,9 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty C -| ollapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty Co +| llapse Del | 1 alpha | 2 beta -| /tmp/pardes-snap/tagalign/cwd Tty+bash Save Mode Filter Collapse Del +| /tmp/pardes-snap/tagalign/cwd Tty+bash Save Mode Filter Collapse Del | ls | deep == snap clicked grid=100x31 cursor=11,2 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document.txt Save Tty Collapse Del | 1 alpha | 2 beta | 3 gamma -| /tmp/pardes-snap/tagalign/cwd Tty+bash Save Mode Filter Collapse Del +| /tmp/pardes-snap/tagalign/cwd Tty+bash Save Mode Filter Collapse Del | ls | deep -== snap revealed grid=70x31 cursor=30,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/documen -| t.txt Save Tty Collapse Del +== snap revealed grid=70x31 cursor=28,3 +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Deb +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/tagalign/cwd/deep/nested-project-directory/document +| .txt Save Tty Collapse Del | 1 alpha | 2 beta -| /tmp/pardes-snap/tagalign/cwd Tty+bash Save Mode Filter Collapse De -| l +| /tmp/pardes-snap/tagalign/cwd Tty+bash Save Mode Filter Collapse Del | ls | deep -== snap alone grid=70x31 cursor=4,6 -|2: /tmp/pardes-snap/tagalign/cwd Tty+bash Save Mode Filter Collapse De -|3: l -|4: ls -|5: deep +== snap alone grid=70x31 cursor=4,5 +|2: /tmp/pardes-snap/tagalign/cwd Tty+bash Save Mode Filter Collapse Del +|3: ls +|4: deep +|5: |6: |7: |8: -|9: diff --git a/test/snapshots/tagalign2col.golden b/test/snapshots/tagalign2col.golden index 129141b6..6c4b997a 100644 --- a/test/snapshots/tagalign2col.golden +++ b/test/snapshots/tagalign2col.golden @@ -1,26 +1,25 @@ -== snap onecol grid=160x31 cursor=7,4 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/tagalign2col/cwd/deep/proj/document.txt Save Tty Collapse De /tmp/pardes-snap/tagalign2col/cwd Tty+bash Save Mode Filter Collapse Del -| l ls Left -| 1 alpha deep -| 2 beta +== snap onecol grid=160x31 cursor=7,3 +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/tagalign2col/cwd/deep/proj/document.txt Save Tty Collapse Del /tmp/pardes-snap/tagalign2col/cwd Tty+bash Save Mode Filter Collapse Del +| 1 alpha ls Left +| 2 beta deep | 3 gamma -== snap aligned grid=160x31 cursor=4,10 -|3: l ls -|7: /tmp/pardes-snap/tagalign2col/cwd Tty+bash Save Mode Filter Collapse Del -|8: ls -|9: deep -== snap widened grid=160x31 cursor=4,10 -|1: New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol -|2: /tmp/pardes-snap/tagalign2col/cwd/deep/proj/document.txt Save Tty Collapse Del ╎ /tmp/pardes-snap/tagalign2col/cwd Tty+bash Save Mode Filt -|3: 1 alpha ╎ er Collapse Del +== snap aligned grid=160x31 cursor=4,9 +|3: 1 alpha ls +|6: /tmp/pardes-snap/tagalign2col/cwd Tty+bash Save Mode Filter Collapse Del +|7: ls +|8: deep +== snap widened grid=160x31 cursor=4,9 +|1: New Tty Find Grep Joincol Delcol ╎ New Tty Find Grep Joincol Delcol +|2: /tmp/pardes-snap/tagalign2col/cwd/deep/proj/document.txt Save Tty Collapse Del ╎ /tmp/pardes-snap/tagalign2col/cwd Tty+bash Save Mode Filte +|3: 1 alpha ╎ r Collapse Del |4: 2 beta ╎ ls |5: 3 gamma ╎ deep -|6: ╎ -|7: /tmp/pardes-snap/tagalign2col/cwd Tty+bash Save Mode Filter Collapse Del ╎ -|8: ls ╎ -|9: deep ╎ +|6: /tmp/pardes-snap/tagalign2col/cwd Tty+bash Save Mode Filter Collapse Del ╎ +|7: ls ╎ +|8: deep ╎ +|9: ╎ |10: ╎ |11: ╎ |12: ╎ diff --git a/test/snapshots/tagbottom.golden b/test/snapshots/tagbottom.golden index 8469c741..ef1bab3a 100644 --- a/test/snapshots/tagbottom.golden +++ b/test/snapshots/tagbottom.golden @@ -1,7 +1,7 @@ == snap boot grid=100x31 cursor=7,3 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del | 1 aaa | 2 bbb | 3 ccc @@ -56,9 +56,9 @@ |26: 25 yyy |27: 26 zzz |28: -|30: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del +|30: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del == snap off grid=100x31 cursor=7,3 -|2: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del +|2: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del |3: 1 aaa |4: 2 bbb |5: 3 ccc @@ -86,7 +86,7 @@ |27: 25 yyy |28: 26 zzz |30: -== snap tag-typed grid=100x31 cursor=74,30 +== snap tag-typed grid=100x31 cursor=73,30 |2: 1 aaa |3: 2 bbb |4: 3 ccc @@ -114,9 +114,9 @@ |26: 25 yyy |27: 26 zzz |28: -|30: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del bottom.txt +|30: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del bottom.txt == snap look-bottom-tag grid=100x31 cursor=7,16 -|15: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del bottom.txt +|15: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del bottom.txt |16: 1 ZZONE |17: 2 ZZTWO |18: @@ -129,11 +129,11 @@ |25: |26: |27: -|30: /tmp/pardes-snap/tagbottom/cwd/bottom.txt Save Tty Collapse Del +|30: /tmp/pardes-snap/tagbottom/cwd/bottom.txt Save Tty Collapse Del == snap body-cursor grid=100x31 cursor=9,6 == snap seam-noop grid=100x31 cursor=12,16 == snap seam-dragged grid=100x31 cursor=12,12 -|11: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del bottom.txt +|11: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del bottom.txt |12: 1 ZZONE |13: 2 ZZTWO |14: @@ -164,7 +164,7 @@ |8: 7 mmm |9: 8 nnn |10: 9 ooo -|11: * /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del bottom.txt +|11: */tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del bottom.txt |12: 1 ZZONE == file cut-buffer aaa @@ -200,9 +200,9 @@ zzz |19: 18 xxx |20: 19 yyy |21: 20 zzz -|30: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del bottom.txt +|30: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del bottom.txt == snap off-again grid=100x31 cursor=7,6 -|2: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del bottom.txt +|2: /tmp/pardes-snap/tagbottom/cwd/top.txt Save Tty Collapse Del bottom.txt |3: 1 aaa |4: 2 bbb |5: 3 ccc diff --git a/test/snapshots/tagbottomimage.golden b/test/snapshots/tagbottomimage.golden index ce6948bf..9f3ff2fd 100644 --- a/test/snapshots/tagbottomimage.golden +++ b/test/snapshots/tagbottomimage.golden @@ -1,11 +1,11 @@ == snap img-top grid=150x31 cursor=11,8 -|Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit -| New Tty Find Grep Joincol Delcol -| /tmp/pardes-snap/tagbottomimage/cwd Tty+bash Save Mode Filter Collapse Del +| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config Debug Exit +| New Tty Find Grep Joincol Delcol +| /tmp/pardes-snap/tagbottomimage/cwd Tty+bash Save Mode Filter Collapse Del | ls | pic.ppm | -| img petscii:on palette:commodore ascii:on /tmp/pardes-snap/tagbottomimage/cwd/pic.ppm Tty Collapse Del +| img petscii:on palette:commodore ascii:on /tmp/pardes-snap/tagbottomimage/cwd/pic.ppm Tty Collapse Del | 4*🬹~F~N🬰|G🬏▚Y~KF🬴s>T&zZ/🬻iTY=`S~╳bkZR37v🬦🬵d4QHZ8X▛▟ | ^🬪🬛$}DrydNU&wsz=`*r🬒🬓🬳🬟*Y🬴G6🬧f🬮/>t🬧u🬲1Rg1t🬝🬻█ @@ -34,7 +34,7 @@ |2: ls |3: pic.ppm |4: -|5: /tmp/pardes-snap/tagbottomimage/cwd Tty+bash Save Mode Filter Collapse Del +|5: /tmp/pardes-snap/tagbottomimage/cwd Tty+bash Save Mode Filter Collapse Del |6: Tagbottom |7: {DbgY🬲s▜M^#▐FUJ[zNq=🬝g/y╱?V@🬱🬙▌UK╱🬍("🬕KJ8hSo🬝🬻 |8: tX🬆s>🬌`🬵 Date: Wed, 21 Oct 2026 17:25:52 -0300 Subject: zig fmt for Zig 0.17 --- build.zig | 15 +- src/9p_io.zig | 2 +- src/Dir.zig | 4 +- src/File.zig | 12 +- src/Messages.zig | 2 +- src/Presentation.zig | 6 +- src/animation.zig | 11 +- src/builtins.zig | 22 +- src/detached/client.zig | 2 +- src/detached/server.zig | 4 +- src/detached/wire.zig | 82 +-- src/diff.zig | 4 +- src/draw.zig | 4 +- src/dump.zig | 4 +- src/edit_cmd.zig | 2 +- src/esp32p4.zig | 34 +- src/esp32p4/app.zig | 6 +- src/esp32p4_9p.zig | 2 +- src/fonts.zig | 2 +- src/gui/Post.zig | 19 +- src/gui/gui.zig | 32 +- src/host_io.zig | 20 +- src/linux/v9fs.zig | 6 +- src/look.zig | 2 +- src/macos.zig | 98 ++-- src/main.zig | 2 +- src/mini.zig | 10 +- src/mouse.zig | 18 +- src/ninep/addr.zig | 6 +- src/ninep/cols.zig | 54 +- src/ninep/ctl.zig | 168 +++--- src/ninep/events.zig | 30 +- src/ninep/pane.zig | 8 +- src/ninep/pty.zig | 5 +- src/ninep/screen.zig | 4 +- src/ninep/testing.zig | 4 +- src/ninep/tree.zig | 120 ++-- src/pager.zig | 4 +- src/pardes.zig | 10 +- src/pdf_view.zig | 2 +- src/syntax.zig | 82 +-- src/terminal.zig | 2 +- src/web.zig | 32 +- test/deck/buttons.zon | 158 ++--- test/deck/lpad-swipe.zon | 322 +++++------ test/deck/replay.zig | 36 +- test/deck/rpad-drag.zon | 442 +++++++------- test/deck/triggers.zon | 1148 ++++++++++++++++++------------------- test/fs_bench.zig | 6 +- test/lspfixture/broken.zig | 4 +- test/output.zig | 10 +- test/panes.zig | 2 +- test/pdf.zig | 6 +- test/pdf_scroll_bench.zig | 2 +- test/perf-baseline-gui-debug.json | 2 +- test/perf-baseline-tty-debug.json | 2 +- test/perf-baseline-tty-fast.json | 2 +- test/perf.zig | 6 +- test/unit_profile.zig | 4 +- 59 files changed, 1556 insertions(+), 1554 deletions(-) (limited to 'src/File.zig') diff --git a/build.zig b/build.zig index ddd41a03..ca7b26af 100644 --- a/build.zig +++ b/build.zig @@ -39,10 +39,13 @@ pub const macos_min_version: std.SemanticVersion = .{ .major = 13, .minor = 0, . pub const TreeSitterGrammars = enum { disabled, zig, minimal, full }; const gui_shaders = [_][]const u8{ - "ui.vert", "ui.frag", + "ui.vert", + "ui.frag", "decor.frag", - "overlay.vert", "overlay.frag", - "image.vert", "image.frag", + "overlay.vert", + "overlay.frag", + "image.vert", + "image.frag", "post.vert", // The bundled post passes: shaders/post/.glsl behind the // Shadertoy prefix (shaderSource). @@ -843,7 +846,7 @@ pub fn build(b: *std.Build) void { const render_anchor = \\ if ((!self.refresh and \\ last.eql(cell) and - ; + ; if (std.mem.count(u8, render_src, render_anchor) != 1) std.debug.panic("vaxis's Vaxis.zig changed at `{s}`: redo its patch in build.zig", .{render_anchor}); render_src = std.mem.replaceOwned(u8, b.allocator, render_src, render_anchor, \\ if ((!self.refresh and @@ -924,7 +927,6 @@ pub fn build(b: *std.Build) void { .uucode = uucode_mod, }); - const iso_off = b.addOptions(); iso_off.addOption(bool, "isolated", false); const iso_on = b.addOptions(); @@ -1401,7 +1403,6 @@ pub fn build(b: *std.Build) void { const lspbench_check_step = b.step("lspbench-check", "require every configured language probe to complete correctly"); lspbench_check_step.dependOn(&run_lspbench_check.step); - const locations_bench_step = b.step("locations-bench", "measure cold/warm result formatting (-Doptimize=ReleaseFast; CSV on stderr)"); if (optimize != .fast) { locations_bench_step.dependOn(&b.addFail("locations-bench requires -Doptimize=ReleaseFast").step); @@ -2016,6 +2017,6 @@ fn wireCore(m: *std.Build.Module, d: struct { /// helper because `cpu_features_add` wants a set and there is no literal syntax for one. fn riscvFeatures(comptime features: []const std.Target.riscv.Feature) std.Target.Cpu.Feature.Set { var set = std.Target.Cpu.Feature.Set.empty; - for (features) |f| set.addFeature(@intFromEnum(f)); + for (features) |f| set.addFeature(@backingInt(f)); return set; } diff --git a/src/9p_io.zig b/src/9p_io.zig index 27d79b93..446c24de 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -1015,7 +1015,7 @@ pub fn sweepDeadSockets(io: std.Io, dir: [:0]const u8) void { i += 1 + name.len; const pid = deadSocketPid(name).?; if (pid == libc.getpid()) continue; - if (std.posix.errno(std.c.kill(pid, @enumFromInt(0))) != .SRCH) continue; + if (std.posix.errno(std.c.kill(pid, @fromBackingInt(@intCast(0)))) != .SRCH) continue; var path_buf: [sun_path_len:0]u8 = undefined; const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}", .{ dir, name }, 0) catch continue; const facts = statNoFollow(path) orelse continue; diff --git a/src/Dir.zig b/src/Dir.zig index 36895bda..b994bc06 100644 --- a/src/Dir.zig +++ b/src/Dir.zig @@ -463,10 +463,10 @@ test "over 9P a directory pane is a text pane whose name ends in /, its body the defer s.p.deinit(); const p = s.p; var line_buf: [4200]u8 = undefined; - _ = th.wr(p, @intFromEnum(tree.TopFile.look), try std.fmt.bufPrint(&line_buf, "{s}\n", .{s.dir})); + _ = th.wr(p, @backingInt(tree.TopFile.look), try std.fmt.bufPrint(&line_buf, "{s}\n", .{s.dir})); p.sync(); const pane = p.panes[p.active].?; - const index = th.rd(p, @intFromEnum(tree.TopFile.index), 0, 8192).bytes; + const index = th.rd(p, @backingInt(tree.TopFile.index), 0, 8192).bytes; try testing.expect(std.mem.indexOf(u8, index, try std.fmt.bufPrint(&line_buf, "{d} text 0 {s}/ ", .{ pane.serial, s.dir })) != null); try testing.expectEqualStrings(".dot sub/ top.txt\n", th.rd(p, tree.Node.of(pane.serial, .body), 0, 4096).bytes); var fields = std.mem.tokenizeScalar(u8, th.rd(p, tree.Node.of(pane.serial, .ctl), 0, 4096).bytes, ' '); diff --git a/src/File.zig b/src/File.zig index c42e39ec..59b04e3f 100644 --- a/src/File.zig +++ b/src/File.zig @@ -251,7 +251,7 @@ pub fn dumpPane( fn dumpLocationRows(arena: std.mem.Allocator, rows: []const locations.Row) ![]const dump.LocationRow { const saved = try arena.alloc(dump.LocationRow, rows.len); for (rows, saved) |row, *out| out.* = .{ - .kind = @enumFromInt(@intFromEnum(row.kind)), + .kind = @fromBackingInt(@intCast(@backingInt(row.kind))), .declaration = row.declaration, .mark_occurrence = row.mark_occurrence, .source_column = row.source_column, @@ -336,10 +336,10 @@ fn restoreOutputLocationRows(gpa: std.mem.Allocator, content: []const u8, saved: const colors = try dump.decodeBytes(gpa, row.colors_b64); errdefer gpa.free(colors); if (colors.len != 0 and colors.len != code_len) return error.InvalidLocationRows; - for (colors) |color| if (color > @intFromEnum(syntax.Syn.comment)) return error.InvalidLocationRows; + for (colors) |color| if (color > @backingInt(syntax.Syn.comment)) return error.InvalidLocationRows; const path = try gpa.dupe(u8, row.path); out.* = .{ - .kind = @enumFromInt(@intFromEnum(row.kind)), + .kind = @fromBackingInt(@intCast(@backingInt(row.kind))), .declaration = row.declaration, .mark_occurrence = row.mark_occurrence, .source_column = row.source_column, @@ -1028,7 +1028,7 @@ pub fn restore(p: *Pardes, id: usize, src: dump.Pane) !*Pane { const colors = try dump.decodeBytes(p.gpa, saved.mini_colors_b64); errdefer p.gpa.free(colors); if (colors.len != content.len or colors.len > Mini.max_output_bytes) return error.InvalidMini; - for (colors) |color| if (color > @intFromEnum(syntax.Syn.comment)) return error.InvalidMini; + for (colors) |color| if (color > @backingInt(syntax.Syn.comment)) return error.InvalidMini; mini = .{ .source = source, .colors = colors }; } else if (saved.mini_colors_b64.len > 0) return error.InvalidMini; @@ -1984,7 +1984,7 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. if (if (tint != null and hs + c == 0) SynStyle{ .fg = tint.?.fg, .bold = true } else - synStyle(p, @enumFromInt(highlights[hidx] & syntax.syn_bits))) |ss| + synStyle(p, @fromBackingInt(@intCast(highlights[hidx] & syntax.syn_bits)))) |ss| { var fill: usize = 0; while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) { @@ -2189,7 +2189,7 @@ pub fn recolorDiffOutput(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, t // green is the tint's to say now: its code takes the page's ink. const paint: ?SynStyle = if (tint != null and prefix) .{ .fg = tint.?.fg, .bold = true } - else if (synStyle(p, @enumFromInt(style & syntax.syn_bits))) |ss| + else if (synStyle(p, @fromBackingInt(@intCast(style & syntax.syn_bits)))) |ss| ss else if (tint != null) .{ .fg = ink, .bold = false } diff --git a/src/Messages.zig b/src/Messages.zig index b67a8402..6d064c93 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -721,7 +721,7 @@ test "with no frontend attached a message goes once it has lingered, on the cloc // line above it with it. p.unattended = true; // A read served meanwhile changes nothing; the session's loop expires. - _ = p.serveFs(.{ .tag = 1, .op = .read, .node = @intFromEnum(ctlfs.TopFile.index), .size = 64 }); + _ = p.serveFs(.{ .tag = 1, .op = .read, .node = @backingInt(ctlfs.TopFile.index), .size = 64 }); try std.testing.expect(pane.msg_len > 0); expireUnattended(p); try std.testing.expectEqual(@as(u16, 0), pane.msg_len); diff --git a/src/Presentation.zig b/src/Presentation.zig index 5cec73e0..2a75b66d 100644 --- a/src/Presentation.zig +++ b/src/Presentation.zig @@ -226,7 +226,7 @@ fn stamp(p: *const Pardes, track: Track) Track { switch (track.effect) { .slide, .zoom, .vertical => { const motion = animation.Motion.of(p.settings.motion); - stamped.motion = @intFromEnum(p.settings.motion) + 1; + stamped.motion = @backingInt(p.settings.motion) + 1; stamped.frame_count = @intFromFloat(@max(2, @round(@as(f32, @floatFromInt(track.effect.frames())) * motion.span))); }, else => {}, @@ -741,7 +741,7 @@ test "a pane past its mark never takes a neighbour's click" { // Bouncy, at its peak: pane 0 slides right to 0..40 and swings past it, // over the neighbour at 40..80. var presentation: Presentation = .{}; - var track: Track = .{ .serial = 7, .effect = .slide, .motion = @intFromEnum(animation.Motion.Flavour.bouncy) + 1, .frame_count = 20, .from = .{ .x = -40, .y = 0, .w = 40, .h = 20 }, .to = .{ .x = 0, .y = 0, .w = 40, .h = 20 } }; + var track: Track = .{ .serial = 7, .effect = .slide, .motion = @backingInt(animation.Motion.Flavour.bouncy) + 1, .frame_count = 20, .from = .{ .x = -40, .y = 0, .w = 40, .h = 20 }, .to = .{ .x = 0, .y = 0, .w = 40, .h = 20 } }; var peak: u16 = 0; var furthest: f32 = -1e9; while (track.frame < track.frames()) : (track.frame += 1) { @@ -807,7 +807,7 @@ test "presentation snapshots own compact body and tag rows across later edits" { } test "a move retargeted mid-way carries its speed into the new one" { - const smooth = @intFromEnum(animation.Motion.Flavour.smooth) + 1; + const smooth = @backingInt(animation.Motion.Flavour.smooth) + 1; const first: Track = .{ .serial = 1, .phase = .moving, .effect = .slide, .motion = smooth, .frame = 4, .frame_count = 14, .from = .{ .x = 0, .y = 1, .w = 40, .h = 20 }, .to = .{ .x = 40, .y = 1, .w = 40, .h = 20 } }; const was = first.velocity(); try std.testing.expect(was.x > 0.5); diff --git a/src/animation.zig b/src/animation.zig index 19f7ce0b..547b9201 100644 --- a/src/animation.zig +++ b/src/animation.zig @@ -897,7 +897,7 @@ test "each flavour is its own motion: off lands at once, bouncy overshoots, play last = now; } try std.testing.expect(t < 1600 * ms); - settle[@intFromEnum(flavour)] = t; + settle[@backingInt(flavour)] = t; switch (flavour) { .crisp, .smooth => try std.testing.expect(peak <= 1.0005 and low >= 0), // Clearly past the mark, not a hint of it. @@ -909,8 +909,8 @@ test "each flavour is its own motion: off lands at once, bouncy overshoots, play // Smooth takes twice crisp's time and more: a character, not a tuning. // Yet as the default a pane's arrival (a slide's 12 frames, scaled) is // inside §8.1's 220 ms, and a lift is still before 300 ms. - try std.testing.expect(settle[@intFromEnum(Motion.Flavour.smooth)] > 2 * settle[@intFromEnum(Motion.Flavour.crisp)]); - try std.testing.expect(settle[@intFromEnum(Motion.Flavour.smooth)] <= 300 * ms); + try std.testing.expect(settle[@backingInt(Motion.Flavour.smooth)] > 2 * settle[@backingInt(Motion.Flavour.crisp)]); + try std.testing.expect(settle[@backingInt(Motion.Flavour.smooth)] <= 300 * ms); try std.testing.expect(@round(@as(f32, 12) * Motion.of(.smooth).span) * frame_ms <= 220); // A fixed-length move lands exactly on its mark, whatever the flavour. for (std.enums.values(Motion.Flavour)) |flavour| try std.testing.expectEqual(@as(f32, 1), Motion.of(flavour).ease(1)); @@ -920,7 +920,7 @@ test "a flavour's stretched pane lands exactly on its box, and a click finds the const from: Box = .{ .x = 0, .y = 2, .w = 30, .h = 10 }; const to: Box = .{ .x = 37.3, .y = 2, .w = 30, .h = 10 }; for (std.enums.values(Motion.Flavour)) |flavour| { - var track: Track = .{ .effect = .slide, .motion = @intFromEnum(flavour) + 1, .frame_count = 20, .from = from, .to = to }; + var track: Track = .{ .effect = .slide, .motion = @backingInt(flavour) + 1, .frame_count = 20, .from = from, .to = to }; track.frame = track.frames() - 1; const landed = track.presented(); // Bit for bit: no stretch or float residue once it lands. @@ -929,7 +929,7 @@ test "a flavour's stretched pane lands exactly on its box, and a click finds the // Playful at its most stretched: the pane is drawn wider than its box, // and the drawn place of a cell maps back to that cell (the pointer // inverts the same box: target + (x - shown.x) / shown.w * target.w). - var track: Track = .{ .effect = .slide, .motion = @intFromEnum(Motion.Flavour.playful) + 1, .frame_count = 20, .from = from, .to = to }; + var track: Track = .{ .effect = .slide, .motion = @backingInt(Motion.Flavour.playful) + 1, .frame_count = 20, .from = from, .to = to }; var most: u16 = 0; var widest: f32 = 0; while (track.frame < track.frames()) : (track.frame += 1) { @@ -1309,4 +1309,3 @@ test "retarget starts at the currently displayed value" { for (0..transition_steps) |_| tween.advance(); try std.testing.expectEqual(third, tween.displayed); } - diff --git a/src/builtins.zig b/src/builtins.zig index d9cef8c9..83966228 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -199,7 +199,7 @@ pub const registry = struct { pub fn takesArg(b: Builtin()) bool { inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return @hasDecl(T, "takes_arg") and T.takes_arg; + if (@backingInt(b) == i) return @hasDecl(T, "takes_arg") and T.takes_arg; // Every setting takes its value, and a switch flips when bare. return true; } @@ -210,7 +210,7 @@ pub const registry = struct { /// may be in (`Dump+2024.zon` is a name, not Dump's argument). pub fn plusArg(b: Builtin()) bool { inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return @hasDecl(T, "plus_arg") and T.plus_arg; + if (@backingInt(b) == i) return @hasDecl(T, "plus_arg") and T.plus_arg; return false; } @@ -223,15 +223,15 @@ pub const registry = struct { /// pane it is refused (exec.runBuiltinFrom), as Repl and Edit are. pub fn needs(b: Builtin()) ?PaneKind { inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return if (@hasDecl(T, "needs")) T.needs else null; + if (@backingInt(b) == i) return if (@hasDecl(T, "needs")) T.needs else null; return null; } pub fn requiresArg(b: Builtin()) bool { inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return @hasDecl(T, "requires_arg") and T.requires_arg; + if (@backingInt(b) == i) return @hasDecl(T, "requires_arg") and T.requires_arg; inline for (comptime settingList(), manualBuiltinCount()..) |setting, i| - if (@intFromEnum(b) == i) return switch (setting.action) { + if (@backingInt(b) == i) return switch (setting.action) { // a switch flips bare, a choice steps, and DumpDir and Shell bare // are the default .toggle, .transition, .scene, .dump_dir, .choice, .lift, .shader_animation, .motion, .shell => false, @@ -244,15 +244,15 @@ pub const registry = struct { pub fn scope(b: Builtin()) Scope { inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return if (@hasDecl(T, "scope")) T.scope else .pane; + if (@backingInt(b) == i) return if (@hasDecl(T, "scope")) T.scope else .pane; return .session; // a setting } pub fn outputTraits(b: Builtin()) ?OutputTraits { inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return if (@hasDecl(T, "output")) T.output else null; + if (@backingInt(b) == i) return if (@hasDecl(T, "output")) T.output else null; inline for (comptime settingList(), manualBuiltinCount()..) |_, i| - if (@intFromEnum(b) == i) return null; + if (@backingInt(b) == i) return null; unreachable; } @@ -260,15 +260,15 @@ pub const registry = struct { /// The ones that own that row themselves declare `quiet` and do not. pub fn announces(b: Builtin()) bool { inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return !(@hasDecl(T, "quiet") and T.quiet); + if (@backingInt(b) == i) return !(@hasDecl(T, "quiet") and T.quiet); return true; // a setting builtin changes something invisible; say so } pub fn dispatch(b: Builtin(), c: Ctx) void { inline for (manualBuiltinList(), 0..) |T, i| - if (@intFromEnum(b) == i) return T.run(c); + if (@backingInt(b) == i) return T.run(c); inline for (comptime settingList(), manualBuiltinCount()..) |setting, i| - if (@intFromEnum(b) == i) return exec.applySettingBuiltin(c.p, setting, c.arg); + if (@backingInt(b) == i) return exec.applySettingBuiltin(c.p, setting, c.arg); unreachable; } }; diff --git a/src/detached/client.zig b/src/detached/client.zig index cf1842d9..60950208 100644 --- a/src/detached/client.zig +++ b/src/detached/client.zig @@ -1209,7 +1209,7 @@ test "detached session: a frontend is never asked to fork, write, or watch" { } const named = for (allowed) |ok| { const want = std.meta.stringToEnum(wire.ServerTag, ok).?; - if (@intFromEnum(want) == tag) break true; + if (@backingInt(want) == tag) break true; } else false; if (!named) { std.debug.print("tag 0x{x:0>2} is decodable by a frontend and is not one of the nine\n", .{tag}); diff --git a/src/detached/server.zig b/src/detached/server.zig index 79d1189a..41bc054f 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -1049,7 +1049,7 @@ pub const Session = struct { } fn apply(s: *Session, c: *Client, slot: u8, tag: u8, payload: []const u8) wire.Error!void { - if (tag == @intFromEnum(wire.ClientTag.hello)) { + if (tag == @backingInt(wire.ClientTag.hello)) { if (c.attached) return error.BadValue; const claimed = try wire.helloVersion(payload); if (claimed != wire.version) { @@ -1124,7 +1124,7 @@ pub const Session = struct { if (entry.scene == null) break true; } else false; const compiled = s.shaders.sync(s.gpa, s.io, s.core, if (files) s.inotify() else s.inotify_fd, &s.watches, .{ .ctx = &s.mailbox, .call = wakeForExit }); - const key = @as(u64, s.shaders.revision) << 8 | @intFromEnum(s.core.settings.shader_animation); + const key = @as(u64, s.shaders.revision) << 8 | @backingInt(s.core.settings.shader_animation); var chain: wire.Post = .{ .animation = s.core.settings.shader_animation, .len = s.core.settings.post.len }; _ = s.shaders.view(&s.core.settings.post, &chain.passes); for (&s.clients) |*c| { diff --git a/src/detached/wire.zig b/src/detached/wire.zig index f1b7a1b3..d57a28be 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -569,13 +569,13 @@ pub fn framed(buf: []const u8) Error!?Framed { fn putColor(w: *Writer, c: pardes.Color) Error!void { switch (c) { - .default => try w.putByte(@intFromEnum(ColorTag.default)), + .default => try w.putByte(@backingInt(ColorTag.default)), .index => |i| { - try w.putByte(@intFromEnum(ColorTag.index)); + try w.putByte(@backingInt(ColorTag.index)); try w.putByte(i); }, .rgb => |v| { - try w.putByte(@intFromEnum(ColorTag.rgb)); + try w.putByte(@backingInt(ColorTag.rgb)); try w.putBytes(&v); }, } @@ -606,7 +606,7 @@ const Ul = @FieldType(pardes.CellStyle, "ul"); /// the `inline else`, exactly as `clientTag` keeps the machine-local reports. fn putUl(w: *Writer, u: Ul) Error!void { try w.putByte(switch (u) { - inline else => |t| @intFromEnum(@field(UlTag, @tagName(t))), + inline else => |t| @backingInt(@field(UlTag, @tagName(t))), }); } @@ -618,7 +618,7 @@ fn getUl(r: *Reader) Error!Ul { fn putFont(w: *Writer, f: pardes.FontRole) Error!void { try w.putByte(switch (f) { - inline else => |t| @intFromEnum(@field(FontTag, @tagName(t))), + inline else => |t| @backingInt(@field(FontTag, @tagName(t))), }); } @@ -795,12 +795,12 @@ pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, point std.debug.assert(cells.len == @as(usize, cols) * @as(usize, rows)); const full = prev.len != cells.len; var w: Writer = .init(out); - const at = try beginMessage(&w, @intFromEnum(ServerTag.frame)); + const at = try beginMessage(&w, @backingInt(ServerTag.frame)); const header: FrameHeader = if (pointer_shape == .link) (if (full) .full_link else .diff_link) else (if (full) .full else .diff); - try w.putByte(@intFromEnum(header)); + try w.putByte(@backingInt(header)); try w.putU16(cols); try w.putU16(rows); try putCursor(&w, cursor, cols, rows); @@ -837,7 +837,7 @@ pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, point for (tags) |layer| { if (layer.rows == 0) continue; if (layer.cells.len != @as(usize, layer.cols) * layer.rows) return error.BadValue; - try w.putByte(@intFromEnum(layer.kind)); + try w.putByte(@backingInt(layer.kind)); try w.putU16(layer.id); try w.putU32(layer.serial); try w.putU16(layer.viewport.x); @@ -852,7 +852,7 @@ pub fn encodeFrameLayers(out: []u8, cols: u16, rows: u16, cursor: ?Cursor, point } try w.putU16(@intCast(regions.len)); for (regions) |region| { - try w.putByte(@intFromEnum(region.kind)); + try w.putByte(@backingInt(region.kind)); try w.putByte(region.owner); try w.putU32(region.serial); try w.putU16(region.rect.x); @@ -1003,7 +1003,7 @@ fn getBodyHit(r: *Reader) Error!?pardes.Mouse.BodyHit { fn putTagHit(w: *Writer, hit: ?pardes.TagHit) Error!void { try w.putBool(hit != null); if (hit) |h| { - try w.putByte(@intFromEnum(h.kind)); + try w.putByte(@backingInt(h.kind)); try w.putU16(h.id); try w.putU32(h.serial); try w.putU16(h.col); @@ -1030,7 +1030,7 @@ fn getTagHit(r: *Reader) Error!?pardes.TagHit { pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { var w: Writer = .init(out); - const at = try beginMessage(&w, @intFromEnum(clientTag(msg))); + const at = try beginMessage(&w, @backingInt(clientTag(msg))); switch (msg) { .hello => |h| { try w.putU16(h.version); @@ -1048,10 +1048,10 @@ pub fn encodeClient(out: []u8, msg: ClientMsg) Error![]const u8 { }, .mouse => |m| { try w.putByte(switch (m.button) { - inline else => |t| @intFromEnum(@field(ButtonTag, @tagName(t))), + inline else => |t| @backingInt(@field(ButtonTag, @tagName(t))), }); try w.putByte(switch (m.kind) { - inline else => |t| @intFromEnum(@field(KindTag, @tagName(t))), + inline else => |t| @backingInt(@field(KindTag, @tagName(t))), }); try w.putU16(m.col); try w.putU16(m.row); @@ -1164,7 +1164,7 @@ fn serverTag(msg: ServerMsg) ServerTag { /// payload is a walk of two grids rather than a value (see `encodeFrame`). pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { var w: Writer = .init(out); - const at = try beginMessage(&w, @intFromEnum(serverTag(msg))); + const at = try beginMessage(&w, @backingInt(serverTag(msg))); switch (msg) { .welcome => |v| { try w.putU16(v.version); @@ -1172,7 +1172,7 @@ pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { try w.putU16(v.cols); try w.putU16(v.rows); }, - .refuse => |why| try w.putByte(@intFromEnum(why)), + .refuse => |why| try w.putByte(@backingInt(why)), // A frame's runs are not a value this union can hold; the server calls // encodeFrame directly and this arm exists so the switch stays // exhaustive over ServerMsg. @@ -1182,11 +1182,11 @@ pub fn encodeServer(out: []u8, msg: ServerMsg) Error![]const u8 { .read_clipboard => {}, .open_link => |u| try w.putSlice16(u), .post => |p| { - try w.putByte(@intFromEnum(p.animation)); + try w.putByte(@backingInt(p.animation)); try w.putByte(p.len); for (p.list()) |pass| { // 0 a file, else a bundled scene and one. - try w.putByte(if (pass.scene) |scene| @as(u8, @intFromEnum(scene)) + 1 else 0); + try w.putByte(if (pass.scene) |scene| @as(u8, @backingInt(scene)) + 1 else 0); try w.putByte(pass.level); try w.putByte(@intFromBool(pass.animated)); try w.putU32(pass.revision); @@ -1341,9 +1341,9 @@ test "detached wire: every Event variant round-trips" { // The tag space is the protocol's own, so assert the numbers themselves: // a renumbering here breaks every deployed frontend and must be a diff // somebody reads, not a silent change. - try testing.expectEqual(@as(u8, 0x01), @intFromEnum(ClientTag.hello)); - try testing.expectEqual(@as(u8, 0x10), @intFromEnum(ClientTag.key)); - try testing.expectEqual(@as(u8, 0x1d), @intFromEnum(ClientTag.pointer_leave)); + try testing.expectEqual(@as(u8, 0x01), @backingInt(ClientTag.hello)); + try testing.expectEqual(@as(u8, 0x10), @backingInt(ClientTag.key)); + try testing.expectEqual(@as(u8, 0x1d), @backingInt(ClientTag.pointer_leave)); { const got = try roundClient(&buf, .{ .hello = .{ .cols = 80, .rows = 24 } }); @@ -1506,7 +1506,7 @@ test "detached wire: a session is never told to do a frontend's remembering" { } const named = for (allowed) |ok| { const want = std.meta.stringToEnum(ClientTag, ok).?; - if (@intFromEnum(want) == tag) break true; + if (@backingInt(want) == tag) break true; } else false; if (!named) { std.debug.print("tag 0x{x:0>2} is decodable by a session and is not something a human did\n", .{tag}); @@ -1752,8 +1752,8 @@ test "detached wire: a truncated frame is refused at every length" { for (0..header_len + 1) |cut| try testing.expectEqual(@as(?Framed, null), try framed(copy[0..cut])); // A payload with bytes LEFT OVER is refused too: it is not this message. - try testing.expectError(error.Trailing, decodeClient(@intFromEnum(ClientTag.pointer_leave), "x")); - try testing.expectError(error.Trailing, decodeServer(@intFromEnum(ServerTag.quit), "x")); + try testing.expectError(error.Trailing, decodeClient(@backingInt(ClientTag.pointer_leave), "x")); + try testing.expectError(error.Trailing, decodeServer(@backingInt(ServerTag.quit), "x")); } test "detached wire: an unknown tag is refused, never guessed" { @@ -1765,9 +1765,9 @@ test "detached wire: an unknown tag is refused, never guessed" { } // A tag NESTED in a payload gets the same treatment: a color, an // underline style, a mouse button, a refusal reason. - try testing.expectError(error.BadTag, decodeServer(@intFromEnum(ServerTag.refuse), &.{0x7f})); + try testing.expectError(error.BadTag, decodeServer(@backingInt(ServerTag.refuse), &.{0x7f})); try testing.expectError(error.BadTag, decodeClient( - @intFromEnum(ClientTag.mouse), + @backingInt(ClientTag.mouse), &.{ 0xff, 0x00, 0, 0, 0, 0, 0 }, )); } @@ -1775,7 +1775,7 @@ test "detached wire: an unknown tag is refused, never guessed" { test "detached wire: an over-long length prefix is refused before it is believed" { // The prefix a hostile or corrupt peer sends to make the receiver allocate // or index by it. `framed` must refuse rather than wait for 4 GiB. - var head: [header_len]u8 = .{ @intFromEnum(ClientTag.paste), 0, 0, 0, 0 }; + var head: [header_len]u8 = .{ @backingInt(ClientTag.paste), 0, 0, 0, 0 }; std.mem.writeInt(u32, head[1..5], max_payload + 1, .little); try testing.expectError(error.Overlong, framed(&head)); std.mem.writeInt(u32, head[1..5], std.math.maxInt(u32), .little); @@ -1789,10 +1789,10 @@ test "detached wire: an over-long length prefix is refused before it is believed var paste: [8]u8 = undefined; std.mem.writeInt(u32, paste[0..4], 4096, .little); @memcpy(paste[4..8], "abcd"); - try testing.expectError(error.Truncated, decodeClient(@intFromEnum(ClientTag.paste), &paste)); + try testing.expectError(error.Truncated, decodeClient(@backingInt(ClientTag.paste), &paste)); // ...and past the cap, which is refused rather than read. std.mem.writeInt(u32, paste[0..4], max_payload + 1, .little); - try testing.expectError(error.Overlong, decodeClient(@intFromEnum(ClientTag.paste), &paste)); + try testing.expectError(error.Overlong, decodeClient(@backingInt(ClientTag.paste), &paste)); } test "detached wire: a frame that lies about its runs cannot walk out of the grid" { @@ -1837,13 +1837,13 @@ test "detached wire: a frame that lies about its runs cannot walk out of the gri // it is used to bound the walk. var head: [frame_head]u8 = undefined; var w: Writer = .init(&head); - try w.putByte(@intFromEnum(FrameKind.diff)); + try w.putByte(@backingInt(FrameKind.diff)); try w.putU16(cols); try w.putU16(rows); try putCursor(&w, null, cols, rows); try w.putU32(0); // no body layers try w.putU32(9); - try testing.expectError(error.Overlong, decodeServer(@intFromEnum(ServerTag.frame), w.written())); + try testing.expectError(error.Overlong, decodeServer(@backingInt(ServerTag.frame), w.written())); // ...and a grid of the wrong size is the receiver's own bug, not a frame // it should paint half of. @@ -1885,7 +1885,7 @@ test "detached wire: a cursor outside the grid is refused, not painted" { var head: [frame_head]u8 = undefined; for ([_][2]u16{ .{ cols, 0 }, .{ 0, rows }, .{ 0xffff, 0xffff } }) |xy| { var w: Writer = .init(&head); - try w.putByte(@intFromEnum(FrameKind.diff)); + try w.putByte(@backingInt(FrameKind.diff)); try w.putU16(cols); try w.putU16(rows); // Written by hand: `putCursor` now refuses this too, which is the @@ -1897,19 +1897,19 @@ test "detached wire: a cursor outside the grid is refused, not painted" { try w.putU32(0); try testing.expectError( error.BadValue, - decodeServer(@intFromEnum(ServerTag.frame), w.written()), + decodeServer(@backingInt(ServerTag.frame), w.written()), ); } // The last cell IS in the grid, and a frame carrying it decodes. { var w: Writer = .init(&head); - try w.putByte(@intFromEnum(FrameKind.diff)); + try w.putByte(@backingInt(FrameKind.diff)); try w.putU16(cols); try w.putU16(rows); try putCursor(&w, .{ .x = cols - 1, .y = rows - 1, .bar = true }, cols, rows); try w.putU32(0); // no body layers try w.putU32(0); - const got = (try decodeServer(@intFromEnum(ServerTag.frame), w.written())).frame; + const got = (try decodeServer(@backingInt(ServerTag.frame), w.written())).frame; try testing.expectEqual(@as(u16, cols - 1), got.cursor.?.x); try testing.expectEqual(@as(u16, rows - 1), got.cursor.?.y); } @@ -1933,25 +1933,25 @@ test "detached wire: values a field cannot mean are refused" { // A bool is 0 or 1. `2` used to be "true" in every hand-written codec that // ever silently accepted a corrupt stream. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.key), + @backingInt(ClientTag.key), &.{ 'a', 0, 0, 0, 0, 0, 2, 0, 0 }, )); // A codepoint past Unicode's last: @intCast into Key.cp's u21 would panic. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.key), + @backingInt(ClientTag.key), &.{ 0x00, 0x00, 0x11, 0x00, 0, 0, 0, 0, 0 }, )); // A pane the core cannot index. `pdf_scroll` reads its pane byte before the // f32 that follows, so a one-byte payload reaches the check this is about // rather than tripping `Truncated` first. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.pdf_scroll), + @backingInt(ClientTag.pdf_scroll), &.{pardes.MAX_PANES}, )); // A zero-column grid would collapse a shared session; an over-wide one is // past what this protocol carries. try testing.expectError(error.BadValue, decodeClient( - @intFromEnum(ClientTag.hello), + @backingInt(ClientTag.hello), &.{ 1, 0, 0, 0, 24, 0 }, )); { @@ -1959,15 +1959,15 @@ test "detached wire: values a field cannot mean are refused" { std.mem.writeInt(u16, hello[0..2], version, .little); std.mem.writeInt(u16, hello[2..4], max_cols + 1, .little); std.mem.writeInt(u16, hello[4..6], 24, .little); - try testing.expectError(error.BadValue, decodeClient(@intFromEnum(ClientTag.hello), &hello)); + try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.hello), &hello)); } // A NaN scroll distance. `pinch` multiplies into a zoom the pane keeps. { var pinch: [4]u8 = undefined; std.mem.writeInt(u32, &pinch, @bitCast(std.math.nan(f32)), .little); - try testing.expectError(error.BadValue, decodeClient(@intFromEnum(ClientTag.pinch), &pinch)); + try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.pinch), &pinch)); std.mem.writeInt(u32, &pinch, @bitCast(std.math.inf(f32)), .little); - try testing.expectError(error.BadValue, decodeClient(@intFromEnum(ClientTag.touch_scroll), &pinch)); + try testing.expectError(error.BadValue, decodeClient(@backingInt(ClientTag.touch_scroll), &pinch)); } // A cell with the reserved attribute bit set, and one with an impossible // grapheme length. Both are bytes this protocol has no meaning for. diff --git a/src/diff.zig b/src/diff.zig index 362695d5..842a6b41 100644 --- a/src/diff.zig +++ b/src/diff.zig @@ -163,8 +163,8 @@ pub const Walk = struct { }; const meta_words = [_][]const u8{ - "index ", "new file mode ", "deleted file mode ", "old mode ", "new mode ", - "similarity index ", "rename from ", "rename to ", "copy from ", "copy to ", + "index ", "new file mode ", "deleted file mode ", "old mode ", "new mode ", + "similarity index ", "rename from ", "rename to ", "copy from ", "copy to ", "Binary files ", "dissimilarity ", }; diff --git a/src/draw.zig b/src/draw.zig index e6420ed4..22a8dc2a 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -564,7 +564,7 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { .accent = chrome.box, .sel_fg = p.theme().sel_fg, .sel_bg = p.theme().sel_bg, - .lift_style = @intFromEnum(liftStyle(p)), + .lift_style = @backingInt(liftStyle(p)), .rule_px = p.theme().rule_px orelse 2, .grip_border = boxBorder(p), .grip_focus_ring = chrome.box, @@ -1167,7 +1167,7 @@ fn renderHeaderLayer(p: *Pardes, arena: std.mem.Allocator, layer: *pardes.Layer, const start = modal.lineStartOffset(text, index + top); const end = start + shown.len; if (mine and swept.lo < swept.hi and swept.hi > start and swept.lo < end) { - const button = @intFromEnum(sweep.button); + const button = @backingInt(sweep.button); var col = panes.File.rawDisplayCol(shown, @max(swept.lo, start) - start) -| scroll; const stop = panes.File.rawDisplayCol(shown, @min(swept.hi, end) - start) -| scroll; while (col < stop and col < columns) : (col += 1) { diff --git a/src/dump.zig b/src/dump.zig index 545d09ec..76a6de85 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -1100,7 +1100,7 @@ test "a restored session's column and workspace tags take more than one selectio try std.testing.expect(restored.col_tags[0].reserveSels()); try std.testing.expect(restored.global_tag.reserveSels()); try std.testing.expect(restored.fs.started != 0); - const stat = th.call(restored, .{ .tag = 1, .op = .getattr, .node = @intFromEnum(pardes.ctlfs.TopFile.index) }); + const stat = th.call(restored, .{ .tag = 1, .op = .getattr, .node = @backingInt(pardes.ctlfs.TopFile.index) }); try std.testing.expect(stat.reply.attr.mtime != 0); } @@ -1146,7 +1146,7 @@ test "a pane restored with unsaved text is asked about by Exit, Restore, Del and const node = if (std.mem.eql(u8, word, "Del") or std.mem.eql(u8, word, "get")) ctlfs.Node.of(restored.panes[id].?.serial, .ctl) else - @intFromEnum(ctlfs.TopFile.ctl); + @backingInt(ctlfs.TopFile.ctl); const line = if (std.mem.eql(u8, word, "Restore")) try std.fmt.bufPrint(&restore_line, "Restore {s}/d.zon\n", .{dir}) else if (std.mem.eql(u8, word, "Exit")) "Exit\n" else if (std.mem.eql(u8, word, "Del")) "Del\n" else "get\n"; const answer = th.wr(restored, node, line); try std.testing.expectEqual(ctlfs.Status.err, answer.reply.status); diff --git a/src/edit_cmd.zig b/src/edit_cmd.zig index d3377e09..447ea66b 100644 --- a/src/edit_cmd.zig +++ b/src/edit_cmd.zig @@ -495,7 +495,7 @@ test "Edit , | sort runs off the loop, through the session's shell in the file's try testing.expectEqualStrings(@import("ninep/ctl.zig").e_after_edit, after.reply.ename); try testing.expect(p.pipe.edit_run == null and !th.logHas(p, "before")); } - try testing.expectEqual(tree.E.INVAL, th.wr(p, @intFromEnum(tree.TopFile.exec), "Msg before\nEdit , | sort\n").errno()); + try testing.expectEqual(tree.E.INVAL, th.wr(p, @backingInt(tree.TopFile.exec), "Msg before\nEdit , | sort\n").errno()); } test "the held write asked again is parked again, then answered once, and a flush stops the Edit" { diff --git a/src/esp32p4.zig b/src/esp32p4.zig index ed18efd9..683d19e1 100644 --- a/src/esp32p4.zig +++ b/src/esp32p4.zig @@ -134,19 +134,19 @@ pub const GpioFn = *const fn (ctx: ?*anyopaque, pin: u16, was: *u8, now: *u8) ca var host_alloc: Allocator = undefined; fn hostAlloc(_: *anyopaque, len: usize, alignment: std.mem.Alignment, _: usize) ?[*]u8 { - return host_alloc.alloc(host_alloc.ctx, len, @intFromEnum(alignment)); + return host_alloc.alloc(host_alloc.ctx, len, @backingInt(alignment)); } fn hostResize(_: *anyopaque, mem: []u8, alignment: std.mem.Alignment, new_len: usize, _: usize) bool { - return host_alloc.resize(host_alloc.ctx, mem.ptr, mem.len, @intFromEnum(alignment), new_len); + return host_alloc.resize(host_alloc.ctx, mem.ptr, mem.len, @backingInt(alignment), new_len); } fn hostRemap(_: *anyopaque, mem: []u8, alignment: std.mem.Alignment, new_len: usize, _: usize) ?[*]u8 { - return if (host_alloc.resize(host_alloc.ctx, mem.ptr, mem.len, @intFromEnum(alignment), new_len)) mem.ptr else null; + return if (host_alloc.resize(host_alloc.ctx, mem.ptr, mem.len, @backingInt(alignment), new_len)) mem.ptr else null; } fn hostFree(_: *anyopaque, mem: []u8, alignment: std.mem.Alignment, _: usize) void { - host_alloc.free(host_alloc.ctx, mem.ptr, mem.len, @intFromEnum(alignment)); + host_alloc.free(host_alloc.ctx, mem.ptr, mem.len, @backingInt(alignment)); } const host_vtable: std.mem.Allocator.VTable = .{ @@ -447,19 +447,21 @@ fn apply(c: *pardes.Pardes, ev: vaxis.Event) void { else => null, }; if (button) |b| { - c.update(.{ .mouse = .{ - .button = b, - .kind = switch (m.type) { - .press => .press, - .release => .release, - .motion => .motion, - .drag => .drag, + c.update(.{ + .mouse = .{ + .button = b, + .kind = switch (m.type) { + .press => .press, + .release => .release, + .motion => .motion, + .drag => .drag, + }, + // Before the first cell (a drag past the edge): the edge. + .col = @intCast(@max(0, m.col)), + .row = @intCast(@max(0, m.row)), + .ctrl = m.mods.ctrl, }, - // Before the first cell (a drag past the edge): the edge. - .col = @intCast(@max(0, m.col)), - .row = @intCast(@max(0, m.row)), - .ctrl = m.mods.ctrl, - } }); + }); dirty = true; } }, diff --git a/src/esp32p4/app.zig b/src/esp32p4/app.zig index 4ee131ec..800e7597 100644 --- a/src/esp32p4/app.zig +++ b/src/esp32p4/app.zig @@ -235,17 +235,17 @@ var gpa_heap: heapmod.Heap = undefined; fn cAlloc(_: ?*anyopaque, len: usize, log2_align: u8) callconv(.c) ?[*]u8 { const a = gpa_heap.allocator(); - return a.vtable.alloc(a.ptr, len, @enumFromInt(log2_align), @returnAddress()); + return a.vtable.alloc(a.ptr, len, @fromBackingInt(@intCast(log2_align)), @returnAddress()); } fn cResize(_: ?*anyopaque, ptr: [*]u8, len: usize, log2_align: u8, new_len: usize) callconv(.c) bool { const a = gpa_heap.allocator(); - return a.vtable.resize(a.ptr, ptr[0..len], @enumFromInt(log2_align), new_len, @returnAddress()); + return a.vtable.resize(a.ptr, ptr[0..len], @fromBackingInt(@intCast(log2_align)), new_len, @returnAddress()); } fn cFree(_: ?*anyopaque, ptr: [*]u8, len: usize, log2_align: u8) callconv(.c) void { const a = gpa_heap.allocator(); - a.vtable.free(a.ptr, ptr[0..len], @enumFromInt(log2_align), @returnAddress()); + a.vtable.free(a.ptr, ptr[0..len], @fromBackingInt(@intCast(log2_align)), @returnAddress()); } const editor_allocator: Allocator = .{ diff --git a/src/esp32p4_9p.zig b/src/esp32p4_9p.zig index cd59b9df..5fcab85b 100644 --- a/src/esp32p4_9p.zig +++ b/src/esp32p4_9p.zig @@ -103,7 +103,7 @@ fn die(msg: []const u8) noreturn { .{ .rerror = .{ .ename = msg[0..@min(msg.len, ninep.errmax)] } }, ninep.notag, &buf, - // unreachable: the message is cut to errmax and buf is sized to it + // unreachable: the message is cut to errmax and buf is sized to it ) catch unreachable; uart.write(bytes); while (true) {} diff --git a/src/fonts.zig b/src/fonts.zig index 098bf36f..88cde63a 100644 --- a/src/fonts.zig +++ b/src/fonts.zig @@ -324,7 +324,7 @@ fn sfntBase(head: []const u8) ?usize { fn scratchFont(buf: *[64:0]u8, ext: []const u8) [:0]const u8 { return std.fmt.bufPrintSentinel(buf, "/tmp/pardes-fonts-test-{d}{s}", .{ @as(u32, @intCast(libc.getpid())), ext, - // unreachable: 23 bytes, a u32 pid (10) and a short extension fit 64 + // unreachable: 23 bytes, a u32 pid (10) and a short extension fit 64 }, 0) catch unreachable; } diff --git a/src/gui/Post.zig b/src/gui/Post.zig index 8d0e14d9..17e8d7e9 100644 --- a/src/gui/Post.zig +++ b/src/gui/Post.zig @@ -623,15 +623,15 @@ test "the uniform block is ghostty's, offset for offset, and the prefix names it try std.testing.expectEqual(@offsetOf(GhosttyUniforms, "selection_background_color"), @offsetOf(Uniforms, "selection_foreground_color")); // The prefix's block, member by member, in ghostty's GLSL names and types. const glsl = [_]struct { []const u8, []const u8 }{ - .{ "vec3", "iResolution" }, .{ "float", "iTime" }, .{ "float", "iTimeDelta" }, - .{ "float", "iFrameRate" }, .{ "int", "iFrame" }, .{ "float", "iChannelTime[4]" }, - .{ "vec3", "iChannelResolution[4]" }, .{ "vec4", "iMouse" }, .{ "vec4", "iDate" }, - .{ "float", "iSampleRate" }, .{ "vec4", "iCurrentCursor" }, .{ "vec4", "iPreviousCursor" }, - .{ "vec4", "iCurrentCursorColor" }, .{ "vec4", "iPreviousCursorColor" }, .{ "int", "iCurrentCursorStyle" }, - .{ "int", "iPreviousCursorStyle" }, .{ "int", "iCursorVisible" }, .{ "float", "iTimeCursorChange" }, - .{ "float", "iTimeFocus" }, .{ "int", "iFocus" }, .{ "vec3", "iPalette[256]" }, - .{ "vec3", "iBackgroundColor" }, .{ "vec3", "iForegroundColor" }, .{ "vec3", "iCursorColor" }, - .{ "vec3", "iCursorText" }, .{ "vec3", "iSelectionForegroundColor" }, .{ "vec3", "iSelectionBackgroundColor" }, + .{ "vec3", "iResolution" }, .{ "float", "iTime" }, .{ "float", "iTimeDelta" }, + .{ "float", "iFrameRate" }, .{ "int", "iFrame" }, .{ "float", "iChannelTime[4]" }, + .{ "vec3", "iChannelResolution[4]" }, .{ "vec4", "iMouse" }, .{ "vec4", "iDate" }, + .{ "float", "iSampleRate" }, .{ "vec4", "iCurrentCursor" }, .{ "vec4", "iPreviousCursor" }, + .{ "vec4", "iCurrentCursorColor" }, .{ "vec4", "iPreviousCursorColor" }, .{ "int", "iCurrentCursorStyle" }, + .{ "int", "iPreviousCursorStyle" }, .{ "int", "iCursorVisible" }, .{ "float", "iTimeCursorChange" }, + .{ "float", "iTimeFocus" }, .{ "int", "iFocus" }, .{ "vec3", "iPalette[256]" }, + .{ "vec3", "iBackgroundColor" }, .{ "vec3", "iForegroundColor" }, .{ "vec3", "iCursorColor" }, + .{ "vec3", "iCursorText" }, .{ "vec3", "iSelectionForegroundColor" }, .{ "vec3", "iSelectionBackgroundColor" }, }; try std.testing.expectEqual(ours.field_names.len, glsl.len); // Its three blocks (Globals, Palette, Colors) read as one, in order. @@ -673,7 +673,6 @@ test "a moved cursor becomes the previous one, stamped with the time of the move try std.testing.expectEqual([4]f32{ 1.0 / 255.0, 2.0 / 255.0, 3.0 / 255.0, 1 }, post.uniforms.selection_foreground_color); } - test "a still pass asks for no idle frames; one that reads the clock does" { var post: Post = .{}; const fake: *Pipeline = @ptrFromInt(0x1000); diff --git a/src/gui/gui.zig b/src/gui/gui.zig index b8687fd3..f0dd0682 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -1888,7 +1888,6 @@ const Gui = struct { sel_glow: SelGlow = .{}, hover_glow: SelGlow = .{}, /// G14: the cells last drawn and when each last changed. - /// The cursor's blink (blinkNow): when the frame drawn last arrived, /// a redraw owed for an edge, and this frame's cursor mode and alpha. frame_arrival_ns: u64 = 0, @@ -2291,7 +2290,7 @@ fn setTransitionFields( instance.present_y0 = presented[1]; instance.present_x1 = presented[2]; instance.present_y1 = presented[3]; - instance.effect = @intFromEnum(active.effect); + instance.effect = @backingInt(active.effect); instance.progress_bits = @bitCast(active.amount()); instance.serial = active.serial; instance.cell_coord = cell_coord; @@ -3356,8 +3355,8 @@ fn setStdinRaw() !void { term.lflag.ICANON = false; term.lflag.IEXTEN = false; term.lflag.ISIG = false; - term.cc[@intFromEnum(posix.V.MIN)] = 1; - term.cc[@intFromEnum(posix.V.TIME)] = 0; + term.cc[@backingInt(posix.V.MIN)] = 1; + term.cc[@backingInt(posix.V.TIME)] = 0; try posix.tcsetattr(0, .NOW, term); } @@ -5484,7 +5483,6 @@ test "a notch scrolls the core at once and the picture glides after it, a wrappe try std.testing.expect(!g.glide.pending and !g.glide.moving()); } - fn resetScroll(g: *Gui) void { g.scroll_pane = null; g.scroll_delta = 0; @@ -5519,13 +5517,15 @@ fn stepScroll(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { const down = left > 0; left += if (down) -1 else 1; const was = pane.scroll(); - core.update(.{ .mouse = .{ - .button = if (down) .wheel_down else .wheel_up, - .kind = .press, - .col = g.scroll_col, - .row = g.scroll_row, - .shift = true, // pardes's own scroll, never a program's wheel - } }); + core.update(.{ + .mouse = .{ + .button = if (down) .wheel_down else .wheel_up, + .kind = .press, + .col = g.scroll_col, + .row = g.scroll_row, + .shift = true, // pardes's own scroll, never a program's wheel + }, + }); if (pane.scroll() == was) { resetScroll(g); return; @@ -7251,7 +7251,7 @@ test "a rising pane past its mark stays inside its box" { var g: Gui = undefined; g.cell_w = 10; g.cell_h = 20; - var track: pardes.animation.Track = .{ .serial = 3, .phase = .opening, .effect = .vertical, .motion = @intFromEnum(pardes.animation.Motion.Flavour.bouncy) + 1, .frame_count = 20, .from = .{ .x = 0, .y = 10, .w = 40, .h = 10 }, .to = .{ .x = 0, .y = 0, .w = 40, .h = 10 } }; + var track: pardes.animation.Track = .{ .serial = 3, .phase = .opening, .effect = .vertical, .motion = @backingInt(pardes.animation.Motion.Flavour.bouncy) + 1, .frame_count = 20, .from = .{ .x = 0, .y = 10, .w = 40, .h = 10 }, .to = .{ .x = 0, .y = 0, .w = 40, .h = 10 } }; var peak: u16 = 0; var highest: f32 = 1e9; while (track.frame < track.frames()) : (track.frame += 1) { @@ -8788,7 +8788,6 @@ fn addPattern(g: *Gui, gpa: std.mem.Allocator, x0: f32, y0: f32, x1: f32, y1: f3 instance.effect |= checker_bit; } - /// How a lift of 0 to 1 stands off the page: the shadow's blur and offset /// in cell heights, and its darkest, where it leaves the caster's edge. /// Within §8.2's budget: sigma 0.4-0.8 cell, at most 30% darker at the edge. @@ -8926,7 +8925,6 @@ fn clipToBodies(g: *Gui, gpa: std.mem.Allocator, first: usize, bodies: []const [ }; } - /// Like shadowCeiling for a light colour laid over at `a` (sRGB blend, as /// the decor pipeline blends a colour that is not black): the largest `a` /// that keeps text and page apart by min(their contrast, 4.5). @@ -10099,7 +10097,7 @@ test "decor is read from the regions, each pane's in its own group" { try std.testing.expect(tracked.decor_count >= 4); try std.testing.expectEqual(still, groups.items[0].decor_count + tracked.decor_count); for (g.decor.items[tracked.decor_start..][0..tracked.decor_count]) |item| - try std.testing.expectEqual(@as(u32, @intFromEnum(pardes.animation.Transition.slide)), item.effect); + try std.testing.expectEqual(@as(u32, @backingInt(pardes.animation.Transition.slide)), item.effect); // Cursors stand still while panes move. try std.testing.expectEqual(@as(u32, 0), groups.items[groups.ink].decor_count); } @@ -10468,7 +10466,7 @@ fn appendCursorGlide(g: *Gui, surface: *const pardes.Surface, builder: *OverlayB fn appendWorkspacePet(g: *Gui, core: ?*const pardes.Pardes, surface: *const pardes.Surface, builder: *OverlayBuilder) void { const p = core orelse return; - const kind: pet.Kind = @enumFromInt(@intFromEnum(p.settings.pet)); + const kind: pet.Kind = @fromBackingInt(@intCast(@backingInt(p.settings.pet))); if (kind == .off or surface.rows == 0 or surface.cols == 0) { g.pet_state = .{}; return; diff --git a/src/host_io.zig b/src/host_io.zig index d789a77d..bef88172 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -572,7 +572,7 @@ pub const Shell = struct { const name = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(&ent.name)), 0); const pid = rcPid(name) orelse continue; if (pid == std.c.getpid()) continue; - if (std.posix.errno(std.c.kill(pid, @enumFromInt(0))) != .SRCH) continue; + if (std.posix.errno(std.c.kill(pid, @fromBackingInt(@intCast(0)))) != .SRCH) continue; if (name.len >= 64 or n == dead.len) continue; @memcpy(dead[n][0..name.len], name); dead_len[n] = name.len; @@ -1236,8 +1236,8 @@ pub fn resetChildSignals() void { const default: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.DFL }, .mask = posix.sigemptyset(), .flags = 0 }; var sig: u8 = 1; while (sig < 65) : (sig += 1) { - if (sig == @intFromEnum(posix.SIG.KILL) or sig == @intFromEnum(posix.SIG.STOP)) continue; - _ = std.c.sigaction(@enumFromInt(sig), &default, null); + if (sig == @backingInt(posix.SIG.KILL) or sig == @backingInt(posix.SIG.STOP)) continue; + _ = std.c.sigaction(@fromBackingInt(@intCast(sig)), &default, null); } const none = posix.sigemptyset(); posix.sigprocmask(posix.SIG.SETMASK, &none, null); @@ -1620,13 +1620,13 @@ pub fn forkShell( if (pid == 0) { resetChildSignals(); if (cwd_z) |path| if (chdir(path.ptr) != 0) { - const why = [_]u8{ 'c', @truncate(@intFromEnum(libc.errno(@as(c_int, -1)))) }; + const why = [_]u8{ 'c', @truncate(@backingInt(libc.errno(@as(c_int, -1)))) }; _ = libc.write(told[1], &why, why.len); _exit(126); }; if (envp) |env| _ = execve(spawn.path, &spawn.argv, env); _ = execv(spawn.path, &spawn.argv); - const why = [_]u8{ 'x', @truncate(@intFromEnum(libc.errno(@as(c_int, -1)))) }; + const why = [_]u8{ 'x', @truncate(@backingInt(libc.errno(@as(c_int, -1)))) }; _ = libc.write(told[1], &why, why.len); _exit(127); } @@ -1643,7 +1643,7 @@ pub fn forkShell( if (failed) |why| { _ = libc.close(master); _ = libc.waitpid(pid, null, 0); - const e: libc.E = @enumFromInt(why[1]); + const e: libc.E = @fromBackingInt(@intCast(why[1])); if (why[0] == 'c') return if (e == .NOENT or e == .NOTDIR) error.FileNotFound else error.AccessDenied; return switch (e) { // Itself, or its script's interpreter: told apart by whether it @@ -2167,7 +2167,7 @@ pub fn reapExited(pid: libc.pid_t) ?struct { status: ?u8 } { if (got != pid) return .{ .status = null }; const s: u32 = @bitCast(status); if (libc.W.IFEXITED(s)) return .{ .status = @truncate(libc.W.EXITSTATUS(s)) }; - if (libc.W.IFSIGNALED(s)) return .{ .status = @truncate(128 + @as(u32, @intFromEnum(libc.W.TERMSIG(s)))) }; + if (libc.W.IFSIGNALED(s)) return .{ .status = @truncate(128 + @as(u32, @backingInt(libc.W.TERMSIG(s)))) }; return .{ .status = null }; } @@ -2194,7 +2194,7 @@ pub fn exitStatus(pid: libc.pid_t, wait_ms: u32) ?u8 { if (got == pid) { const s: u32 = @bitCast(status); if (libc.W.IFEXITED(s)) return @truncate(libc.W.EXITSTATUS(s)); - if (libc.W.IFSIGNALED(s)) return @truncate(128 + @as(u32, @intFromEnum(libc.W.TERMSIG(s)))); + if (libc.W.IFSIGNALED(s)) return @truncate(128 + @as(u32, @backingInt(libc.W.TERMSIG(s)))); return null; } if (got < 0 or waited >= wait_ms) return null; @@ -2722,8 +2722,8 @@ test "a retired shell that ignores the hangup is killed and reaped, not left a z retireShell(pid); // A zombie still answers kill(pid, 0); only a reaped pid is gone. var waited: i64 = 0; - while (libc.kill(pid, @enumFromInt(0)) == 0 and waited < 2000) : (waited += 10) sleepMs(10); - try std.testing.expect(libc.kill(pid, @enumFromInt(0)) != 0); + while (libc.kill(pid, @fromBackingInt(@intCast(0))) == 0 and waited < 2000) : (waited += 10) sleepMs(10); + try std.testing.expect(libc.kill(pid, @fromBackingInt(@intCast(0))) != 0); try std.testing.expect(waited >= 90); // it did ignore the hangup } diff --git a/src/linux/v9fs.zig b/src/linux/v9fs.zig index 15945e7b..0d1e2e33 100644 --- a/src/linux/v9fs.zig +++ b/src/linux/v9fs.zig @@ -89,7 +89,7 @@ var sudo_pid: std.atomic.Value(c_int) = .init(-1); fn forwardSignal(sig: std.posix.SIG) callconv(.c) void { const pid = sudo_pid.load(.monotonic); - if (pid > 0) _ = kill(pid, @intCast(@intFromEnum(sig))); + if (pid > 0) _ = kill(pid, @intCast(@backingInt(sig))); } fn launch(arena: std.mem.Allocator, args: []const [:0]const u8) !u8 { @@ -123,8 +123,8 @@ fn launch(arena: std.mem.Allocator, args: []const [:0]const u8) !u8 { const default: std.posix.Sigaction = .{ .handler = .{ .handler = std.posix.SIG.DFL }, .mask = std.posix.sigemptyset(), .flags = 0 }; var sig: u8 = 1; while (sig < 65) : (sig += 1) { - if (sig == @intFromEnum(std.posix.SIG.KILL) or sig == @intFromEnum(std.posix.SIG.STOP)) continue; - _ = std.c.sigaction(@enumFromInt(sig), &default, null); + if (sig == @backingInt(std.posix.SIG.KILL) or sig == @backingInt(std.posix.SIG.STOP)) continue; + _ = std.c.sigaction(@fromBackingInt(@intCast(sig)), &default, null); } const none = std.posix.sigemptyset(); std.posix.sigprocmask(std.posix.SIG.SETMASK, &none, null); diff --git a/src/look.zig b/src/look.zig index f9c470cf..f4fbe52e 100644 --- a/src/look.zig +++ b/src/look.zig @@ -2555,7 +2555,7 @@ test "every entry point to Look takes one expansion: a diff line and a file:12:5 const line = modal.lineSlice(case.text, case.row); // A diff line written whole; a place, as a script writes it. const written = if (std.mem.eql(u8, case.name, "change.diff")) line else line[case.sweep[0] .. case.sweep[1] + 1]; - _ = th.wr(p, @intFromEnum(pardes.ctlfs.TopFile.look), written); + _ = th.wr(p, @backingInt(pardes.ctlfs.TopFile.look), written); }, .event_write_back => { const body = pane.file.?.content; diff --git a/src/macos.zig b/src/macos.zig index 37db0abd..21af41ae 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -1717,18 +1717,20 @@ fn mouseWithHit(button_arg: c_int, kind_arg: c_int, col: u16, row: u16, mods: u3 3 => .drag, else => return, }; - st.core.update(.{ .mouse = .{ - .body_hit = hit, - .tag_hit = tag_hit, - .button = button, - .kind = kind, - .col = col, - .row = row, - .ctrl = mods & 1 != 0, - // Option-click is B2 and Cmd-click B3 (mouse.emulateButton). - .alt = mods & 2 != 0, - .super = mods & 8 != 0, - } }); + st.core.update(.{ + .mouse = .{ + .body_hit = hit, + .tag_hit = tag_hit, + .button = button, + .kind = kind, + .col = col, + .row = row, + .ctrl = mods & 1 != 0, + // Option-click is B2 and Cmd-click B3 (mouse.emulateButton). + .alt = mods & 2 != 0, + .super = mods & 8 != 0, + }, + }); } export fn pardes_pointer_leave() void { @@ -2156,7 +2158,7 @@ export fn pardes_tag_layer_value(index: u32, field: u32) u32 { const layer = &st.core.surface.tag_layers[index]; return switch (field) { 0 => layer.cols, - 1 => @intFromEnum(layer.kind), + 1 => @backingInt(layer.kind), 2 => layer.id, 3 => layer.serial, 4 => layer.viewport.x, @@ -2238,7 +2240,7 @@ export fn pardes_pointer_shape() u32 { pardes.turn.wake(); defer pardes.turn.rest(); const st = &(state orelse return 0); - return @intFromEnum(st.core.surface.pointer_shape); + return @backingInt(st.core.surface.pointer_shape); } export fn pardes_cursor_y() i32 { @@ -2646,7 +2648,7 @@ fn encodeAttrs(style: pardes.CellStyle) u16 { attrs |= @as(u16, @intFromBool(style.reverse)) << 4; attrs |= @as(u16, @intFromBool(style.invisible)) << 5; attrs |= @as(u16, @intFromBool(style.strikethrough)) << 6; - attrs |= @as(u16, @intFromEnum(style.ul)) << 8; + attrs |= @as(u16, @backingInt(style.ul)) << 8; return attrs; } @@ -2896,21 +2898,21 @@ test "pardes.h matches the Zig boundary" { try expectEqual(@as(u8, c.PARDES_CELL_HOVER), cell_flag_hover); try expectEqual(@as(u16, c.PARDES_TOPBAR_H), pardes.TOPBAR_H); try expectEqual(@as(u32, c.PARDES_SCENE_CRT), scene_flag_crt); - try expectEqual(@as(u8, c.PARDES_PANEL_OPENING), @intFromEnum(animation.Phase.opening)); - try expectEqual(@as(u8, c.PARDES_PANEL_MOVING), @intFromEnum(animation.Phase.moving)); - try expectEqual(@as(u8, c.PARDES_PANEL_CLOSING), @intFromEnum(animation.Phase.closing)); - try expectEqual(@as(u8, c.PARDES_PANEL_OFF), @intFromEnum(animation.Transition.off)); - try expectEqual(@as(u8, c.PARDES_PANEL_SLIDE), @intFromEnum(animation.Transition.slide)); - try expectEqual(@as(u8, c.PARDES_PANEL_ZOOM), @intFromEnum(animation.Transition.zoom)); - try expectEqual(@as(u8, c.PARDES_PANEL_DISSOLVE), @intFromEnum(animation.Transition.dissolve)); - try expectEqual(@as(u8, c.PARDES_PANEL_ASCII), @intFromEnum(animation.Transition.ascii)); - try expectEqual(@as(u8, c.PARDES_PANEL_VERTICAL), @intFromEnum(animation.Transition.vertical)); - try expectEqual(@as(u8, c.PARDES_PANEL_EDGES), @intFromEnum(animation.Transition.edges)); - try expectEqual(@as(u8, c.PARDES_PANEL_FALL), @intFromEnum(animation.Transition.fall)); - try expectEqual(@as(u8, c.PARDES_PANEL_WAVE), @intFromEnum(animation.Transition.wave)); - try expectEqual(@as(u8, c.PARDES_PANEL_CURTAIN), @intFromEnum(animation.Transition.curtain)); - try expectEqual(@as(u8, c.PARDES_PANEL_SCRAMBLE), @intFromEnum(animation.Transition.scramble)); - try expectEqual(@as(u8, c.PARDES_PANEL_TYPEWRITER), @intFromEnum(animation.Transition.typewriter)); + try expectEqual(@as(u8, c.PARDES_PANEL_OPENING), @backingInt(animation.Phase.opening)); + try expectEqual(@as(u8, c.PARDES_PANEL_MOVING), @backingInt(animation.Phase.moving)); + try expectEqual(@as(u8, c.PARDES_PANEL_CLOSING), @backingInt(animation.Phase.closing)); + try expectEqual(@as(u8, c.PARDES_PANEL_OFF), @backingInt(animation.Transition.off)); + try expectEqual(@as(u8, c.PARDES_PANEL_SLIDE), @backingInt(animation.Transition.slide)); + try expectEqual(@as(u8, c.PARDES_PANEL_ZOOM), @backingInt(animation.Transition.zoom)); + try expectEqual(@as(u8, c.PARDES_PANEL_DISSOLVE), @backingInt(animation.Transition.dissolve)); + try expectEqual(@as(u8, c.PARDES_PANEL_ASCII), @backingInt(animation.Transition.ascii)); + try expectEqual(@as(u8, c.PARDES_PANEL_VERTICAL), @backingInt(animation.Transition.vertical)); + try expectEqual(@as(u8, c.PARDES_PANEL_EDGES), @backingInt(animation.Transition.edges)); + try expectEqual(@as(u8, c.PARDES_PANEL_FALL), @backingInt(animation.Transition.fall)); + try expectEqual(@as(u8, c.PARDES_PANEL_WAVE), @backingInt(animation.Transition.wave)); + try expectEqual(@as(u8, c.PARDES_PANEL_CURTAIN), @backingInt(animation.Transition.curtain)); + try expectEqual(@as(u8, c.PARDES_PANEL_SCRAMBLE), @backingInt(animation.Transition.scramble)); + try expectEqual(@as(u8, c.PARDES_PANEL_TYPEWRITER), @backingInt(animation.Transition.typewriter)); try expectEqual(@as(u21, c.PARDES_KEY_ENTER), pardes.Key.enter); try expectEqual(@as(u21, c.PARDES_KEY_ESCAPE), pardes.Key.escape); @@ -2926,24 +2928,24 @@ test "pardes.h matches the Zig boundary" { try expectEqual(@as(u21, c.PARDES_KEY_PAGE_DOWN), pardes.Key.page_down); try expectEqual(@as(u21, c.PARDES_KEY_DELETE), pardes.Key.delete); - try expectEqual(c.PARDES_MOUSE_LEFT, @intFromEnum(pardes.Mouse.Button.left)); - try expectEqual(c.PARDES_MOUSE_MIDDLE, @intFromEnum(pardes.Mouse.Button.middle)); - try expectEqual(c.PARDES_MOUSE_RIGHT, @intFromEnum(pardes.Mouse.Button.right)); - try expectEqual(c.PARDES_MOUSE_WHEEL_UP, @intFromEnum(pardes.Mouse.Button.wheel_up)); - try expectEqual(c.PARDES_MOUSE_WHEEL_DOWN, @intFromEnum(pardes.Mouse.Button.wheel_down)); - try expectEqual(c.PARDES_MOUSE_WHEEL_LEFT, @intFromEnum(pardes.Mouse.Button.wheel_left)); - try expectEqual(c.PARDES_MOUSE_WHEEL_RIGHT, @intFromEnum(pardes.Mouse.Button.wheel_right)); - try expectEqual(c.PARDES_MOUSE_NONE, @intFromEnum(pardes.Mouse.Button.none)); - try expectEqual(c.PARDES_MOUSE_BACK, @intFromEnum(pardes.Mouse.Button.back)); - try expectEqual(c.PARDES_MOUSE_FORWARD, @intFromEnum(pardes.Mouse.Button.forward)); - try expectEqual(c.PARDES_MOUSE_PRESS, @intFromEnum(pardes.Mouse.Kind.press)); - try expectEqual(c.PARDES_MOUSE_RELEASE, @intFromEnum(pardes.Mouse.Kind.release)); - try expectEqual(c.PARDES_MOUSE_MOTION, @intFromEnum(pardes.Mouse.Kind.motion)); - try expectEqual(c.PARDES_MOUSE_DRAG, @intFromEnum(pardes.Mouse.Kind.drag)); - - try expectEqual(c.PARDES_HAPTIC_NONE, @intFromEnum(pardes.Haptic.none)); - try expectEqual(c.PARDES_HAPTIC_EXEC, @intFromEnum(pardes.Haptic.exec)); - try expectEqual(c.PARDES_HAPTIC_LOOK, @intFromEnum(pardes.Haptic.look)); + try expectEqual(c.PARDES_MOUSE_LEFT, @backingInt(pardes.Mouse.Button.left)); + try expectEqual(c.PARDES_MOUSE_MIDDLE, @backingInt(pardes.Mouse.Button.middle)); + try expectEqual(c.PARDES_MOUSE_RIGHT, @backingInt(pardes.Mouse.Button.right)); + try expectEqual(c.PARDES_MOUSE_WHEEL_UP, @backingInt(pardes.Mouse.Button.wheel_up)); + try expectEqual(c.PARDES_MOUSE_WHEEL_DOWN, @backingInt(pardes.Mouse.Button.wheel_down)); + try expectEqual(c.PARDES_MOUSE_WHEEL_LEFT, @backingInt(pardes.Mouse.Button.wheel_left)); + try expectEqual(c.PARDES_MOUSE_WHEEL_RIGHT, @backingInt(pardes.Mouse.Button.wheel_right)); + try expectEqual(c.PARDES_MOUSE_NONE, @backingInt(pardes.Mouse.Button.none)); + try expectEqual(c.PARDES_MOUSE_BACK, @backingInt(pardes.Mouse.Button.back)); + try expectEqual(c.PARDES_MOUSE_FORWARD, @backingInt(pardes.Mouse.Button.forward)); + try expectEqual(c.PARDES_MOUSE_PRESS, @backingInt(pardes.Mouse.Kind.press)); + try expectEqual(c.PARDES_MOUSE_RELEASE, @backingInt(pardes.Mouse.Kind.release)); + try expectEqual(c.PARDES_MOUSE_MOTION, @backingInt(pardes.Mouse.Kind.motion)); + try expectEqual(c.PARDES_MOUSE_DRAG, @backingInt(pardes.Mouse.Kind.drag)); + + try expectEqual(c.PARDES_HAPTIC_NONE, @backingInt(pardes.Haptic.none)); + try expectEqual(c.PARDES_HAPTIC_EXEC, @backingInt(pardes.Haptic.exec)); + try expectEqual(c.PARDES_HAPTIC_LOOK, @backingInt(pardes.Haptic.look)); try expectEqual(@as(u16, c.PARDES_ATTR_BOLD), encodeAttrs(.{ .bold = true })); try expectEqual(@as(u16, c.PARDES_ATTR_DIM), encodeAttrs(.{ .dim = true })); diff --git a/src/main.zig b/src/main.zig index e3bae75f..64614daa 100644 --- a/src/main.zig +++ b/src/main.zig @@ -499,7 +499,7 @@ fn nativeMain(init: std.process.Init) !void { if (!outside) { const owner = std.mem.span(std.c.getenv("PARDES_PID") orelse break :forwarding); const pid = std.fmt.parseInt(std.c.pid_t, owner, 10) catch break :forwarding; - if (pid <= 0 or std.c.kill(pid, @enumFromInt(0)) != 0) break :forwarding; + if (pid <= 0 or std.c.kill(pid, @fromBackingInt(@intCast(0))) != 0) break :forwarding; } // Can I reach it? That is the other two, and it is a separate answer. diff --git a/src/mini.zig b/src/mini.zig index 8af64201..ce291c99 100644 --- a/src/mini.zig +++ b/src/mini.zig @@ -130,7 +130,7 @@ pub fn generate(gpa: std.mem.Allocator, source: []const u8, styles: []const u8) if (source.len > max_input_bytes) return error.MiniTooLarge; if (!std.unicode.utf8ValidateSlice(source)) return error.InvalidUtf8; if (styles.len != 0 and styles.len != source.len) return error.InvalidMiniColors; - for (styles) |color| if (color > @intFromEnum(syntax.Syn.comment)) return error.InvalidMiniColors; + for (styles) |color| if (color > @backingInt(syntax.Syn.comment)) return error.InvalidMiniColors; const len = try render(null, source, styles); const content = try gpa.alloc(u8, len); errdefer gpa.free(content); @@ -248,17 +248,17 @@ test "Mini chooses highlighted dots over plain ink with stable color ties" { const gpa = std.testing.allocator; const source = "xx\nxx\nxx\nxx\n"; var styles: [source.len]u8 = @splat(0); - styles[0] = @intFromEnum(syntax.Syn.keyword); + styles[0] = @backingInt(syntax.Syn.keyword); const rare = try generate(gpa, source, &styles); defer rare.deinit(gpa); try std.testing.expectEqualStrings("⣿\n", rare.content); try std.testing.expectEqualSlices(u8, &.{ 1, 1, 1, 0 }, rare.colors); - styles[0] = @intFromEnum(syntax.Syn.string); - styles[1] = @intFromEnum(syntax.Syn.number); + styles[0] = @backingInt(syntax.Syn.string); + styles[1] = @backingInt(syntax.Syn.number); const tied = try generate(gpa, source, &styles); defer tied.deinit(gpa); try std.testing.expectEqualSlices(u8, &.{ 2, 2, 2, 0 }, tied.colors); - styles[3] = @intFromEnum(syntax.Syn.number); + styles[3] = @backingInt(syntax.Syn.number); const majority = try generate(gpa, source, &styles); defer majority.deinit(gpa); try std.testing.expectEqualSlices(u8, &.{ 3, 3, 3, 0 }, majority.colors); diff --git a/src/mouse.zig b/src/mouse.zig index 536a4fdb..43323f9a 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -379,7 +379,7 @@ fn programMouse(p: *Pardes, m: Mouse) bool { .none => null, else => return false, }; - const bit: u3 = if (button) |b| @as(u3, 1) << @intCast(@intFromEnum(b)) else 0; + const bit: u3 = if (button) |b| @as(u3, 1) << @intCast(@backingInt(b)) else 0; const at = p.presentation.pointer(p.screen_w, p.screen_h, @min(m.col, p.screen_w -| 1), @min(m.row, p.screen_h -| 1)); var mods: panes.terminal.MouseMods = .{ .shift = m.shift, .alt = m.alt, .ctrl = m.ctrl }; var buf: [64]u8 = undefined; @@ -701,7 +701,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { // look; the rest of the gesture is inert if (p.drag == .select and p.drag.select.button == config.look_button) { if (p.panes[p.drag.select.id]) |t| { - t.sel[@intFromEnum(config.look_button)].state = .none; + t.sel[@backingInt(config.look_button)].state = .none; if (comptime pdf_enabled) panes.Pdf.pointerCancel(t, p.drag.select.pdf); } @@ -812,7 +812,7 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { // an execute or look drag cancels it (textselect23's mask) if (p.drag == .select) { if (p.panes[p.drag.select.id]) |t| { - t.sel[@intFromEnum(p.drag.select.button)].state = .none; + t.sel[@backingInt(p.drag.select.button)].state = .none; if (comptime pdf_enabled) panes.Pdf.pointerCancel(t, p.drag.select.pdf); } @@ -833,8 +833,8 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { pane.scrollBy(if (m.button == config.look_button) local else -local); } else if (edit.pointerTextSelection(p, id, mcol, mrow, m.body_hit, p.pointer_tag_hit)) |pointed| { if (m.button == config.look_button) p.active = id; - pane.clearPointerSelection(@intFromEnum(m.button)); - pane.sel[@intFromEnum(m.button)] = pointed.sel; + pane.clearPointerSelection(@backingInt(m.button)); + pane.sel[@backingInt(m.button)] = pointed.sel; p.drag = .{ .select = .{ .id = id, @@ -906,7 +906,7 @@ pub fn dragUpdate(p: *Pardes, mcol: u16, mrow: u16, body_hit: ?Mouse.BodyHit) vo .select => |*s| { if (p.panes[s.id]) |pane| { const r = p.rects[s.id]; - const b = @intFromEnum(s.button); + const b = @backingInt(s.button); const tag_rows: i32 = pane.tag_rows; if (pane.body_rows > 0 and pane.sel[b].r0 >= tag_rows) if (body_hit) |supplied| { const mapped_hit = bodyHitForPane(p, s.id, supplied, true) orelse return; @@ -1235,10 +1235,10 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { } if (s.chorded) { // a cut/paste chord consumed this drag; the release is inert - pane.sel[@intFromEnum(s.button)].state = .none; + pane.sel[@backingInt(s.button)].state = .none; return; } - const b = @intFromEnum(s.button); + const b = @backingInt(s.button); pane.sel[b].state = .done; if (s.button == config.select_button) { const sl = pane.sel[sel_slot]; @@ -1501,7 +1501,7 @@ test "plain left click clears explicit modal selection" { try std.testing.expectEqual(@as(i32, 3), pane.body.cur_col); try std.testing.expect(!pane.body.vsel.active); try std.testing.expect(!pane.body.msel.active); - try std.testing.expectEqual(.none, pane.sel[@intFromEnum(config.select_button)].state); + try std.testing.expectEqual(.none, pane.sel[@backingInt(config.select_button)].state); } test "selection drag and queued release do not enter panel pending state" { diff --git a/src/ninep/addr.zig b/src/ninep/addr.zig index 3feda5a2..86d2d49e 100644 --- a/src/ninep/addr.zig +++ b/src/ninep/addr.zig @@ -638,9 +638,9 @@ test "the address language, form by form" { } // Each failure says which it is. for ([_][2][]const u8{ - .{ "zzz", e_syntax }, .{ "/nomatch/", e_no_match }, .{ "99", e_range }, - .{ "#999", e_range }, .{ "/a[/", e_regexp }, .{ "/(a/", e_regexp }, - .{ "/*a/", e_regexp }, .{ "99:1", e_range }, .{ "2:0", e_col_zero }, + .{ "zzz", e_syntax }, .{ "/nomatch/", e_no_match }, .{ "99", e_range }, + .{ "#999", e_range }, .{ "/a[/", e_regexp }, .{ "/(a/", e_regexp }, + .{ "/*a/", e_regexp }, .{ "99:1", e_range }, .{ "2:0", e_col_zero }, }) |c| { _ = th.wr(p, addr, "#0"); try testing.expectEqualStrings(c[1], th.wr(p, addr, c[0]).reply.ename); diff --git a/src/ninep/cols.zig b/src/ninep/cols.zig index 59f6ae42..6f5bee23 100644 --- a/src/ninep/cols.zig +++ b/src/ninep/cols.zig @@ -34,7 +34,7 @@ pub fn writeLayout(p: *Pardes, w: *std.Io.Writer) !void { const active = activeColumn(p); for (0..p.ncol) |c| { try w.print("{d} {d} {d} {d} {s} {s}", .{ - layout.columnSerial(p, c), c, p.col_x[c], p.col_w[c], + layout.columnSerial(p, c), c, p.col_x[c], p.col_w[c], if (active == c) "current" else "notcurrent", if (p.col_n[c] == 0) "empty" else "full", }); for (p.col_panes[c][0..p.col_n[c]]) |id| if (p.panes[id]) |pane| try w.print(" {d}", .{pane.serial}); @@ -229,8 +229,8 @@ test "Joincol is refused when the joined column cannot give each pane its tag an const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 12 }); defer p.deinit(); while (p.nextEffect()) |_| {} - const ctl = @intFromEnum(tree.TopFile.ctl); - const focus = @intFromEnum(tree.TopFile.focus); + const ctl = @backingInt(tree.TopFile.ctl); + const focus = @backingInt(tree.TopFile.focus); // Two panes in the first column, then a second column of two. const a = try th.newPane(p); _ = a; @@ -257,10 +257,10 @@ test "pane/new takes rows from a pane in another column before refusing ENOSPC" while (p.nextEffect()) |_| {} const first = p.panes[p.active].?.serial; // A second column holding one tall pane. - try testing.expectEqual(tree.Status.ok, th.wr(p, @intFromEnum(tree.TopFile.ctl), "Newcol\n").reply.status); + try testing.expectEqual(tree.Status.ok, th.wr(p, @backingInt(tree.TopFile.ctl), "Newcol\n").reply.status); const tall = try th.newPane(p); const tall_col = layout.findPane(p, p.paneBySerial(tall).?).?.col; - const focus = @intFromEnum(tree.TopFile.focus); + const focus = @backingInt(tree.TopFile.focus); var digits: [16]u8 = undefined; // From the first column, until pane/new is refused. var moved = false; @@ -289,7 +289,7 @@ test "exactly 4096 bytes written with echo's newline after a truncation fit ever defer p.deinit(); const serial = th.serialOf(p); const text = &@as([4096]u8, @splat('w')) ++ "\n"; - for ([_]u64{ tree.Node.of(serial, .tag), tree.Node.ofCol(layout.columnSerial(p, 0), .tag), @intFromEnum(tree.TopFile.tag) }) |node| { + for ([_]u64{ tree.Node.of(serial, .tag), tree.Node.ofCol(layout.columnSerial(p, 0), .tag), @backingInt(tree.TopFile.tag) }) |node| { _ = th.call(p, .{ .tag = 1, .op = .setattr, .node = node, .truncate = true }); const h = th.call(p, .{ .tag = 2, .op = .open, .node = node, .omode = 1 }).reply.handle; const r = th.call(p, .{ .tag = 3, .op = .write, .node = node, .handle = h, .data = text }); @@ -320,8 +320,8 @@ test "a Newcol refused because the tags would not fit logs its err alone and spe } try testing.expect(p.col_n[col] >= 2); p.sync(); - const ctl = @intFromEnum(tree.TopFile.ctl); - const focus = @intFromEnum(tree.TopFile.focus); + const ctl = @backingInt(tree.TopFile.ctl); + const focus = @backingInt(tree.TopFile.focus); var digits: [16]u8 = undefined; const own = try std.fmt.bufPrint(&digits, "{d}\n", .{pane.serial}); var refused = false; @@ -349,7 +349,7 @@ test "a Newcol refused because the tags would not fit logs its err alone and spe test "a tagexec word that makes, acts on and focuses no pane reads back nothing" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const tagexec = @intFromEnum(tree.TopFile.tagexec); + const tagexec = @backingInt(tree.TopFile.tagexec); try testing.expectEqual(tree.Status.ok, th.wr(p, tagexec, "Newcol\n").reply.status); try testing.expectEqualStrings("", th.rd(p, tagexec, 0, 64).bytes); // A column's New makes one, and answers it. @@ -362,7 +362,7 @@ test "a tagexec word that makes, acts on and focuses no pane reads back nothing" test "New written to a column's ctl reads back the new pane alone, as its exec does" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const root_exec = @intFromEnum(tree.TopFile.exec); + const root_exec = @backingInt(tree.TopFile.exec); _ = th.wr(p, root_exec, "Msg before\n"); const ctl_node = tree.Node.ofCol(layout.columnSerial(p, 0), .ctl); try testing.expectEqual(tree.Status.ok, th.wr(p, ctl_node, "New\n").reply.status); @@ -390,7 +390,7 @@ test "a pane's word written to /tagexec or a column's exec is refused, and acts const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); const col_exec = tree.Node.ofCol(layout.columnSerial(p, 0), .exec); - for ([_]u64{ @intFromEnum(tree.TopFile.tagexec), col_exec }) |node| { + for ([_]u64{ @backingInt(tree.TopFile.tagexec), col_exec }) |node| { for ([_][]const u8{ "Undo\n", "Msg hi\n", "Redo\n" }) |line| { const refused = th.wr(p, node, line); try testing.expectEqual(E.INVAL, refused.errno()); @@ -411,7 +411,7 @@ test "Help and Find at /tagexec act in the session's directory, not the keyboard const session = buf[0..try tmp.dir.realPath(testing.io, &buf)]; @memcpy(p.session_dir[0..session.len], session); p.session_dir_len = @intCast(session.len); - const tagexec = @intFromEnum(tree.TopFile.tagexec); + const tagexec = @backingInt(tree.TopFile.tagexec); for ([_][]const u8{ "Help\n", "Find needle\n" }) |line| { try testing.expectEqual(tree.Status.ok, th.wr(p, tagexec, line).reply.status); const made = p.panes[p.active].?.file.?.path; @@ -427,7 +427,7 @@ test "a shell command at /tagexec or a column's exec is a command pane in the se const term = p.panes[p.active].?; try testing.expect(pardes.exec.takesCommandLine(p, p.active)); const col_exec = tree.Node.ofCol(layout.columnSerial(p, 0), .exec); - for ([_]u64{ @intFromEnum(tree.TopFile.tagexec), col_exec }) |node| { + for ([_]u64{ @backingInt(tree.TopFile.tagexec), col_exec }) |node| { p.active = p.paneBySerial(term.serial).?; const before = p.next_serial; const r = th.wr(p, node, "echo from-the-tag\n"); @@ -443,7 +443,7 @@ test "a shell command at /tagexec or a column's exec is a command pane in the se test "New and Tty run at /tagexec and a column's exec, with no pane at all too" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const tagexec = @intFromEnum(tree.TopFile.tagexec); + const tagexec = @backingInt(tree.TopFile.tagexec); const col_exec = tree.Node.ofCol(layout.columnSerial(p, 0), .exec); for ([_]u64{ tagexec, col_exec }) |node| for ([_][]const u8{ "New\n", "Tty\n" }) |line| { const before = p.next_serial; @@ -469,7 +469,7 @@ test "every pane word a tag no pane owns does not hold is refused there, Edit in const Builtin = pardes.builtins.registry.Builtin(); const col_exec = tree.Node.ofCol(layout.columnSerial(p, 0), .exec); for ([_]struct { node: u64, own: []const u8 }{ - .{ .node = @intFromEnum(tree.TopFile.tagexec), .own = pardes.config.topbar_str }, + .{ .node = @backingInt(tree.TopFile.tagexec), .own = pardes.config.topbar_str }, .{ .node = col_exec, .own = tagline.column_tag_default }, }) |tag_file| { var checked: usize = 0; @@ -517,7 +517,7 @@ test "layout lists each column's place, panes and state, and the active one" { const first_serial = layout.columnSerial(p, 0); const new_serial = layout.columnSerial(p, 1); try testing.expect(first_serial != new_serial); - const layout_node = @intFromEnum(tree.TopFile.layout); + const layout_node = @backingInt(tree.TopFile.layout); const text = th.rd(p, layout_node, 0, 4096).bytes; var want: [256]u8 = undefined; const first = try std.fmt.bufPrint(&want, "{d} 0 {d} {d} notcurrent full {d}\n", .{ first_serial, p.col_x[0], p.col_w[0], p.panes[0].?.serial }); @@ -528,19 +528,19 @@ test "layout lists each column's place, panes and state, and the active one" { try testing.expect(text.len > 0); try testing.expectEqual(@as(u64, 0), th.call(p, .{ .tag = 1, .op = .getattr, .node = layout_node }).reply.attr.size); // generated by each read // /index says which column each pane is in, by its serial, last. - try testing.expect(std.mem.endsWith(u8, th.rd(p, @intFromEnum(tree.TopFile.index), 0, 4096).bytes, try std.fmt.bufPrint(&want, " {d}\n", .{first_serial}))); + try testing.expect(std.mem.endsWith(u8, th.rd(p, @backingInt(tree.TopFile.index), 0, 4096).bytes, try std.fmt.bufPrint(&want, " {d}\n", .{first_serial}))); try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "newcol {d}\n", .{new_serial}))); // A column that closes takes its name with it; the others keep theirs. try p.removeColumn(1); try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "delcol {d}\n", .{new_serial}))); - try testing.expectEqual(E.NOENT, th.look_up(p, @intFromEnum(tree.TopFile.col), try std.fmt.bufPrint(&want, "{d}", .{new_serial})).errno()); + try testing.expectEqual(E.NOENT, th.look_up(p, @backingInt(tree.TopFile.col), try std.fmt.bufPrint(&want, "{d}", .{new_serial})).errno()); try testing.expectEqual(first_serial, layout.columnSerial(p, 0)); } test "a column's tag and the workspace's read, replace and append as a pane tag does, on one line" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const col_dir = @intFromEnum(tree.TopFile.col); + const col_dir = @backingInt(tree.TopFile.col); const serial = layout.columnSerial(p, 0); var name: [16]u8 = undefined; try testing.expectEqual(tree.Status.ok, th.look_up(p, col_dir, try std.fmt.bufPrint(&name, "{d}", .{serial})).reply.status); @@ -557,7 +557,7 @@ test "a column's tag and the workspace's read, replace and append as a pane tag // `>>` appends; a newline in a one-line tag is a space. _ = th.wr(p, tag, " Lint\nNow"); try testing.expectEqualStrings("Make Lint Now", th.rd(p, tag, 0, 4096).bytes); - const top = @intFromEnum(tree.TopFile.tag); + const top = @backingInt(tree.TopFile.tag); _ = th.call(p, .{ .tag = 3, .op = .setattr, .node = top, .truncate = true }); _ = th.wr(p, top, "Newcol Exit\n"); try testing.expectEqualStrings("Newcol Exit", tagline.topbar(p)); @@ -574,11 +574,11 @@ test "a focus write makes its pane's column the active one: layout says so and p p.sync(); try testing.expectEqual(@as(usize, 1), layout.findPane(p, p.active).?.col); var digits: [16]u8 = undefined; - _ = th.wr(p, @intFromEnum(tree.TopFile.focus), try std.fmt.bufPrint(&digits, "{d}\n", .{left})); + _ = th.wr(p, @backingInt(tree.TopFile.focus), try std.fmt.bufPrint(&digits, "{d}\n", .{left})); var want: [32]u8 = undefined; - const text = th.rd(p, @intFromEnum(tree.TopFile.layout), 0, 4096).bytes; + const text = th.rd(p, @backingInt(tree.TopFile.layout), 0, 4096).bytes; try testing.expect(std.mem.endsWith(u8, text, try std.fmt.bufPrint(&want, "active {d}\n", .{layout.columnSerial(p, 0)}))); - const made = th.call(p, .{ .tag = 1, .op = .open, .node = @intFromEnum(tree.TopFile.new) }).reply.handle; + const made = th.call(p, .{ .tag = 1, .op = .open, .node = @backingInt(tree.TopFile.new) }).reply.handle; try testing.expectEqual(@as(usize, 0), layout.findPane(p, p.paneBySerial(made).?).?.col); } } @@ -590,7 +590,7 @@ test "a refused write after a truncation leaves every kind of tag as it was, and const col = layout.columnSerial(p, 0); const big = &@as([limits.max_tag_tail + 1]u8, @splat('w')); // Each tag: a truncating open, then a write too long: nothing changes. - for ([_]u64{ Node.of(serial, .tag), Node.ofCol(col, .tag), @intFromEnum(tree.TopFile.tag) }) |node| { + for ([_]u64{ Node.of(serial, .tag), Node.ofCol(col, .tag), @backingInt(tree.TopFile.tag) }) |node| { _ = th.wr(p, node, " Mine"); const before = try testing.allocator.dupe(u8, th.rd(p, node, 0, 1 << 16).bytes); defer testing.allocator.free(before); @@ -651,13 +651,13 @@ test "a column's ctl and exec act on it as its tag would, and rmdir closes it on try testing.expectEqual(@as(?usize, 0), layout.columnBySerial(p, right)); try testing.expect(std.mem.endsWith(u8, headerText(p, right).?, " Mine")); // The root's ctl points a column word at the column's own. - try testing.expect(std.mem.endsWith(u8, th.wr(p, @intFromEnum(tree.TopFile.ctl), "Delcol\n").reply.ename, "write it to col//ctl")); + try testing.expect(std.mem.endsWith(u8, th.wr(p, @backingInt(tree.TopFile.ctl), "Delcol\n").reply.ename, "write it to col//ctl")); } test "tagexec runs a word as a click in the workspace tag; exec files read back what they touched; their messages are the session's" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const tagexec = @intFromEnum(tree.TopFile.tagexec); + const tagexec = @backingInt(tree.TopFile.tagexec); try testing.expectEqual(tree.Status.ok, th.look_up(p, tree.root, "tagexec").reply.status); try testing.expectEqual(tree.Status.ok, th.wr(p, tagexec, "Newcol\n").reply.status); try testing.expectEqual(@as(usize, 2), p.ncol); @@ -680,7 +680,7 @@ test "a word run from the workspace's or a column's tag runs in the session's di defer p.deinit(); const session = p.sessionDir(); try testing.expect(!std.mem.eql(u8, session, pardes.Pardes.paneDir(p.panes[0].?))); // the file is elsewhere - const dirs = [_]u64{ @intFromEnum(tree.TopFile.tagexec), Node.ofCol(layout.columnSerial(p, 0), .exec) }; + const dirs = [_]u64{ @backingInt(tree.TopFile.tagexec), Node.ofCol(layout.columnSerial(p, 0), .exec) }; for (dirs) |node| { try testing.expectEqual(tree.Status.ok, th.wr(p, node, "true\n").reply.status); const made = p.paneBySerial(p.fs.results[0]).?; diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 6b4bbafb..3e7c367b 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -1277,15 +1277,15 @@ const withFile = th.withFile; const serialOf = th.serialOf; const Node = tree.Node; const Status = tree.Status; -const root_status = @intFromEnum(tree.TopFile.status); -const root_look = @intFromEnum(tree.TopFile.look); -const root_exec = @intFromEnum(tree.TopFile.exec); +const root_status = @backingInt(tree.TopFile.status); +const root_look = @backingInt(tree.TopFile.look); +const root_exec = @backingInt(tree.TopFile.exec); test "a control character in a write to any ctl refuses the whole write, and a quoted line shows a tab as a blank" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); const col = layout.columnSerial(p, 0); - for ([_]u64{ @intFromEnum(tree.TopFile.ctl), Node.of(serialOf(p), .ctl), Node.ofCol(col, .ctl) }) |node| { + for ([_]u64{ @backingInt(tree.TopFile.ctl), Node.of(serialOf(p), .ctl), Node.ofCol(col, .ctl) }) |node| { const r = wr(p, node, "Wrap off\nbo\x01gus\n"); try testing.expectEqual(E.INVAL, r.errno()); try testing.expectEqualStrings(e_control, r.reply.ename); @@ -1325,7 +1325,7 @@ test "pane ctl read is acme's fields -- index's five, width in cells, font, tab test "commands lists every builtin with its argument and the ctl that takes it" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const node = @intFromEnum(tree.TopFile.commands); + const node = @backingInt(tree.TopFile.commands); const listed = rd(p, node, 0, 1 << 16); try testing.expectEqual(@as(u64, listed.bytes.len), call(p, .{ .tag = 1, .op = .getattr, .node = node }).reply.attr.size); try testing.expectEqual(E.PERM, wr(p, node, "Del\n").errno()); @@ -1372,7 +1372,7 @@ test "focus reads the pane with the keyboard, and a serial written to it moves t defer p.deinit(); const first = serialOf(p); const second = try th.newPane(p); - const focus = @intFromEnum(tree.TopFile.focus); + const focus = @backingInt(tree.TopFile.focus); var line: [16]u8 = undefined; try testing.expectEqualStrings(try std.fmt.bufPrint(&line, "{d}\n", .{second}), rd(p, focus, 0, 64).bytes); try testing.expectEqual(@as(u64, rd(p, focus, 0, 64).bytes.len), call(p, .{ .tag = 1, .op = .getattr, .node = focus }).reply.attr.size); @@ -1447,7 +1447,7 @@ test "the root ctl reads the settings as a write takes them, and takes the sessi const gpa = testing.allocator; const p = try withFile(gpa, "x\n"); defer p.deinit(); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); const first = rd(p, root_ctl, 0, 1 << 16); try testing.expectEqual(Status.ok, first.reply.status); const settings = try gpa.dupe(u8, first.bytes); @@ -1575,7 +1575,7 @@ test "a write of an Edit block carries it whole, to a pane's ctl, the root's ctl try testing.expectEqual(Status.ok, wr(p, Node.of(serial, .ctl), "Edit ,x/foo/{\ni/[/\na/]/\n}\n").reply.status); try testing.expectEqualStrings("[foo] x\n[foo] y\n", rd(p, body, 0, 64).bytes); p.active = p.paneBySerial(serial).?; - try testing.expectEqual(Status.ok, wr(p, @intFromEnum(tree.TopFile.ctl), "Edit ,x/\\[/{\nc/ 0); - try testing.expectEqual(@as(u64, 0), call(p, .{ .tag = 1, .op = .getattr, .node = @intFromEnum(tree.TopFile.index) }).reply.attr.size); + try testing.expectEqual(@as(u64, 0), call(p, .{ .tag = 1, .op = .getattr, .node = @backingInt(tree.TopFile.index) }).reply.attr.size); // Its tag never carries the raw newline either. const tag = rd(p, Node.of(serialOf(p), .tag), 0, 4096).bytes; try testing.expect(std.mem.indexOf(u8, tag, "/tmp/two\\nlines") != null); // A backslash of the name's own is doubled: `\n` written in a name // reads back unlike a newline. p.setCwd(term, "/tmp/back\\nslash"); - try testing.expect(std.mem.indexOf(u8, rd(p, @intFromEnum(tree.TopFile.index), 0, 4096).bytes, "/tmp/back\\\\nslash") != null); + try testing.expect(std.mem.indexOf(u8, rd(p, @backingInt(tree.TopFile.index), 0, 4096).bytes, "/tmp/back\\\\nslash") != null); } test "a look at a ./ or ../ name that is not there is a miss naming the file; a plain one is looked for as text" { @@ -3766,7 +3766,7 @@ test "a served-tree pane spoils no Grep, and Look . from a gone directory is ENO test "a tag write refuses NUL and the other control characters" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - for ([_]u64{ @intFromEnum(tree.TopFile.tag), tree.Node.ofCol(pardes.layout.columnSerial(p, 0), .tag), Node.of(serialOf(p), .tag) }) |node| { + for ([_]u64{ @backingInt(tree.TopFile.tag), tree.Node.ofCol(pardes.layout.columnSerial(p, 0), .tag), Node.of(serialOf(p), .tag) }) |node| { const refused = wr(p, node, " a\x00b"); try testing.expectEqual(E.INVAL, refused.errno()); try testing.expectStringStartsWith(refused.reply.ename, "invalid tag text"); @@ -3815,7 +3815,7 @@ test "a column takes panes until their documented minimums fill it, not until no const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 }); defer p.deinit(); while (p.nextEffect()) |_| {} - const new = @intFromEnum(tree.TopFile.new); + const new = @backingInt(tree.TopFile.new); while (call(p, .{ .tag = 1, .op = .open, .node = new }).reply.status == .ok) p.sync(); p.sync(); const avail = p.screen_h - (p.topBarHeight() + p.columnBarHeight()); @@ -3913,13 +3913,13 @@ test "a closed file is found again: Recent and /recent list it closed, a look at const opened = p.active; try testing.expectEqualStrings(a, p.panes[opened].?.file.?.path); var want: [4300]u8 = undefined; - try testing.expect(std.mem.indexOf(u8, rd(p, @intFromEnum(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "open {s}\n", .{a})) != null); + try testing.expect(std.mem.indexOf(u8, rd(p, @backingInt(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "open {s}\n", .{a})) != null); // Another file, so the jumplist has somewhere to come back from. try testing.expectEqual(Status.ok, wr(p, root_look, try std.fmt.bufPrint(&line, "{s}/b.txt\n", .{dir})).reply.status); p.sync(); try testing.expectEqual(Status.ok, wr(p, Node.of(p.panes[opened].?.serial, .ctl), "Del\n").reply.status); p.sync(); - try testing.expect(std.mem.indexOf(u8, rd(p, @intFromEnum(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "closed {s}\n", .{a})) != null); + try testing.expect(std.mem.indexOf(u8, rd(p, @backingInt(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "closed {s}\n", .{a})) != null); // Recent lists it, closed, at its dot; a look at the row opens it there. try testing.expectEqual(Status.ok, wr(p, root_exec, "Recent\n").reply.status); const rows = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; @@ -4045,8 +4045,8 @@ test "Back and Forward written to exec keep to the focused file, and JumpScope a .{ .word = "Forward", .file = "/b.txt", .line = 80 }, .{ .word = "Forward", .file = "/a.txt", .line = 80 }, }); - try testing.expectEqual(Status.ok, wr(p, @intFromEnum(tree.TopFile.ctl), "JumpScope all\n").reply.status); - try testing.expect(std.mem.indexOf(u8, rd(p, @intFromEnum(tree.TopFile.ctl), 0, 8192).bytes, "JumpScope all\n") != null); + try testing.expectEqual(Status.ok, wr(p, @backingInt(tree.TopFile.ctl), "JumpScope all\n").reply.status); + try testing.expect(std.mem.indexOf(u8, rd(p, @backingInt(tree.TopFile.ctl), 0, 8192).bytes, "JumpScope all\n") != null); try walk(p, &.{ .{ .word = "Back", .file = "/b.txt", .line = 80 }, .{ .word = "Back", .file = "/a.txt", .line = 40 }, @@ -4102,14 +4102,14 @@ test "a new file saved shows in /recent, open, while it is" { try testing.expectEqual(Status.ok, wr(p, Node.of(made, .ctl), "Save\n").reply.status); p.perform(.{ .save_file = .{ .pane = @intCast(p.paneBySerial(made).?) } }); var want: [4300]u8 = undefined; - try testing.expect(std.mem.indexOf(u8, rd(p, @intFromEnum(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "open {s}\n", .{path})) != null); + try testing.expect(std.mem.indexOf(u8, rd(p, @backingInt(tree.TopFile.recent), 0, 8192).bytes, try std.fmt.bufPrint(&want, "open {s}\n", .{path})) != null); } test "/recent shows a name as /index does, a newline in it escaped" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); p.recent.opened(p.recentGpa(), "/tmp/a\nb\\c"); - const text = rd(p, @intFromEnum(tree.TopFile.recent), 0, 8192).bytes; + const text = rd(p, @backingInt(tree.TopFile.recent), 0, 8192).bytes; try testing.expect(std.mem.indexOf(u8, text, "closed /tmp/a\\nb\\\\c\n") != null); } @@ -4191,8 +4191,8 @@ test "size is monotonic: growing is never refused, and a size once taken is take defer p.deinit(); while (p.nextEffect()) |_| {} p.unattended = true; - const root_ctl = @intFromEnum(tree.TopFile.ctl); - const new = @intFromEnum(tree.TopFile.new); + const root_ctl = @backingInt(tree.TopFile.ctl); + const new = @backingInt(tree.TopFile.new); // The dogfood's repro: Newcol, three pane/new, a Tty, then pane/new // until a column has no room (ENOSPC). try testing.expectEqual(Status.ok, wr(p, root_ctl, "Newcol\n").reply.status); @@ -4283,7 +4283,7 @@ test "a file changed on disk under unsaved edits is not reloaded: it says so, ge var want: [32]u8 = undefined; try testing.expect(th.logHas(p, try std.fmt.bufPrint(&want, "changed {d}\n", .{serial}))); // Exit and get still ask about the edits. - try testing.expectEqual(Status.err, wr(p, @intFromEnum(tree.TopFile.ctl), "Exit\n").reply.status); + try testing.expectEqual(Status.err, wr(p, @backingInt(tree.TopFile.ctl), "Exit\n").reply.status); try testing.expect(std.mem.indexOf(u8, wr(p, Node.of(serial, .ctl), "get\n").reply.ename, "Modified") != null); // Save warns once before overwriting the newer file, then writes. const first = wr(p, Node.of(serial, .ctl), "Save\n"); @@ -4328,7 +4328,7 @@ test "a looked word is found in its own pane, next place after the dot, wrapping test "every word's /commands description is its own doc comment's first sentence, no citation" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const listed = rd(p, @intFromEnum(tree.TopFile.commands), 0, 1 << 16).bytes; + const listed = rd(p, @backingInt(tree.TopFile.commands), 0, 1 << 16).bytes; for ([_][]const u8{ "\nRepl arg pane -- Binds this terminal as a language's REPL, so an exec on that language's files is typed into it instead of run.\n", "\nJoincol root -- Fold the active pane's column into the one on its right, keeping its panes.\n", @@ -4374,7 +4374,7 @@ test "Newcol at the column cap fails the write and says the cap" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); p.update(.{ .resize = .{ .cols = 4000, .rows = 30 } }); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); while (p.ncol < pardes.MAX_COLS) { // From the widest column's tag, so no column gets too narrow first. p.sync(); @@ -4403,7 +4403,7 @@ test "Save on a terminal asked over 9P is an ask in the log, answered with a pat try testing.expect(p.panes[id].?.prompt == .save); // Again: the one open stands, one ask in the log. _ = wr(p, Node.of(serial, .tagexec), "Save\n"); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; try testing.expectEqual(@as(usize, 1), std.mem.count(u8, call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes, "save path\n")); _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h }); @@ -4429,7 +4429,7 @@ test "get names the path it could not read, logs the edits it threw away, and a pardes.panes.File.deleted(p, 0); pardes.panes.File.deleted(p, 0); var rec: [32]u8 = undefined; - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; try testing.expectEqual(@as(usize, 1), std.mem.count(u8, call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes, try std.fmt.bufPrint(&rec, "changed {d} deleted\n", .{serial}))); _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h }); @@ -4441,12 +4441,12 @@ test "a builtin that fails through exec, tagexec or a column's exec fails the wr p.update(.tick); // the pane's `new` is logged first while (p.nextEffect()) |_| {} const serial = serialOf(p); - for ([_]u64{ root_exec, Node.of(serial, .exec), @intFromEnum(tree.TopFile.tagexec), Node.ofCol(pardes.layout.columnSerial(p, 0), .exec) }) |node| { + for ([_]u64{ root_exec, Node.of(serial, .exec), @backingInt(tree.TopFile.tagexec), Node.ofCol(pardes.layout.columnSerial(p, 0), .exec) }) |node| { const failed = wr(p, node, "Unmount zzz\n"); try testing.expectEqual(Status.err, failed.reply.status); try testing.expect(std.mem.indexOf(u8, failed.reply.ename, "Unmount: no such mount zzz") != null); } - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; const text = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes; try testing.expect(std.mem.indexOf(u8, text, "msg ") == null); @@ -4458,11 +4458,11 @@ test "a builtin that fails through exec, tagexec or a column's exec fails the wr // A control character is refused with its reason. try testing.expectEqualStrings(e_control, wr(p, root_exec, "Msg a\x01b\n").reply.ename); // A look miss: one err, no msg. - _ = wr(p, @intFromEnum(tree.TopFile.look), "zzqqnotthere\n"); + _ = wr(p, @backingInt(tree.TopFile.look), "zzqqnotthere\n"); try testing.expect(th.logHas(p, "look: no match for \"zzqqnotthere\"")); try testing.expect(!th.logHas(p, "msg 1 Look: no match")); // The same miss again is that record counted, as any repeated err is. - _ = wr(p, @intFromEnum(tree.TopFile.look), "zzqqnotthere\n"); + _ = wr(p, @backingInt(tree.TopFile.look), "zzqqnotthere\n"); try testing.expect(th.logHas(p, "look: no match for \"zzqqnotthere\" (x2)\n")); } @@ -4483,7 +4483,7 @@ test "@p:
takes any sam address; a miss and an unknown serial a const p = try withFile(testing.allocator, "foo x foo y\nbar\n"); defer p.deinit(); const serial = serialOf(p); - const root = @intFromEnum(tree.TopFile.look); + const root = @backingInt(tree.TopFile.look); const dot = Node.of(serial, .dot); const Case = struct { addr: []const u8, want: []const u8 }; for ([_]Case{ @@ -4544,7 +4544,7 @@ test "@p:
takes any address over the terminal's lines, select const id = p.paneBySerial(serial).?; p.update(.{ .output = .{ .pane = @intCast(id), .bytes = "one\r\ntwo MARK three\r\n" } }); const pane = p.panes[id].?; - const root = @intFromEnum(tree.TopFile.look); + const root = @backingInt(tree.TopFile.look); var line: [64]u8 = undefined; try testing.expectEqual(Status.ok, wr(p, root, try std.fmt.bufPrint(&line, "@p{d}:0/MARK/\n", .{serial})).reply.status); try testing.expectEqual(@as(i32, 1), pane.body.cur_row); @@ -4576,7 +4576,7 @@ test "a bad command inside an Edit block written whole is named, not the } after test "a refused Delcol changes nothing: no pane, no focus" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - _ = wr(p, @intFromEnum(tree.TopFile.ctl), "Newcol\n"); + _ = wr(p, @backingInt(tree.TopFile.ctl), "Newcol\n"); const made = try th.newPane(p); _ = wr(p, Node.of(made, .name), "/tmp/pardes-delcol-refused.txt\n"); _ = wr(p, Node.of(made, .body), "edit\n"); @@ -4599,8 +4599,8 @@ test "a refused Delcol changes nothing: no pane, no focus" { test "pager answers its +Pager on the open that asked, whatever another client exec'd meanwhile" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const pager = @intFromEnum(tree.TopFile.pager); - const exec = @intFromEnum(tree.TopFile.exec); + const pager = @backingInt(tree.TopFile.pager); + const exec = @backingInt(tree.TopFile.exec); const asked = call(p, .{ .tag = 1, .op = .open, .node = pager, .omode = 2 }).reply.handle; try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = pager, .handle = asked, .data = "/tmp\n" }).reply.status); const paged = for (p.panes) |slot| { @@ -4653,7 +4653,7 @@ test "pager answers its +Pager on the open that asked, whatever another client e test "what a /pager open writes after its directory is the text: plain in the body, its colours the pane's, clean, in by the read" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const pager = @intFromEnum(tree.TopFile.pager); + const pager = @backingInt(tree.TopFile.pager); const asked = call(p, .{ .tag = 1, .op = .open, .node = pager, .omode = 2 }).reply.handle; // The directory and the text's start in one write, escapes and all, a // second line no directory; the rest in writes after it. @@ -4812,7 +4812,7 @@ test "a second LookWord list look in a directory refills its +Search rather than const path = try std.fmt.bufPrint(&path_buf, "{s}/words.txt", .{dir}); const p = try Pardes.init(gpa, .{ .file = path, .tty_only = true, .cols = 80, .rows = 30 }); defer p.deinit(); - _ = wr(p, @intFromEnum(tree.TopFile.ctl), "LookWord list\n"); + _ = wr(p, @backingInt(tree.TopFile.ctl), "LookWord list\n"); pardes.look.lookAt(p, 0, "alpha"); pardes.look.lookAt(p, 0, "beta"); var searches: usize = 0; @@ -4986,7 +4986,7 @@ test "DumpDir refuses a relative directory and one that may not be written, up f if (comptime !pardes.hosted) return; const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const root_ctl = @intFromEnum(tree.TopFile.ctl); + const root_ctl = @backingInt(tree.TopFile.ctl); try testing.expectEqual(E.INVAL, wr(p, root_ctl, "DumpDir dumps\n").errno()); try testing.expectEqual(E.INVAL, wr(p, root_ctl, "DumpDir /proc/1/root/dumps\n").errno()); try testing.expectEqual(Status.ok, wr(p, root_ctl, "DumpDir /tmp/pardes-dumps-test\n").reply.status); @@ -4998,7 +4998,7 @@ test "DumpDir refuses a relative directory and one that may not be written, up f test "a Mount dial with a network it does not know is a bad dial address, EINVAL" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const r = wr(p, @intFromEnum(tree.TopFile.ctl), "Mount peer nowhere!x\n"); + const r = wr(p, @backingInt(tree.TopFile.ctl), "Mount peer nowhere!x\n"); try testing.expectEqual(E.INVAL, r.errno()); try testing.expectStringStartsWith(r.reply.ename, "Mount: bad dial address: nowhere!x"); } @@ -5056,11 +5056,11 @@ test "a Mount of a socket path that is not there says no such socket, ENOENT" { if (comptime !pardes.hosted) return; const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const r = wr(p, @intFromEnum(tree.TopFile.ctl), "Mount peer unix!/tmp/pardes-surely-no-socket\n"); + const r = wr(p, @backingInt(tree.TopFile.ctl), "Mount peer unix!/tmp/pardes-surely-no-socket\n"); try testing.expectEqual(E.NOENT, r.errno()); try testing.expect(std.mem.indexOf(u8, r.reply.ename, "no such socket") != null); try testing.expectEqual(@as(usize, 0), p.fs.mounts.items.len); - try testing.expectEqual(E.INVAL, wr(p, @intFromEnum(tree.TopFile.ctl), "Mount peer rel/x.sock\n").errno()); + try testing.expectEqual(E.INVAL, wr(p, @backingInt(tree.TopFile.ctl), "Mount peer rel/x.sock\n").errno()); } test "the init file reads past a BOM, and every line it fails is a notice and an err, never silent" { diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 7b73dc0e..78788c3c 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -542,7 +542,7 @@ pub const Action = enum(u8) { tag_exec = 'x', pub fn char(a: Action) u8 { - return @intFromEnum(a); + return @backingInt(a); } pub fn fromChar(c: u8) ?Action { @@ -550,7 +550,7 @@ pub const Action = enum(u8) { } pub fn onTag(a: Action) bool { - return @intFromEnum(a) >= 'a'; + return @backingInt(a) >= 'a'; } }; @@ -889,7 +889,7 @@ test "a stream read at an offset inside its last answer gets the rest of it agai defer p.deinit(); p.update(.tick); while (p.nextEffect()) |_| {} - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const f = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; const frozen: u64 = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = f, .size = 8192 }).bytes.len; _ = call(p, .{ .tag = 3, .op = .write, .node = log, .handle = f, .data = "follow" }); @@ -897,7 +897,7 @@ test "a stream read at an offset inside its last answer gets the rest of it agai notePath(p, "dump", "/b"); const Read = struct { fn at(pp: *Pardes, h: u32, off: u64) []const u8 { - return call(pp, .{ .tag = 4, .op = .read, .node = @intFromEnum(tree.TopFile.log), .handle = h, .off = off, .size = 128 }).bytes; + return call(pp, .{ .tag = 4, .op = .read, .node = @backingInt(tree.TopFile.log), .handle = h, .off = off, .size = 128 }).bytes; } }; try testing.expectEqualStrings("dump /a\n", Read.at(p, f, frozen)); @@ -1130,7 +1130,7 @@ test "writing an event record back performs the action it names" { // A look written back sets what look reads back. _ = wr(p, event, "FL0 3\n"); var want_serial: [16]u8 = undefined; - try testing.expectEqualStrings(try std.fmt.bufPrint(&want_serial, "{d}\n", .{serial}), rd(p, @intFromEnum(tree.TopFile.look), 0, 64).bytes); + try testing.expectEqualStrings(try std.fmt.bufPrint(&want_serial, "{d}\n", .{serial}), rd(p, @backingInt(tree.TopFile.look), 0, 64).bytes); // Well formed but past the text: said so, not "bad event syntax". try testing.expectEqualStrings("range past end of body", wr(p, event, "MX0 999\n").reply.ename); @@ -1144,7 +1144,7 @@ test "the log records whether or not anyone reads, and an open that follows wait const gpa = testing.allocator; const p = try withFile(gpa, "logged\n"); defer p.deinit(); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); var expected: [4200]u8 = undefined; // Nobody holds /log open, and the pane is recorded anyway. @@ -1256,21 +1256,21 @@ test "a refused or failed write is an err record in the log, saying which file a p.update(.tick); // the pane's `new` is logged before the log is opened while (p.nextEffect()) |_| {} const serial = serialOf(p); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const f = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; const frozen = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = f, .size = 1 << 16 }).bytes.len; _ = call(p, .{ .tag = 3, .op = .write, .node = log, .handle = f, .data = "follow" }); var want: [128]u8 = undefined; const next = struct { fn record(pp: *Pardes, h: u32, off: usize) []const u8 { - return call(pp, .{ .tag = 4, .op = .read, .node = @intFromEnum(tree.TopFile.log), .handle = h, .off = off, .size = 4096 }).bytes; + return call(pp, .{ .tag = 4, .op = .read, .node = @backingInt(tree.TopFile.log), .handle = h, .off = off, .size = 4096 }).bytes; } }; _ = wr(p, Node.of(serial, .addr), "/nowhere/"); try testing.expectEqualStrings(try std.fmt.bufPrint(&want, "err {d} addr: no match for regexp\n", .{serial}), next.record(p, f, frozen)); - _ = wr(p, @intFromEnum(tree.TopFile.ctl), "Bogus"); + _ = wr(p, @backingInt(tree.TopFile.ctl), "Bogus"); try testing.expectEqualStrings("err - ctl: unknown control message \"Bogus\"\n", next.record(p, f, frozen)); - _ = wr(p, @intFromEnum(tree.TopFile.focus), "99999"); + _ = wr(p, @backingInt(tree.TopFile.focus), "99999"); try testing.expectEqualStrings("err - focus: no such pane\n", next.record(p, f, frozen)); // A write that succeeds says nothing. _ = wr(p, Node.of(serial, .addr), "#0"); @@ -1373,7 +1373,7 @@ test "opens of the log share the open records, and a closed one frees its record const gpa = testing.allocator; const p = try withFile(gpa, "x\n"); defer p.deinit(); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); var handles: [tree.open_slots]u32 = undefined; for (&handles) |*h| h.* = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; try testing.expectEqual(E.NFILE, call(p, .{ .tag = 2, .op = .open, .node = log }).errno()); @@ -1447,7 +1447,7 @@ test "follow new skips what the log held and waits for what comes after" { p.update(.tick); // the pane's `new` is logged first while (p.nextEffect()) |_| {} p.setMessage(0, "before the open"); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = log, .handle = h, .data = "follow new\n" }).reply.status); try testing.expectEqual(Status.again, call(p, .{ .tag = 3, .op = .read, .node = log, .handle = h, .size = 4096 }).reply.status); @@ -1461,7 +1461,7 @@ test "a long msg record is cut between words at its cap, with an ellipsis" { defer p.deinit(); const long = std.mem.asBytes(&@as([60][5]u8, @splat("word ".*))); // 300 bytes _ = wr(p, Node.of(serialOf(p), .ctl), "Msg " ++ long ++ "\n"); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; const text = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes; const at = std.mem.lastIndexOf(u8, text, "msg ").?; @@ -1485,8 +1485,8 @@ test "a record is one line of UTF-8: DEL and C1 are spaces, bytes not UTF-8 are test "a long err record keeps its end, its middle given up to an ellipsis" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - _ = wr(p, @intFromEnum(tree.TopFile.ctl), "Bogus" ++ std.mem.asBytes(&@as([40][8]u8, @splat("abcdefgh".*))) ++ "\n"); - const log = @intFromEnum(tree.TopFile.log); + _ = wr(p, @backingInt(tree.TopFile.ctl), "Bogus" ++ std.mem.asBytes(&@as([40][8]u8, @splat("abcdefgh".*))) ++ "\n"); + const log = @backingInt(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; const text = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes; const at = std.mem.lastIndexOf(u8, text, "err - ctl: ").?; diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 8605cab8..dc104e4b 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -1104,7 +1104,7 @@ test "index lists serial kind dirty flag and name, and stats 0, a view generated const p = try withFile(gpa, "hello\nthere\n"); defer p.deinit(); const pane = p.panes[0].?; - const index = @intFromEnum(tree.TopFile.index); + const index = @backingInt(tree.TopFile.index); const a = rd(p, index, 0, 4096); try testing.expectEqual(Status.ok, a.reply.status); @@ -1138,7 +1138,7 @@ test "a terminal is listed as term with its directory as name" { var want: [64]u8 = undefined; try testing.expect(std.mem.indexOf( u8, - rd(p, @intFromEnum(tree.TopFile.index), 0, 4096).bytes, + rd(p, @backingInt(tree.TopFile.index), 0, 4096).bytes, try std.fmt.bufPrint(&want, "{d} term 0 /work/dir {d}\n", .{ pane.serial, columnOf(p, 0) }), ) != null); try testing.expectEqualStrings("/work/dir\n", rd(p, Node.of(pane.serial, .name), 0, 4096).bytes); @@ -1751,8 +1751,8 @@ test "name refreshes cached syntax for unchanged contents" { try testing.expectEqual(Status.ok, wr(p, Node.of(pane.serial, .name), "renamed.zig\n").reply.status); panes.File.refreshHighlights(p); try testing.expect(pane.file.?.highlights.len >= 2); - try testing.expectEqual(@intFromEnum(pardes.syntax.Syn.keyword), pane.file.?.highlights[0]); - try testing.expectEqual(@intFromEnum(pardes.syntax.Syn.keyword), pane.file.?.highlights[1]); + try testing.expectEqual(@backingInt(pardes.syntax.Syn.keyword), pane.file.?.highlights[0]); + try testing.expectEqual(@backingInt(pardes.syntax.Syn.keyword), pane.file.?.highlights[1]); try testing.expectEqualStrings("fn check() void {}\n", pane.file.?.content); } diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index aeb57a00..d80f7175 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -893,7 +893,7 @@ test "a shell that exits under a run answers its status, and the log says exit b const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; p.update(.{ .output = .{ .pane = 0, .bytes = prompt } }); while (p.nextEffect()) |_| {} - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const f = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; const frozen = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = f, .size = 1 << 16 }).bytes.len; _ = call(p, .{ .tag = 3, .op = .write, .node = log, .handle = f, .data = "follow" }); @@ -984,7 +984,6 @@ test "a run's answer says cut when its output's start is gone, and reads a bound var got = sh.answered(p, node, h, into); try testing.expectEqualStrings("exit 0\nafter\n", got); - // A resize between its start and end reflows the pins with the text. h = sh.send(p, node); sh.put(p, c ++ "one\r\ntwo\r\n"); @@ -1092,7 +1091,7 @@ test "a terminal's ctl counts its body, and a new directory is a rename in the l _ = fields.next(); try testing.expectEqual(body_len, try std.fmt.parseInt(usize, fields.next().?, 10)); - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const f = call(p, .{ .tag = 4, .op = .open, .node = log }).reply.handle; const frozen = call(p, .{ .tag = 5, .op = .read, .node = log, .handle = f, .size = 1 << 16 }).bytes.len; _ = call(p, .{ .tag = 6, .op = .write, .node = log, .handle = f, .data = "follow" }); diff --git a/src/ninep/screen.zig b/src/ninep/screen.zig index 8d4707e0..ba676ded 100644 --- a/src/ninep/screen.zig +++ b/src/ninep/screen.zig @@ -95,7 +95,7 @@ const withTerm = th.withTerm; const serialOf = th.serialOf; const Node = tree.Node; const Status = tree.Status; -const screen_node = @intFromEnum(tree.TopFile.screen); +const screen_node = @backingInt(tree.TopFile.screen); test "listener addresses are readable canonical dials with bounded partial reads" { const gpa = testing.allocator; @@ -111,7 +111,7 @@ test "listener addresses are readable canonical dials with bounded partial reads try testing.expectEqualStrings(expected, bytes); try testing.expectError(error.ReadOnlyFilesystem, fs.write(p, path, "")); } - const node = @intFromEnum(tree.TopFile.listeners); + const node = @backingInt(tree.TopFile.listeners); var off: usize = 0; while (off < expected.len) { const part = rd(p, node, off, 3); diff --git a/src/ninep/testing.zig b/src/ninep/testing.zig index a35a9cf0..ec665130 100644 --- a/src/ninep/testing.zig +++ b/src/ninep/testing.zig @@ -71,7 +71,7 @@ pub fn logHas(p: *Pardes, needle: []const u8) bool { /// How many times the log, read whole from a fresh open, holds `needle`. pub fn logCount(p: *Pardes, needle: []const u8) usize { - const log = @intFromEnum(tree.TopFile.log); + const log = @backingInt(tree.TopFile.log); const h = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; defer _ = call(p, .{ .tag = 3, .op = .release, .node = log, .handle = h }); const text = call(p, .{ .tag = 2, .op = .read, .node = log, .handle = h, .size = 1 << 16 }).bytes; @@ -95,7 +95,7 @@ pub fn look_up(p: *Pardes, dir: u64, name: []const u8) Answer { /// The open is what makes the pane; the handle it answers is the serial, which /// is also what a read of that fid reports. pub fn newPane(p: *Pardes) !u32 { - const made = call(p, .{ .tag = 8, .op = .open, .node = @intFromEnum(tree.TopFile.new) }); + const made = call(p, .{ .tag = 8, .op = .open, .node = @backingInt(tree.TopFile.new) }); if (made.reply.status != .ok or made.reply.handle == 0) return error.NoPane; return made.reply.handle; } diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 5678832b..9aa0225a 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -115,7 +115,7 @@ pub fn changesPane(p: *Pardes, req: Req) bool { return switch (req.op) { .write => true, .setattr => truncates(req), - .open => req.node == @intFromEnum(TopFile.new), + .open => req.node == @backingInt(TopFile.new), .release => req.remove or holdsLines(p, req) or holdsPage(p, req), .read => holdsPage(p, req), .lookup, .getattr, .readdir => false, @@ -279,7 +279,7 @@ pub const TopFile = enum(u5) { } }; -pub const root: u64 = @intFromEnum(TopFile.root); +pub const root: u64 = @backingInt(TopFile.root); /// Declaration order is readdir order. pub const PaneFile = enum(u5) { @@ -363,11 +363,11 @@ pub const Node = packed struct(u64) { pub fn of(serial: u32, file: PaneFile) u64 { std.debug.assert(serial != 0); - return @bitCast(Node{ .file = @intFromEnum(file), .serial = serial }); + return @bitCast(Node{ .file = @backingInt(file), .serial = serial }); } pub fn ofCol(serial: u32, file: ColFile) u64 { - return @bitCast(Node{ .file = @intFromEnum(file), .serial = col_bit | @as(u59, serial) }); + return @bitCast(Node{ .file = @backingInt(file), .serial = col_bit | @as(u59, serial) }); } pub fn target(node: u64) ?Target { @@ -424,9 +424,9 @@ pub fn resolveSelf(p: *Pardes, path: []const u8) ?u64 { // `new` is reached in /pane, where the panes it makes are. const top = std.meta.stringToEnum(TopFile, first) orelse return sources.node(normalized); if (top == .root or top == .new or top == .pane or parts.next() != null) return null; - return @intFromEnum(top); + return @backingInt(top); } - const next = parts.next() orelse return @intFromEnum(TopFile.pane); + const next = parts.next() orelse return @backingInt(TopFile.pane); // `new` is served on the wire but deliberately unreachable from an editor // path: this resolves Look targets and hover previews, and a preview that // opened `new` to see what was there would make a pane per hover. @@ -606,7 +606,7 @@ fn attrOf(p: *Pardes, target: Target) ?Reply.Attr { switch (target) { .top => |f| return .{ .name = f.fileName(), - .node = @intFromEnum(f), + .node = @backingInt(f), .dir = f.dir(), .mode = f.mode(), .size = topSize(p, f), @@ -695,11 +695,11 @@ fn lookup(p: *Pardes, req: Req, target: Target) Reply { const parent: u64 = switch (target) { .top => |top| if (top.dir()) root else return Reply.fail(req.tag, E.NOTDIR), .pane => |t| switch (t.file) { - .dir => @intFromEnum(TopFile.pane), + .dir => @backingInt(TopFile.pane), .pty => Node.of(t.serial, .dir), else => return Reply.fail(req.tag, E.NOTDIR), }, - .col => |c| if (c.file == .dir) @intFromEnum(TopFile.col) else return Reply.fail(req.tag, E.NOTDIR), + .col => |c| if (c.file == .dir) @backingInt(TopFile.col) else return Reply.fail(req.tag, E.NOTDIR), }; return handle(p, .{ .tag = req.tag, .op = .getattr, .node = parent }); } @@ -709,12 +709,12 @@ fn lookup(p: *Pardes, req: Req, target: Target) Reply { .root => root: { if (std.mem.eql(u8, name, "os")) return fs.osHandle(p, .{ .tag = req.tag, .op = .getattr, .node = fs.os_root }); // `new` is reached in /pane, where the panes it makes are. - if (std.meta.stringToEnum(TopFile, name)) |t| if (t != .root and t != .new) break :root @intFromEnum(t); + if (std.meta.stringToEnum(TopFile, name)) |t| if (t != .root and t != .new) break :root @backingInt(t); if (sources.node(name)) |n| return sources.handle(p, .{ .tag = req.tag, .op = .getattr, .node = n }); return Reply.fail(req.tag, E.NOENT); }, .pane => pane: { - if (std.mem.eql(u8, name, new_pane)) break :pane @intFromEnum(TopFile.new); + if (std.mem.eql(u8, name, new_pane)) break :pane @backingInt(TopFile.new); // A pane directory is its serial, in decimal digits and never 0. if (name.len > 10) return Reply.fail(req.tag, E.NOENT); for (name) |c| if (c < '0' or c > '9') return Reply.fail(req.tag, E.NOENT); @@ -778,13 +778,13 @@ fn readdir(p: *Pardes, req: Req, target: Target) Reply { // The guide, then what describes the session, then the // files that act, then the directories. inline for (.{ TopFile.README, TopFile.index, TopFile.status, TopFile.focus, TopFile.ctl, TopFile.commands, TopFile.recent, TopFile.look, TopFile.exec, TopFile.pager, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.layout, TopFile.tag, TopFile.tagexec, TopFile.pane, TopFile.col }) |t| { - if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(t), t.dir(), t.fileName()); + if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @backingInt(t), t.dir(), t.fileName()); } if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, fs.os_root, true, "os"); sources.stage(p, out, "", &skip); }, .pane => { - if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @intFromEnum(TopFile.new), false, TopFile.new.fileName()); + if (skip > 0) skip -= 1 else stageDirent(out, p.gpa, @backingInt(TopFile.new), false, TopFile.new.fileName()); var last: u32 = 0; while (nextSerialAfter(p, last)) |serial| { last = serial; @@ -1378,7 +1378,7 @@ test "a listing read in chunks is what it was at the open, however the panes cha const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); for ([_]TopFile{ .index, .layout, .recent, .ctl }) |file| { - const node = @intFromEnum(file); + const node = @backingInt(file); const whole = try testing.allocator.dupe(u8, th.rd(p, node, 0, 1 << 16).bytes); defer testing.allocator.free(whole); const h = th.call(p, .{ .tag = 1, .op = .open, .node = node }).reply.handle; @@ -1389,7 +1389,7 @@ test "a listing read in chunks is what it was at the open, however the panes cha // Something changes between the chunks. const made = try th.newPane(p); _ = th.wr(p, Node.of(made, .name), "/tmp/pardes-frozen-listing.txt\n"); - _ = th.wr(p, @intFromEnum(TopFile.ctl), "Verbose off\n"); + _ = th.wr(p, @backingInt(TopFile.ctl), "Verbose off\n"); while (true) { const more = th.call(p, .{ .tag = 2, .op = .read, .node = node, .handle = h, .off = got.items.len, .size = 7 }).bytes; if (more.len == 0) break; @@ -1397,7 +1397,7 @@ test "a listing read in chunks is what it was at the open, however the panes cha } _ = th.call(p, .{ .tag = 3, .op = .release, .node = node, .handle = h, .opened = true }); try testing.expectEqualStrings(whole, got.items); - _ = th.wr(p, @intFromEnum(TopFile.ctl), "Verbose on\n"); + _ = th.wr(p, @backingInt(TopFile.ctl), "Verbose on\n"); } } @@ -1418,7 +1418,7 @@ test "filesystem inspection preserves pending and displayed Look hover" { } }); try testing.expect(p.look_hover_wait != null); const body = Node.of(serialOf(p), .body); - const screen_node = @intFromEnum(TopFile.screen); + const screen_node = @backingInt(TopFile.screen); for (0..2) |phase| { if (phase == 1) { for (0..delay) |_| p.update(.tick); @@ -1429,7 +1429,7 @@ test "filesystem inspection preserves pending and displayed Look hover" { const requests = [_]Req{ .{ .tag = 1, .op = .lookup, .node = root, .data = "screen" }, .{ .tag = 1, .op = .lookup, .node = root, .data = "status" }, - .{ .tag = 1, .op = .getattr, .node = @intFromEnum(TopFile.pane) }, + .{ .tag = 1, .op = .getattr, .node = @backingInt(TopFile.pane) }, .{ .tag = 2, .op = .getattr, .node = body }, .{ .tag = 3, .op = .open, .node = body }, .{ .tag = 4, .op = .read, .node = body, .size = 5 }, @@ -1458,14 +1458,14 @@ test "log stats 0 however much it holds, a stream as acme's generated files are" defer p.deinit(); _ = th.wr(p, Node.of(th.serialOf(p), .exec), "Msg a record for the log\n"); try testing.expect(th.logHas(p, "a record for the log")); - try testing.expectEqual(@as(u64, 0), call(p, .{ .tag = 1, .op = .getattr, .node = @intFromEnum(TopFile.log) }).reply.attr.size); + try testing.expectEqual(@as(u64, 0), call(p, .{ .tag = 1, .op = .getattr, .node = @backingInt(TopFile.log) }).reply.attr.size); } test "filesystem pane creation and truncation cancel Look hover" { const requests = [_]Req{ // Opening `new` is what makes a pane now; walking to it makes none, // and so must leave a pending hover alone. - .{ .tag = 2, .op = .open, .node = @intFromEnum(TopFile.new) }, + .{ .tag = 2, .op = .open, .node = @backingInt(TopFile.new) }, .{ .tag = 3, .op = .setattr, .node = 0, .truncate = true }, }; for (requests) |request| { @@ -1493,16 +1493,16 @@ test "README names every file the tree serves" { } }; inline for (@typeInfo(TopFile).@"enum".field_values) |value| { - const t: TopFile = @enumFromInt(value); + const t: TopFile = @fromBackingInt(@intCast(value)); if (t != .root and !words.has(t.fileName())) { std.debug.print("README does not mention /{s}\n", .{t.fileName()}); return error.Undocumented; } } inline for (@typeInfo(PaneFile).@"enum".field_values) |value| { - const t: PaneFile = @enumFromInt(value); + const t: PaneFile = @fromBackingInt(@intCast(value)); const ok = if (t == .dir) true else if (t.inPty() and t != .pty) - std.mem.indexOf(u8, fs.help, "pty/" ++ comptime @as(PaneFile, @enumFromInt(value)).fileName()) != null + std.mem.indexOf(u8, fs.help, "pty/" ++ comptime @as(PaneFile, @fromBackingInt(@intCast(value))).fileName()) != null else words.has(t.fileName()); if (!ok) { @@ -1530,8 +1530,8 @@ test "readdir lists the root and a pane directory without creating anything" { try testing.expectEqualStrings(name, top[i].name); try testing.expectEqual(i >= 16, top[i].dir); } - try testing.expectEqual(@intFromEnum(TopFile.pane), top[16].node); - try testing.expectEqual(@intFromEnum(TopFile.col), top[17].node); + try testing.expectEqual(@backingInt(TopFile.pane), top[16].node); + try testing.expectEqual(@backingInt(TopFile.col), top[17].node); try testing.expectEqual(fs.os_root, top[18].node); var idbuf: [16]u8 = undefined; try testing.expect(th.nameAt(top, try std.fmt.bufPrint(&idbuf, "{d}", .{serial})) == null); @@ -1554,7 +1554,7 @@ test "readdir lists the root and a pane directory without creating anything" { try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = entry.node }).reply.status); try testing.expectEqual(before, p.next_serial); } - const panes_dir = rdir(p, @intFromEnum(TopFile.pane), 0); + const panes_dir = rdir(p, @backingInt(TopFile.pane), 0); const listed = th.dirents(panes_dir.bytes, &buf); var idname: [16]u8 = undefined; const own = th.nameAt(listed, try std.fmt.bufPrint(&idname, "{d}", .{serial})).?; @@ -1565,16 +1565,16 @@ test "readdir lists the root and a pane directory without creating anything" { // client that stats every name a listing gave it inert. const shown = th.nameAt(listed, new_pane).?; try testing.expect(!shown.dir); - try testing.expectEqual(Status.ok, look_up(p, @intFromEnum(TopFile.pane), new_pane).reply.status); - try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = @intFromEnum(TopFile.new) }).reply.status); + try testing.expectEqual(Status.ok, look_up(p, @backingInt(TopFile.pane), new_pane).reply.status); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = @backingInt(TopFile.new) }).reply.status); try testing.expectEqual(before, p.next_serial); const dir = rdir(p, Node.of(serial, .dir), 0); const files = th.dirents(dir.bytes, &buf); try testing.expectEqual(@as(usize, 18), files.len); for ([_][]const u8{ - "name", "body", "tag", "ctl", "addr", "dot", "limit", "data", "xdata", - "sel", "dirty", "mark", "scroll", "errors", "event", "look", "exec", "tagexec", + "name", "body", "tag", "ctl", "addr", "dot", "limit", "data", "xdata", + "sel", "dirty", "mark", "scroll", "errors", "event", "look", "exec", "tagexec", }, 0..) |name, i| try testing.expectEqualStrings(name, files[i].name); try testing.expect(th.nameAt(files, ".") == null); @@ -1588,7 +1588,7 @@ test "readdir lists the root and a pane directory without creating anything" { try testing.expectEqual(before, p.next_serial); try testing.expectEqual(E.NOTDIR, rdir(p, Node.of(serial, .body), 0).errno()); - try testing.expectEqual(E.NOTDIR, rdir(p, @intFromEnum(TopFile.index), 0).errno()); + try testing.expectEqual(E.NOTDIR, rdir(p, @backingInt(TopFile.index), 0).errno()); } test "lookup resolves top files, pane serials and pane files" { @@ -1597,7 +1597,7 @@ test "lookup resolves top files, pane serials and pane files" { defer p.deinit(); const serial = serialOf(p); - try testing.expectEqual(@as(u64, @intFromEnum(TopFile.index)), look_up(p, root, "index").reply.attr.node); + try testing.expectEqual(@as(u64, @backingInt(TopFile.index)), look_up(p, root, "index").reply.attr.node); try testing.expect(!look_up(p, root, "status").reply.attr.dir); try testing.expectEqual(@as(u16, 0o444), look_up(p, root, "status").reply.attr.mode); try testing.expectEqual(@as(u16, 0o666), look_up(p, root, "look").reply.attr.mode); @@ -1607,17 +1607,17 @@ test "lookup resolves top files, pane serials and pane files" { try testing.expectEqual(E.NOENT, look_up(p, root, "nosuchthing").errno()); try testing.expectEqual(E.NOENT, look_up(p, root, "self").errno()); try testing.expectEqual(E.NOENT, look_up(p, root, "cons").errno()); - try testing.expectEqual(E.NOTDIR, look_up(p, @intFromEnum(TopFile.index), "x").errno()); + try testing.expectEqual(E.NOTDIR, look_up(p, @backingInt(TopFile.index), "x").errno()); var idbuf: [16]u8 = undefined; const serial_name = try std.fmt.bufPrint(&idbuf, "{d}", .{serial}); try testing.expectEqual(E.NOENT, look_up(p, root, serial_name).errno()); - const dir = look_up(p, @intFromEnum(TopFile.pane), serial_name); + const dir = look_up(p, @backingInt(TopFile.pane), serial_name); try testing.expectEqual(Node.of(serial, .dir), dir.reply.attr.node); try testing.expect(dir.reply.attr.dir); try testing.expectEqualStrings(serial_name, dir.reply.attr.name); - try testing.expectEqual(E.NOENT, look_up(p, @intFromEnum(TopFile.pane), "99999").errno()); - try testing.expectEqual(E.NOENT, look_up(p, @intFromEnum(TopFile.pane), "0").errno()); + try testing.expectEqual(E.NOENT, look_up(p, @backingInt(TopFile.pane), "99999").errno()); + try testing.expectEqual(E.NOENT, look_up(p, @backingInt(TopFile.pane), "0").errno()); const body = look_up(p, Node.of(serial, .dir), "body"); try testing.expectEqual(Node.of(serial, .body), body.reply.attr.node); @@ -1634,19 +1634,19 @@ test "opening /pane/new makes a pane and removing one closes it" { const p = try withFile(gpa, "first\n"); defer p.deinit(); const before = p.next_serial; - const panes_dir = @intFromEnum(TopFile.pane); + const panes_dir = @backingInt(TopFile.pane); // Browsing /pane creates nothing, and neither does walking or stat-ing // `new` itself: only an open does. That is what lets `new` be listed at // all, since `ls -l` stats every name a listing handed it. try testing.expectEqual(Status.ok, rdir(p, panes_dir, 0).reply.status); try testing.expectEqual(Status.ok, look_up(p, panes_dir, new_pane).reply.status); - try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = @intFromEnum(TopFile.new) }).reply.status); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .getattr, .node = @backingInt(TopFile.new) }).reply.status); try testing.expectEqual(before, p.next_serial); // The open makes the pane and hands back its serial; the read only // observes, so two reads of one fid answer the same pane. - const made = call(p, .{ .tag = 2, .op = .open, .node = @intFromEnum(TopFile.new) }); + const made = call(p, .{ .tag = 2, .op = .open, .node = @backingInt(TopFile.new) }); try testing.expectEqual(Status.ok, made.reply.status); try testing.expectEqual(before + 1, p.next_serial); const serial = before + 1; @@ -1654,7 +1654,7 @@ test "opening /pane/new makes a pane and removing one closes it" { var expected: [16]u8 = undefined; const want = try std.fmt.bufPrint(&expected, "{d}\n", .{serial}); for (0..2) |_| { - const answer = call(p, .{ .tag = 3, .op = .read, .node = @intFromEnum(TopFile.new), .handle = made.reply.handle, .size = 64 }); + const answer = call(p, .{ .tag = 3, .op = .read, .node = @backingInt(TopFile.new), .handle = made.reply.handle, .size = 64 }); try testing.expectEqualStrings(want, answer.bytes); } @@ -1668,10 +1668,10 @@ test "opening /pane/new makes a pane and removing one closes it" { // A second open is a second pane, and releasing a clone fid leaves the // pane it made standing. - const second = call(p, .{ .tag = 4, .op = .open, .node = @intFromEnum(TopFile.new) }); + const second = call(p, .{ .tag = 4, .op = .open, .node = @backingInt(TopFile.new) }); try testing.expectEqual(Status.ok, second.reply.status); try testing.expect(second.reply.handle != made.reply.handle); - _ = call(p, .{ .tag = 5, .op = .release, .node = @intFromEnum(TopFile.new), .handle = made.reply.handle, .opened = true }); + _ = call(p, .{ .tag = 5, .op = .release, .node = @backingInt(TopFile.new), .handle = made.reply.handle, .opened = true }); try testing.expect(p.paneBySerial(serial) != null); try testing.expectEqualStrings("hi", p.panes[id].?.file.?.content); @@ -1689,7 +1689,7 @@ test "opening /pane/new makes a pane and removing one closes it" { // Tremove closes the pane it names, and nothing else in the tree. try testing.expectEqual(E.PERM, th.rmdir(p, Node.of(serial, .body)).errno()); - try testing.expectEqual(E.PERM, th.rmdir(p, @intFromEnum(TopFile.index)).errno()); + try testing.expectEqual(E.PERM, th.rmdir(p, @backingInt(TopFile.index)).errno()); try testing.expect(p.paneBySerial(serial) != null); try testing.expectEqual(Status.ok, th.rmdir(p, Node.of(serial, .dir)).reply.status); try testing.expect(p.paneBySerial(serial) == null); @@ -1700,7 +1700,7 @@ test "every open that holds something is one record, named by its handle only on const p = try th.withTerm(testing.allocator); defer p.deinit(); const serial = serialOf(p); - const log = @intFromEnum(TopFile.log); + const log = @backingInt(TopFile.log); const event = Node.of(serial, .event); const run = Node.of(serial, .pty_run); const logged = call(p, .{ .tag = 1, .op = .open, .node = log }).reply.handle; @@ -1729,15 +1729,15 @@ test "directories walk to their parents" { defer p.deinit(); for ([_]struct { node: u64, parent: u64 }{ .{ .node = root, .parent = root }, - .{ .node = @intFromEnum(TopFile.pane), .parent = root }, - .{ .node = Node.of(serialOf(p), .dir), .parent = @intFromEnum(TopFile.pane) }, + .{ .node = @backingInt(TopFile.pane), .parent = root }, + .{ .node = Node.of(serialOf(p), .dir), .parent = @backingInt(TopFile.pane) }, .{ .node = fs.os_root, .parent = root }, }) |case| { const result = look_up(p, case.node, ".."); try testing.expectEqual(Status.ok, result.reply.status); try testing.expectEqual(case.parent, result.reply.attr.node); } - try testing.expectEqual(E.NOTDIR, look_up(p, @intFromEnum(TopFile.index), "..").errno()); + try testing.expectEqual(E.NOTDIR, look_up(p, @backingInt(TopFile.index), "..").errno()); try testing.expectEqual(E.NOTDIR, look_up(p, Node.of(serialOf(p), .body), "..").errno()); } @@ -1748,10 +1748,10 @@ test "editor paths resolve to the same nodes the wire serves" { var path: [64]u8 = undefined; try testing.expectEqual(root, resolveSelf(p, "").?); try testing.expectEqual(root, resolveSelf(p, "/./pane/../").?); - try testing.expectEqual(@intFromEnum(TopFile.index), resolveSelf(p, "index").?); - try testing.expectEqual(@intFromEnum(TopFile.status), resolveSelf(p, "status").?); + try testing.expectEqual(@backingInt(TopFile.index), resolveSelf(p, "index").?); + try testing.expectEqual(@backingInt(TopFile.status), resolveSelf(p, "status").?); try testing.expect(resolveSelf(p, "new") == null); - try testing.expectEqual(@intFromEnum(TopFile.pane), resolveSelf(p, "pane").?); + try testing.expectEqual(@backingInt(TopFile.pane), resolveSelf(p, "pane").?); try testing.expectEqual(Node.of(serial, .dir), resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}", .{serial})).?); try testing.expectEqual(Node.of(serial, .sel), resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}/sel", .{serial})).?); try testing.expect(resolveSelf(p, try std.fmt.bufPrint(&path, "pane/{d}/pty/ctl", .{serial})) == null); @@ -1800,7 +1800,7 @@ test "random placements, refused or not, leave no pane under its tag and two row const action = r.uintLessThan(u8, 8); switch (action) { 0 => _ = th.wr(p, Node.of(at, .exec), "New\n"), - 1 => _ = call(p, .{ .tag = 1, .op = .open, .node = @intFromEnum(TopFile.new) }), + 1 => _ = call(p, .{ .tag = 1, .op = .open, .node = @backingInt(TopFile.new) }), 2 => _ = th.wr(p, Node.of(at, .exec), "Newcol\n"), 3 => _ = th.wr(p, Node.of(at, .exec), "Edit =\n"), 4 => _ = th.wr(p, Node.of(at, .exec), "Tty\n"), @@ -1823,7 +1823,7 @@ test "at the pane cap, pane/new, look and New each say so, and look reads back e // Tall enough that the column holds every pane at its tag and two rows, // and wide enough that each tag, the session directory's +New, is one. p.update(.{ .resize = .{ .cols = 400, .rows = pardes.MAX_PANES * 4 } }); - const new = @intFromEnum(TopFile.new); + const new = @backingInt(TopFile.new); while (p.freeSlot() != null) try testing.expectEqual(Status.ok, call(p, .{ .tag = 1, .op = .open, .node = new }).reply.status); var want: [64]u8 = undefined; const said = try std.fmt.bufPrint(&want, "no space for a pane: {d} max", .{pardes.MAX_PANES}); @@ -1840,7 +1840,7 @@ test "at the pane cap, pane/new, look and New each say so, and look reads back e var dir_buf: [4096]u8 = undefined; const dir = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; var line: [4200]u8 = undefined; - const look_node = @intFromEnum(TopFile.look); + const look_node = @backingInt(TopFile.look); const looked = th.wr(p, look_node, try std.fmt.bufPrint(&line, "{s}/f.txt\n", .{dir})); try testing.expect(looked.errno() != 0); try testing.expect(std.mem.indexOf(u8, looked.reply.ename, said) != null); @@ -1857,7 +1857,7 @@ test "at the pane cap, pane/new, look and New each say so, and look reads back e test "nothing a mount's close or a no-op truncate sends waits on the editor: a held line runs at its next step" { const p = try withFile(testing.allocator, "x\n"); defer p.deinit(); - const exec = @intFromEnum(TopFile.exec); + const exec = @backingInt(TopFile.exec); // `> exec` truncates nothing; `> body` does. try testing.expect(!needsQuiet(p, .{ .tag = 1, .op = .setattr, .node = exec, .truncate = true })); try testing.expect(!changesPane(p, .{ .tag = 1, .op = .setattr, .node = exec, .truncate = true })); @@ -1875,7 +1875,7 @@ test "nothing a mount's close or a no-op truncate sends waits on the editor: a h test "a command line cut across writes runs once whole, and the last runs at release; an Edit block waits for its end" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const exec = @intFromEnum(TopFile.exec); + const exec = @backingInt(TopFile.exec); const h = call(p, .{ .tag = 1, .op = .open, .node = exec, .omode = 1 }).reply.handle; try testing.expect(h != 0); // Each piece fills its Twrite (a client's one write cut at msize). @@ -1906,12 +1906,12 @@ test "a refused open, create or remove says why in words and logs no err; a refu const serial = serialOf(p); // pane/new is read, never written: a write is refused, and is no // failure the log tells of. - const new = th.wr(p, @intFromEnum(TopFile.new), "x\n"); + const new = th.wr(p, @backingInt(TopFile.new), "x\n"); try testing.expectEqual(Status.err, new.reply.status); try testing.expectEqualStrings("permission denied", new.reply.ename); const made = call(p, .{ .tag = 2, .op = .open, .node = Node.of(serial, .body), .create = true }); try testing.expectEqualStrings("permission denied", made.reply.ename); - const gone = th.rmdir(p, @intFromEnum(TopFile.index)); + const gone = th.rmdir(p, @backingInt(TopFile.index)); try testing.expectEqual(Status.err, gone.reply.status); try testing.expect(gone.reply.ename.len > 0 and !std.ascii.isUpper(gone.reply.ename[0])); // An OTRUNC open's truncation of data after a failed addr: refused, no err. @@ -1961,7 +1961,7 @@ test "a write with no newline waits for its newline or the close, whatever its s test "look and exec read back what their own open's write touched; a fresh open reads the session's last" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const exec = @intFromEnum(TopFile.exec); + const exec = @backingInt(TopFile.exec); const first = p.panes[0].?.serial; const mine = call(p, .{ .tag = 1, .op = .open, .node = exec, .omode = 2 }).reply.handle; const theirs = call(p, .{ .tag = 2, .op = .open, .node = exec, .omode = 2 }).reply.handle; @@ -2013,7 +2013,7 @@ test "a rename of a pane's directory or file is refused as not permitted" { test "no placement leaves a pane shorter than its tag and two rows; a full column refuses the next" { const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); - const new = @intFromEnum(TopFile.new); + const new = @backingInt(TopFile.new); var made: usize = 1; const refused = while (made < pardes.MAX_PANES) : (made += 1) { const a = call(p, .{ .tag = 1, .op = .open, .node = new }); @@ -2078,7 +2078,7 @@ test "a pane made from pane/new goes last in its column, even when the last pane const p = try th.withFile(testing.allocator, "x\n"); defer p.deinit(); for (0..3) |_| { - const made = call(p, .{ .tag = 1, .op = .open, .node = @intFromEnum(TopFile.new) }).reply.handle; + const made = call(p, .{ .tag = 1, .op = .open, .node = @backingInt(TopFile.new) }).reply.handle; p.sync(); try testing.expectEqual(made, p.panes[p.col_panes[0][p.col_n[0] - 1]].?.serial); } diff --git a/src/pager.zig b/src/pager.zig index feabd194..aba73d43 100644 --- a/src/pager.zig +++ b/src/pager.zig @@ -240,8 +240,8 @@ const Handler = struct { .reset_strikethrough => s.strikethrough = false, .direct_color_fg => |c| s.fg = .{ .rgb = .{ c.r, c.g, c.b } }, .direct_color_bg => |c| s.bg = .{ .rgb = .{ c.r, c.g, c.b } }, - .@"8_fg", .@"8_bright_fg" => |name| s.fg = .{ .index = @intFromEnum(name) }, - .@"8_bg", .@"8_bright_bg" => |name| s.bg = .{ .index = @intFromEnum(name) }, + .@"8_fg", .@"8_bright_fg" => |name| s.fg = .{ .index = @backingInt(name) }, + .@"8_bg", .@"8_bright_bg" => |name| s.bg = .{ .index = @backingInt(name) }, .@"256_fg" => |i| s.fg = .{ .index = i }, .@"256_bg" => |i| s.bg = .{ .index = i }, .reset_fg => s.fg = .default, diff --git a/src/pardes.zig b/src/pardes.zig index 8da0922d..7e166847 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -924,7 +924,7 @@ test "Filter is ordered after Del and toggles only its terminal or +Pager pane" const testing = std.testing; const del = std.meta.stringToEnum(Builtin, "Del") orelse return error.MissingDelBuiltin; const filter = std.meta.stringToEnum(Builtin, "Filter") orelse return error.MissingFilterBuiltin; - try testing.expectEqual(@intFromEnum(del) + 1, @intFromEnum(filter)); + try testing.expectEqual(@backingInt(del) + 1, @backingInt(filter)); const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); defer p.deinit(); @@ -3308,8 +3308,8 @@ test "tabbed file aligns syntax cursor and mouse at the nearest insertion gap" { const pane = try p.setTestFile("\treturn x\n"); const f = &pane.file.?; f.highlights = try p.tree_sitter_gpa.alloc(u8, f.content.len); - @memset(f.highlights, @intFromEnum(syntax.Syn.none)); - @memset(f.highlights[1..7], @intFromEnum(syntax.Syn.keyword)); + @memset(f.highlights, @backingInt(syntax.Syn.none)); + @memset(f.highlights[1..7], @backingInt(syntax.Syn.keyword)); f.syntax_dirty = false; pane.body.cur_row = 0; pane.body.cur_col = 1; @@ -3721,7 +3721,7 @@ pub fn hit(key: Key, binding: []const config.Chord) bool { return false; } -pub const sel_slot = @intFromEnum(config.select_button); +pub const sel_slot = @backingInt(config.select_button); /// Pixel dimensions are meaningful only to the native PDF placement path. /// Keep resize events layout-only when that path is not part of the build. @@ -6040,7 +6040,7 @@ pub const Pardes = struct { // The one-failure rule is a write's: a refused open (its OTRUNC's // truncation, a setattr, too), create or remove is its Rerror alone, // no err, as is a write to pane/new, which is only ever read. - const ruled = req.op == .write and req.node != @intFromEnum(ctlfs.TopFile.new); + const ruled = req.op == .write and req.node != @backingInt(ctlfs.TopFile.new); if (reply.status == .err and ruled) ctlfs.events.noteError(p, req, reply); // The request was a whole step of its own, so it settles the way a // step does: the cursor and scroll reconciled, the scripted panes diff --git a/src/pdf_view.zig b/src/pdf_view.zig index 567117bb..500f05f3 100644 --- a/src/pdf_view.zig +++ b/src/pdf_view.zig @@ -2604,7 +2604,7 @@ pub fn pointerRelease( ) PointerRelease { if (comptime !enabled) return .{}; const state = &(pane.pdf orelse return .{}); - const slot = @intFromEnum(button); + const slot = @backingInt(button); const grid_selection = pane.sel[slot]; pane.sel[slot].state = .none; // native quads, not projected text cells diff --git a/src/syntax.zig b/src/syntax.zig index fa212ca7..1c09c9f3 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -214,7 +214,7 @@ fn ensure(spec: *Spec) !Selected { const capture_styles = spec.capture_styles[0..query.captureCount()]; for (capture_styles, 0..) |*style, id| { const name = query.captureNameForId(@intCast(id)) orelse ""; - style.* = @intFromEnum(synFor(name)); + style.* = @backingInt(synFor(name)); if (style.* == 0) query.disableCapture(name); } const parser = ts.Parser.create(); @@ -965,11 +965,11 @@ test "syntax formatted locations color hidden context and preserve multiline sou const styles = try highlightLocationRows(gpa, content, &rows); defer gpa.free(styles); const body = std.mem.indexOf(u8, content, "comment body").?; - try std.testing.expectEqual(@intFromEnum(Syn.comment), styles[body]); - try std.testing.expectEqual(@intFromEnum(Syn.none), styles[body - 1]); + try std.testing.expectEqual(@backingInt(Syn.comment), styles[body]); + try std.testing.expectEqual(@backingInt(Syn.none), styles[body - 1]); const number = std.mem.indexOf(u8, content, "42").?; - try std.testing.expectEqual(@intFromEnum(Syn.number), styles[number]); - try std.testing.expectEqual(@intFromEnum(Syn.none), styles[0]); + try std.testing.expectEqual(@backingInt(Syn.number), styles[number]); + try std.testing.expectEqual(@backingInt(Syn.none), styles[0]); } test "syntax formatted locations separate alignment from Markdown indentation" { @@ -985,8 +985,8 @@ test "syntax formatted locations separate alignment from Markdown indentation" { }; const styles = try highlightLocationRows(gpa, content, &rows); defer gpa.free(styles); - try std.testing.expectEqual(@intFromEnum(Syn.keyword), styles[std.mem.indexOf(u8, content, "Heading").?]); - try std.testing.expectEqual(@intFromEnum(Syn.string), styles[std.mem.indexOf(u8, content, "Code").?]); + try std.testing.expectEqual(@backingInt(Syn.keyword), styles[std.mem.indexOf(u8, content, "Heading").?]); + try std.testing.expectEqual(@backingInt(Syn.string), styles[std.mem.indexOf(u8, content, "Code").?]); } fn inject(styles: []u8, source: []const u8, node: ts.Node, markdown: bool) void { const kind = node.kind(); @@ -1149,7 +1149,7 @@ pub fn highlightDiffRows(gpa: std.mem.Allocator, content: []const u8, start_raw: .meta, .old_path, .new_path => .comment, else => .none, }; - if (style != .none) window.fill(at, nl - at, @intFromEnum(style)); + if (style != .none) window.fill(at, nl - at, @backingInt(style)); } if (nl >= content.len) break; at = nl + 1; @@ -1192,10 +1192,10 @@ fn paintDiffPiece(gpa: std.mem.Allocator, window: anytype, bytes: []const u8, at for (kinds) |kind| { const line = lines.next() orelse break; const style: u8 = switch (kind) { - .added => @intFromEnum(Syn.string) | diff_added, - .removed => @intFromEnum(Syn.number) | diff_removed, - .no_newline => @intFromEnum(Syn.comment), - .hunk => @intFromEnum(Syn.keyword), + .added => @backingInt(Syn.string) | diff_added, + .removed => @backingInt(Syn.number) | diff_removed, + .no_newline => @backingInt(Syn.comment), + .hunk => @backingInt(Syn.keyword), else => 0, }; if (style != 0) window.fill(at + offset, line.len, style); @@ -1273,8 +1273,8 @@ fn paintHunk(gpa: std.mem.Allocator, out: []u8, bytes: []const u8, kinds: []cons .removed => @memcpy(dst, old_colors[old_at..][0..code_len]), .added => @memcpy(dst, new_colors[new_at..][0..code_len]), .context => @memcpy(dst, if (context_new) new_colors[new_at..][0..code_len] else old_colors[old_at..][0..code_len]), - .no_newline => @memset(out[offset..][0..line.len], @intFromEnum(Syn.comment)), - .hunk => @memset(out[offset..][0..line.len], @intFromEnum(Syn.keyword)), + .no_newline => @memset(out[offset..][0..line.len], @backingInt(Syn.comment)), + .hunk => @memset(out[offset..][0..line.len], @backingInt(Syn.keyword)), else => {}, } if (kind == .context or kind == .removed) old_at += code_len + 1; @@ -1322,8 +1322,8 @@ test "syntax a results row is coloured by the file its location names" { try std.testing.expectEqual(content.len, styles.len); for (styles[0.."src/a.zig:1:1".len]) |b| try std.testing.expectEqual(@as(u8, 0), b); const zig_kw = std.mem.indexOf(u8, content, "struct").?; - try std.testing.expectEqual(@intFromEnum(Syn.keyword), styles[zig_kw]); - try std.testing.expectEqual(@intFromEnum(Syn.keyword), styles[zig_kw + 5]); + try std.testing.expectEqual(@backingInt(Syn.keyword), styles[zig_kw]); + try std.testing.expectEqual(@backingInt(Syn.keyword), styles[zig_kw + 5]); const prose = std.mem.indexOf(u8, content, "just some prose").?; for (styles[prose .. prose + 14]) |b| try std.testing.expectEqual(@as(u8, 0), b); const bare = std.mem.indexOf(u8, content, "src/c.zig").?; @@ -1371,14 +1371,14 @@ test "syntax default full grammar set highlights Typst source" { const keyword_at = std.mem.indexOf(u8, source, "let").?; const number_at = std.mem.indexOf(u8, source, "42").?; const string_at = std.mem.indexOf(u8, source, "\"hello\"").?; - try std.testing.expectEqual(Syn.comment, @as(Syn, @enumFromInt(styles[comment_at]))); - try std.testing.expectEqual(Syn.keyword, @as(Syn, @enumFromInt(styles[keyword_at]))); - try std.testing.expectEqual(Syn.number, @as(Syn, @enumFromInt(styles[number_at]))); - try std.testing.expectEqual(Syn.string, @as(Syn, @enumFromInt(styles[string_at]))); + try std.testing.expectEqual(Syn.comment, @as(Syn, @fromBackingInt(@intCast(styles[comment_at])))); + try std.testing.expectEqual(Syn.keyword, @as(Syn, @fromBackingInt(@intCast(styles[keyword_at])))); + try std.testing.expectEqual(Syn.number, @as(Syn, @fromBackingInt(@intCast(styles[number_at])))); + try std.testing.expectEqual(Syn.string, @as(Syn, @fromBackingInt(@intCast(styles[string_at])))); const short_ext = try highlightFileRange(std.testing.allocator, "paper.typ", source, 0, source.len); defer std.testing.allocator.free(short_ext); - try std.testing.expectEqual(Syn.keyword, @as(Syn, @enumFromInt(short_ext[keyword_at]))); + try std.testing.expectEqual(Syn.keyword, @as(Syn, @fromBackingInt(@intCast(short_ext[keyword_at])))); } test "syntax Typst markup constructs paint and raw blocks inject their language" { @@ -1403,7 +1403,7 @@ test "syntax Typst markup constructs paint and raw blocks inject their language" const synAt = struct { fn f(s: []const u8, src: []const u8, needle: []const u8, offset: usize) Syn { - return @enumFromInt(s[std.mem.indexOf(u8, src, needle).? + offset]); + return @fromBackingInt(@intCast(s[std.mem.indexOf(u8, src, needle).? + offset])); } }.f; try std.testing.expectEqual(Syn.keyword, synAt(styles, source, "= Heading", 0)); @@ -1443,7 +1443,7 @@ test "syntax markdown highlights markup, injects inline spans and fenced code bl const synAt = struct { fn f(s: []const u8, src: []const u8, needle: []const u8, offset: usize) Syn { - return @enumFromInt(s[std.mem.indexOf(u8, src, needle).? + offset]); + return @fromBackingInt(@intCast(s[std.mem.indexOf(u8, src, needle).? + offset])); } }.f; try std.testing.expectEqual(Syn.keyword, synAt(styles, source, "Title", 0)); @@ -1471,8 +1471,8 @@ test "syntax inline fast path agrees with full Markdown query" { const actual = try std.testing.allocator.alloc(u8, source.len); defer std.testing.allocator.free(actual); for ([_]Syn{ .none, .keyword }) |background| { - @memset(expected, @intFromEnum(background)); - @memset(actual, @intFromEnum(background)); + @memset(expected, @backingInt(background)); + @memset(actual, @backingInt(background)); runQuery(expected, sel, tree, 0); inject(actual, source, tree.rootNode(), true); if (!std.mem.eql(u8, expected, actual)) std.debug.print("inline mismatch: {s}\n", .{source}); @@ -1511,9 +1511,9 @@ test "syntax plain Markdown keeps block styles without starting the inline parse const source = "# Heading\n\nPlain prose.\n\n indented code\n"; const styles = try highlightFileRange(std.testing.allocator, "a.md", source, 0, source.len); defer std.testing.allocator.free(styles); - try std.testing.expectEqual(@intFromEnum(Syn.keyword), styles[2]); - try std.testing.expectEqual(@intFromEnum(Syn.none), styles[std.mem.indexOf(u8, source, "Plain").?]); - try std.testing.expectEqual(@intFromEnum(Syn.string), styles[std.mem.indexOf(u8, source, "indented").?]); + try std.testing.expectEqual(@backingInt(Syn.keyword), styles[2]); + try std.testing.expectEqual(@backingInt(Syn.none), styles[std.mem.indexOf(u8, source, "Plain").?]); + try std.testing.expectEqual(@backingInt(Syn.string), styles[std.mem.indexOf(u8, source, "indented").?]); for (specs) |spec| { if (std.mem.eql(u8, spec.name, "markdown_inline")) try std.testing.expect(spec.selected == null); } @@ -1544,7 +1544,7 @@ test "syntax highlightDiff colors unified diff lines by prefix" { } fn diffSynAt(styles: []const u8, text: []const u8, needle: []const u8, offset: usize) Syn { - return @enumFromInt(styles[std.mem.indexOf(u8, text, needle).? + offset] & syn_bits); + return @fromBackingInt(@intCast(styles[std.mem.indexOf(u8, text, needle).? + offset] & syn_bits)); } test "syntax a Zig hunk is coloured as Zig, each side parsed whole" { @@ -1715,7 +1715,7 @@ test "syntax a hunk painted once is kept, and a long one is parsed in pieces" { const at = std.mem.indexOf(u8, content, "+const v1000 ").?; const window = try highlightDiff(gpa, content, at, at + 200); defer gpa.free(window); - try std.testing.expectEqual(Syn.number, @as(Syn, @enumFromInt(window["+const v1000 = ".len] & syn_bits))); + try std.testing.expectEqual(Syn.number, @as(Syn, @fromBackingInt(@intCast(window["+const v1000 = ".len] & syn_bits)))); var cached: usize = 0; for (diff_pieces) |slot| if (slot) |piece| { cached += 1; @@ -1780,7 +1780,7 @@ test "syntax query filtering preserves upstream colors" { reference.query = raw_query; reference.capture_styles = try std.testing.allocator.alloc(u8, raw_query.captureCount()); defer std.testing.allocator.free(reference.capture_styles); - for (reference.capture_styles, 0..) |*style, id| style.* = @intFromEnum(synFor(raw_query.captureNameForId(@intCast(id)) orelse "")); + for (reference.capture_styles, 0..) |*style, id| style.* = @backingInt(synFor(raw_query.captureNameForId(@intCast(id)) orelse "")); const tree = selected.parser.parseString(source, null) orelse return error.ParseFailed; defer tree.destroy(); var expected: [source.len]u8 = @splat(0); @@ -1806,8 +1806,8 @@ test "syntax Zig keyword captures cover both bytes beyond line ten thousand" { defer std.testing.allocator.free(styles); for ([_][]const u8{ "fn", "if" }) |keyword| { const at = std.mem.indexOf(u8, code, keyword).?; - try std.testing.expectEqual(@intFromEnum(Syn.keyword), styles[at]); - try std.testing.expectEqual(@intFromEnum(Syn.keyword), styles[at + 1]); + try std.testing.expectEqual(@backingInt(Syn.keyword), styles[at]); + try std.testing.expectEqual(@backingInt(Syn.keyword), styles[at + 1]); } } @@ -1823,8 +1823,8 @@ test "syntax allocator switching clears default-runtime caches" { const restored = try highlightFileRange(std.testing.allocator, "a.zig", source, 0, source.len); defer std.testing.allocator.free(restored); defer stop(); - try std.testing.expectEqual(@intFromEnum(Syn.keyword), restored[0]); - try std.testing.expectEqual(@intFromEnum(Syn.keyword), restored[1]); + try std.testing.expectEqual(@backingInt(Syn.keyword), restored[0]); + try std.testing.expectEqual(@backingInt(Syn.keyword), restored[1]); } test "syntax location context snapshots retain omitted multiline comment scope" { @@ -1848,8 +1848,8 @@ test "syntax location context snapshots retain omitted multiline comment scope" const styles = try highlightLocationRows(gpa, content, &rows); defer gpa.free(styles); for (styles[rows[0].code_start..][0..code.len]) |style| - try std.testing.expectEqual(@intFromEnum(Syn.comment), style); - try std.testing.expectEqual(@intFromEnum(Syn.none), styles[0]); + try std.testing.expectEqual(@backingInt(Syn.comment), style); + try std.testing.expectEqual(@backingInt(Syn.none), styles[0]); } test "syntax declaration locations clear snapshots without muting ordinary context" { @@ -1875,7 +1875,7 @@ test "syntax declaration locations clear snapshots without muting ordinary conte const styles = try highlightLocationRows(gpa, content, &rows); defer gpa.free(styles); for (styles[3..][0..header.len]) |style| try std.testing.expectEqual(@as(u8, 0), style); - try std.testing.expectEqual(@intFromEnum(Syn.number), styles[std.mem.indexOf(u8, content, "42").?]); + try std.testing.expectEqual(@backingInt(Syn.number), styles[std.mem.indexOf(u8, content, "42").?]); } test "syntax stacked addresses do not split multiline source groups" { @@ -1895,11 +1895,11 @@ test "syntax stacked addresses do not split multiline source groups" { }; const styles = try highlightLocationRows(gpa, content, &rows); defer gpa.free(styles); - try std.testing.expectEqual(@intFromEnum(Syn.comment), styles[std.mem.indexOf(u8, content, "42").?]); - try std.testing.expectEqual(@intFromEnum(Syn.number), styles[std.mem.indexOf(u8, content, "7;").?]); + try std.testing.expectEqual(@backingInt(Syn.comment), styles[std.mem.indexOf(u8, content, "42").?]); + try std.testing.expectEqual(@backingInt(Syn.number), styles[std.mem.indexOf(u8, content, "7;").?]); for ([_][]const u8{ "a.c:1:1", "a.c:2:1", "a.c:3:1" }) |label| { const at = std.mem.indexOf(u8, content, label).?; - for (styles[at..][0..label.len]) |style| try std.testing.expectEqual(@intFromEnum(Syn.none), style); + for (styles[at..][0..label.len]) |style| try std.testing.expectEqual(@backingInt(Syn.none), style); } } diff --git a/src/terminal.zig b/src/terminal.zig index a8e7931c..33ad22e6 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -1347,7 +1347,7 @@ pub fn forwardKey(p: *Pardes, id: usize, key: Key) void { pub fn enterTty(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; - const selected = pane.rawPointerText(pane.sel[@intFromEnum(config.select_button)]) != null; + const selected = pane.rawPointerText(pane.sel[@backingInt(config.select_button)]) != null; if (comptime enabled) if (!selected and pane.terminal != null and pane.body.cur_pinned and pane.terminal.?.vt.cursorIsAtPrompt()) handoff: { const screen = pane.terminal.?.vt.screens.active; const goff: i32 = @intCast(screen.pages.scrollbar().offset); diff --git a/src/web.zig b/src/web.zig index fed2ba5a..f89aa7e9 100644 --- a/src/web.zig +++ b/src/web.zig @@ -258,18 +258,20 @@ fn mouseWithHit(button_arg: u32, kind_arg: u32, col_arg: u32, row_arg: u32, mods 3 => .drag, else => return, }; - s.core.update(.{ .mouse = .{ - .body_hit = hit, - .tag_hit = tag_hit, - .button = button, - .kind = kind, - .col = @intCast(@min(col_arg, std.math.maxInt(u16))), - .row = @intCast(@min(row_arg, std.math.maxInt(u16))), - .ctrl = mods & 1 != 0, - // Alt-click is B2 and Cmd/Super-click B3 (mouse.emulateButton). - .alt = mods & 2 != 0, - .super = mods & 8 != 0, - } }); + s.core.update(.{ + .mouse = .{ + .body_hit = hit, + .tag_hit = tag_hit, + .button = button, + .kind = kind, + .col = @intCast(@min(col_arg, std.math.maxInt(u16))), + .row = @intCast(@min(row_arg, std.math.maxInt(u16))), + .ctrl = mods & 1 != 0, + // Alt-click is B2 and Cmd/Super-click B3 (mouse.emulateButton). + .alt = mods & 2 != 0, + .super = mods & 8 != 0, + }, + }); } export fn pardes_touch_scroll(delta: f32) void { @@ -347,7 +349,7 @@ export fn pardes_tag_layer_value(index: u32, field: u32) u32 { if (layer.rows == 0) return 0; return switch (field) { 0 => layer.cols, - 1 => @intFromEnum(layer.kind), + 1 => @backingInt(layer.kind), 2 => layer.id, 3 => layer.serial, 4 => layer.viewport.x, @@ -421,7 +423,7 @@ export fn pardes_row_metrics(body_w: u16, body_h: u16, tagline_w: u16, tagline_h export fn pardes_pointer_shape() u32 { const s = &(state orelse return 0); - return @intFromEnum(s.core.surface.pointer_shape); + return @backingInt(s.core.surface.pointer_shape); } export fn pardes_cursor_y() i32 { @@ -557,6 +559,6 @@ fn encodeAttrs(style: pardes.CellStyle) u16 { attrs |= @as(u16, @intFromBool(style.invisible)) << 5; attrs |= @as(u16, @intFromBool(style.strikethrough)) << 6; attrs |= @as(u16, @intFromBool(style.font_role == .tagline)) * attr_tagline; - attrs |= @as(u16, @intFromEnum(style.ul)) << 8; + attrs |= @as(u16, @backingInt(style.ul)) << 8; return attrs; } diff --git a/test/deck/buttons.zon b/test/deck/buttons.zon index 8b3ae7f8..50d9c70c 100644 --- a/test/deck/buttons.zon +++ b/test/deck/buttons.zon @@ -1,81 +1,81 @@ .{ .version = 1, .events = .{ -.{.t=3700753450,.pad=2,.ev=.{.button=.{.idx=10,.down=true}}}, -.{.t=3900818994,.pad=2,.ev=.{.button=.{.idx=10,.down=false}}}, -.{.t=3956546622,.pad=2,.ev=.{.button=.{.idx=9,.down=true}}}, -.{.t=4123264775,.pad=2,.ev=.{.button=.{.idx=9,.down=false}}}, -.{.t=4930702402,.pad=2,.ev=.{.button=.{.idx=8,.down=true}}}, -.{.t=5145495294,.pad=2,.ev=.{.button=.{.idx=8,.down=false}}}, -.{.t=5256748340,.pad=2,.ev=.{.button=.{.idx=7,.down=true}}}, -.{.t=5467530268,.pad=2,.ev=.{.button=.{.idx=7,.down=false}}}, -.{.t=6756403713,.pad=2,.ev=.{.button=.{.idx=2,.down=true}}}, -.{.t=6911854483,.pad=2,.ev=.{.button=.{.idx=2,.down=false}}}, -.{.t=7211860980,.pad=2,.ev=.{.button=.{.idx=3,.down=true}}}, -.{.t=7389532087,.pad=2,.ev=.{.button=.{.idx=3,.down=false}}}, -.{.t=8133944867,.pad=2,.ev=.{.button=.{.idx=3,.down=true}}}, -.{.t=8289426557,.pad=2,.ev=.{.button=.{.idx=3,.down=false}}}, -.{.t=9089438184,.pad=2,.ev=.{.button=.{.idx=5,.down=true}}}, -.{.t=9234016011,.pad=2,.ev=.{.button=.{.idx=2,.down=true}}}, -.{.t=9356447170,.pad=2,.ev=.{.button=.{.idx=2,.down=false}}}, -.{.t=9500690066,.pad=2,.ev=.{.button=.{.idx=5,.down=false}}}, -.{.t=10234132592,.pad=2,.ev=.{.button=.{.idx=5,.down=true}}}, -.{.t=10389693142,.pad=2,.ev=.{.button=.{.idx=2,.down=true}}}, -.{.t=10500635738,.pad=2,.ev=.{.button=.{.idx=2,.down=false}}}, -.{.t=10600562571,.pad=2,.ev=.{.button=.{.idx=5,.down=false}}}, -.{.t=11211884827,.pad=2,.ev=.{.button=.{.idx=3,.down=true}}}, -.{.t=11333789807,.pad=2,.ev=.{.button=.{.idx=3,.down=false}}}, -.{.t=11622673840,.pad=2,.ev=.{.button=.{.idx=3,.down=true}}}, -.{.t=11778210450,.pad=2,.ev=.{.button=.{.idx=3,.down=false}}}, -.{.t=12056066449,.pad=2,.ev=.{.button=.{.idx=0,.down=true}}}, -.{.t=12200470216,.pad=2,.ev=.{.button=.{.idx=0,.down=false}}}, -.{.t=13122626673,.pad=2,.ev=.{.button=.{.idx=1,.down=true}}}, -.{.t=13256318175,.pad=2,.ev=.{.button=.{.idx=1,.down=false}}}, -.{.t=30877608417,.pad=2,.ev=.{.button=.{.idx=13,.down=true}}}, -.{.t=30932947265,.pad=2,.ev=.{.button=.{.idx=13,.down=false}}}, -.{.t=31188916557,.pad=2,.ev=.{.button=.{.idx=14,.down=true}}}, -.{.t=31344392047,.pad=2,.ev=.{.button=.{.idx=14,.down=false}}}, -.{.t=31355303161,.pad=2,.ev=.{.button=.{.idx=11,.down=true}}}, -.{.t=31377574308,.pad=2,.ev=.{.button=.{.idx=11,.down=false}}}, -.{.t=31377580618,.pad=2,.ev=.{.button=.{.idx=11,.down=true}}}, -.{.t=31533158438,.pad=2,.ev=.{.button=.{.idx=11,.down=false}}}, -.{.t=31599806330,.pad=2,.ev=.{.button=.{.idx=12,.down=true}}}, -.{.t=31699701622,.pad=2,.ev=.{.button=.{.idx=14,.down=true}}}, -.{.t=31699711442,.pad=2,.ev=.{.button=.{.idx=12,.down=false}}}, -.{.t=31833163995,.pad=2,.ev=.{.button=.{.idx=14,.down=false}}}, -.{.t=31844214668,.pad=2,.ev=.{.button=.{.idx=11,.down=true}}}, -.{.t=31933218167,.pad=2,.ev=.{.button=.{.idx=11,.down=false}}}, -.{.t=31944106321,.pad=2,.ev=.{.button=.{.idx=13,.down=true}}}, -.{.t=31944118861,.pad=2,.ev=.{.button=.{.idx=13,.down=false}}}, -.{.t=32577585424,.pad=2,.ev=.{.button=.{.idx=7,.down=true}}}, -.{.t=32777404849,.pad=2,.ev=.{.button=.{.idx=7,.down=false}}}, -.{.t=32932893939,.pad=2,.ev=.{.button=.{.idx=8,.down=true}}}, -.{.t=33122371409,.pad=2,.ev=.{.button=.{.idx=8,.down=false}}}, -.{.t=34899667922,.pad=2,.ev=.{.button=.{.idx=10,.down=true}}}, -.{.t=35143908581,.pad=2,.ev=.{.button=.{.idx=10,.down=false}}}, -.{.t=35143918751,.pad=2,.ev=.{.button=.{.idx=9,.down=true}}}, -.{.t=35299532711,.pad=2,.ev=.{.button=.{.idx=9,.down=false}}}, -.{.t=36188307687,.pad=2,.ev=.{.button=.{.idx=10,.down=true}}}, -.{.t=36351697335,.pad=2,.ev=.{.button=.{.idx=9,.down=true}}}, -.{.t=36399712574,.pad=2,.ev=.{.button=.{.idx=10,.down=false}}}, -.{.t=36521680424,.pad=2,.ev=.{.button=.{.idx=10,.down=true}}}, -.{.t=36543814231,.pad=2,.ev=.{.button=.{.idx=9,.down=false}}}, -.{.t=36688528867,.pad=2,.ev=.{.button=.{.idx=10,.down=false}}}, -.{.t=38810548641,.pad=2,.ev=.{.button=.{.idx=8,.down=true}}}, -.{.t=38988265258,.pad=2,.ev=.{.button=.{.idx=8,.down=false}}}, -.{.t=39421485428,.pad=2,.ev=.{.button=.{.idx=7,.down=true}}}, -.{.t=39521563760,.pad=2,.ev=.{.button=.{.idx=8,.down=true}}}, -.{.t=39543869347,.pad=2,.ev=.{.button=.{.idx=7,.down=false}}}, -.{.t=39654975672,.pad=2,.ev=.{.button=.{.idx=8,.down=false}}}, -.{.t=40199575307,.pad=2,.ev=.{.button=.{.idx=0,.down=true}}}, -.{.t=40388115109,.pad=2,.ev=.{.button=.{.idx=0,.down=false}}}, -.{.t=40810375225,.pad=2,.ev=.{.button=.{.idx=2,.down=true}}}, -.{.t=40976868838,.pad=2,.ev=.{.button=.{.idx=2,.down=false}}}, -.{.t=41032455046,.pad=2,.ev=.{.button=.{.idx=3,.down=true}}}, -.{.t=41243668724,.pad=2,.ev=.{.button=.{.idx=3,.down=false}}}, -.{.t=42565700760,.pad=2,.ev=.{.button=.{.idx=2,.down=true}}}, -.{.t=42743538487,.pad=2,.ev=.{.button=.{.idx=2,.down=false}}}, -.{.t=43676697498,.pad=2,.ev=.{.button=.{.idx=5,.down=true}}}, -.{.t=43932510879,.pad=2,.ev=.{.button=.{.idx=5,.down=false}}}, -.{.t=43943745523,.pad=2,.ev=.{.button=.{.idx=1,.down=true}}}, -.{.t=44021582808,.pad=2,.ev=.{.button=.{.idx=1,.down=false}}}, -.{.t=44599100514,.pad=2,.ev=.{.button=.{.idx=1,.down=true}}}, + .{ .t = 3700753450, .pad = 2, .ev = .{ .button = .{ .idx = 10, .down = true } } }, + .{ .t = 3900818994, .pad = 2, .ev = .{ .button = .{ .idx = 10, .down = false } } }, + .{ .t = 3956546622, .pad = 2, .ev = .{ .button = .{ .idx = 9, .down = true } } }, + .{ .t = 4123264775, .pad = 2, .ev = .{ .button = .{ .idx = 9, .down = false } } }, + .{ .t = 4930702402, .pad = 2, .ev = .{ .button = .{ .idx = 8, .down = true } } }, + .{ .t = 5145495294, .pad = 2, .ev = .{ .button = .{ .idx = 8, .down = false } } }, + .{ .t = 5256748340, .pad = 2, .ev = .{ .button = .{ .idx = 7, .down = true } } }, + .{ .t = 5467530268, .pad = 2, .ev = .{ .button = .{ .idx = 7, .down = false } } }, + .{ .t = 6756403713, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = true } } }, + .{ .t = 6911854483, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = false } } }, + .{ .t = 7211860980, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = true } } }, + .{ .t = 7389532087, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = false } } }, + .{ .t = 8133944867, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = true } } }, + .{ .t = 8289426557, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = false } } }, + .{ .t = 9089438184, .pad = 2, .ev = .{ .button = .{ .idx = 5, .down = true } } }, + .{ .t = 9234016011, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = true } } }, + .{ .t = 9356447170, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = false } } }, + .{ .t = 9500690066, .pad = 2, .ev = .{ .button = .{ .idx = 5, .down = false } } }, + .{ .t = 10234132592, .pad = 2, .ev = .{ .button = .{ .idx = 5, .down = true } } }, + .{ .t = 10389693142, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = true } } }, + .{ .t = 10500635738, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = false } } }, + .{ .t = 10600562571, .pad = 2, .ev = .{ .button = .{ .idx = 5, .down = false } } }, + .{ .t = 11211884827, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = true } } }, + .{ .t = 11333789807, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = false } } }, + .{ .t = 11622673840, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = true } } }, + .{ .t = 11778210450, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = false } } }, + .{ .t = 12056066449, .pad = 2, .ev = .{ .button = .{ .idx = 0, .down = true } } }, + .{ .t = 12200470216, .pad = 2, .ev = .{ .button = .{ .idx = 0, .down = false } } }, + .{ .t = 13122626673, .pad = 2, .ev = .{ .button = .{ .idx = 1, .down = true } } }, + .{ .t = 13256318175, .pad = 2, .ev = .{ .button = .{ .idx = 1, .down = false } } }, + .{ .t = 30877608417, .pad = 2, .ev = .{ .button = .{ .idx = 13, .down = true } } }, + .{ .t = 30932947265, .pad = 2, .ev = .{ .button = .{ .idx = 13, .down = false } } }, + .{ .t = 31188916557, .pad = 2, .ev = .{ .button = .{ .idx = 14, .down = true } } }, + .{ .t = 31344392047, .pad = 2, .ev = .{ .button = .{ .idx = 14, .down = false } } }, + .{ .t = 31355303161, .pad = 2, .ev = .{ .button = .{ .idx = 11, .down = true } } }, + .{ .t = 31377574308, .pad = 2, .ev = .{ .button = .{ .idx = 11, .down = false } } }, + .{ .t = 31377580618, .pad = 2, .ev = .{ .button = .{ .idx = 11, .down = true } } }, + .{ .t = 31533158438, .pad = 2, .ev = .{ .button = .{ .idx = 11, .down = false } } }, + .{ .t = 31599806330, .pad = 2, .ev = .{ .button = .{ .idx = 12, .down = true } } }, + .{ .t = 31699701622, .pad = 2, .ev = .{ .button = .{ .idx = 14, .down = true } } }, + .{ .t = 31699711442, .pad = 2, .ev = .{ .button = .{ .idx = 12, .down = false } } }, + .{ .t = 31833163995, .pad = 2, .ev = .{ .button = .{ .idx = 14, .down = false } } }, + .{ .t = 31844214668, .pad = 2, .ev = .{ .button = .{ .idx = 11, .down = true } } }, + .{ .t = 31933218167, .pad = 2, .ev = .{ .button = .{ .idx = 11, .down = false } } }, + .{ .t = 31944106321, .pad = 2, .ev = .{ .button = .{ .idx = 13, .down = true } } }, + .{ .t = 31944118861, .pad = 2, .ev = .{ .button = .{ .idx = 13, .down = false } } }, + .{ .t = 32577585424, .pad = 2, .ev = .{ .button = .{ .idx = 7, .down = true } } }, + .{ .t = 32777404849, .pad = 2, .ev = .{ .button = .{ .idx = 7, .down = false } } }, + .{ .t = 32932893939, .pad = 2, .ev = .{ .button = .{ .idx = 8, .down = true } } }, + .{ .t = 33122371409, .pad = 2, .ev = .{ .button = .{ .idx = 8, .down = false } } }, + .{ .t = 34899667922, .pad = 2, .ev = .{ .button = .{ .idx = 10, .down = true } } }, + .{ .t = 35143908581, .pad = 2, .ev = .{ .button = .{ .idx = 10, .down = false } } }, + .{ .t = 35143918751, .pad = 2, .ev = .{ .button = .{ .idx = 9, .down = true } } }, + .{ .t = 35299532711, .pad = 2, .ev = .{ .button = .{ .idx = 9, .down = false } } }, + .{ .t = 36188307687, .pad = 2, .ev = .{ .button = .{ .idx = 10, .down = true } } }, + .{ .t = 36351697335, .pad = 2, .ev = .{ .button = .{ .idx = 9, .down = true } } }, + .{ .t = 36399712574, .pad = 2, .ev = .{ .button = .{ .idx = 10, .down = false } } }, + .{ .t = 36521680424, .pad = 2, .ev = .{ .button = .{ .idx = 10, .down = true } } }, + .{ .t = 36543814231, .pad = 2, .ev = .{ .button = .{ .idx = 9, .down = false } } }, + .{ .t = 36688528867, .pad = 2, .ev = .{ .button = .{ .idx = 10, .down = false } } }, + .{ .t = 38810548641, .pad = 2, .ev = .{ .button = .{ .idx = 8, .down = true } } }, + .{ .t = 38988265258, .pad = 2, .ev = .{ .button = .{ .idx = 8, .down = false } } }, + .{ .t = 39421485428, .pad = 2, .ev = .{ .button = .{ .idx = 7, .down = true } } }, + .{ .t = 39521563760, .pad = 2, .ev = .{ .button = .{ .idx = 8, .down = true } } }, + .{ .t = 39543869347, .pad = 2, .ev = .{ .button = .{ .idx = 7, .down = false } } }, + .{ .t = 39654975672, .pad = 2, .ev = .{ .button = .{ .idx = 8, .down = false } } }, + .{ .t = 40199575307, .pad = 2, .ev = .{ .button = .{ .idx = 0, .down = true } } }, + .{ .t = 40388115109, .pad = 2, .ev = .{ .button = .{ .idx = 0, .down = false } } }, + .{ .t = 40810375225, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = true } } }, + .{ .t = 40976868838, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = false } } }, + .{ .t = 41032455046, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = true } } }, + .{ .t = 41243668724, .pad = 2, .ev = .{ .button = .{ .idx = 3, .down = false } } }, + .{ .t = 42565700760, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = true } } }, + .{ .t = 42743538487, .pad = 2, .ev = .{ .button = .{ .idx = 2, .down = false } } }, + .{ .t = 43676697498, .pad = 2, .ev = .{ .button = .{ .idx = 5, .down = true } } }, + .{ .t = 43932510879, .pad = 2, .ev = .{ .button = .{ .idx = 5, .down = false } } }, + .{ .t = 43943745523, .pad = 2, .ev = .{ .button = .{ .idx = 1, .down = true } } }, + .{ .t = 44021582808, .pad = 2, .ev = .{ .button = .{ .idx = 1, .down = false } } }, + .{ .t = 44599100514, .pad = 2, .ev = .{ .button = .{ .idx = 1, .down = true } } }, } } diff --git a/test/deck/lpad-swipe.zon b/test/deck/lpad-swipe.zon index 33a17751..d5b5049a 100644 --- a/test/deck/lpad-swipe.zon +++ b/test/deck/lpad-swipe.zon @@ -1,163 +1,163 @@ .{ .version = 1, .events = .{ -.{.t=28555347100,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.29483032,.y=0.24435425,.pressure=0.0022583008}}}, -.{.t=28555355490,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2937622,.y=0.24847412,.pressure=0.0015563965}}}, -.{.t=28566662333,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2920227,.y=0.25350952,.pressure=0.00048828125}}}, -.{.t=28566669273,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.up,.x=0.28912354,.y=0.25863647,.pressure=0}}}, -.{.t=28633190705,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.down,.x=0.26437378,.y=0.44036865,.pressure=0.0008239746}}}, -.{.t=28644226129,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2635193,.y=0.44857788,.pressure=0.0008239746}}}, -.{.t=28644235079,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.26348877,.y=0.4538269,.pressure=0.0015563965}}}, -.{.t=28644241049,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.26272583,.y=0.45950317,.pressure=0.003692627}}}, -.{.t=28655363472,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.26229858,.y=0.46218872,.pressure=0.0047912598}}}, -.{.t=28655373032,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.26153564,.y=0.46594238,.pressure=0.005493164}}}, -.{.t=28666533886,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2607727,.y=0.46810913,.pressure=0.008026123}}}, -.{.t=28666541736,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.26037598,.y=0.46969604,.pressure=0.00982666}}}, -.{.t=28666544986,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.26004028,.y=0.47079468,.pressure=0.010894775}}}, -.{.t=28677510399,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25985718,.y=0.47192383,.pressure=0.011962891}}}, -.{.t=28677516759,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25924683,.y=0.47277832,.pressure=0.013061523}}}, -.{.t=28677520229,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25894165,.y=0.47366333,.pressure=0.01449585}}}, -.{.t=28688736483,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25906372,.y=0.47409058,.pressure=0.015197754}}}, -.{.t=28688747523,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25872803,.y=0.47351074,.pressure=0.013061523}}}, -.{.t=28688752063,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25827026,.y=0.4732666,.pressure=0.013397217}}}, -.{.t=28699780696,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2581787,.y=0.47317505,.pressure=0.014129639}}}, -.{.t=28699788576,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25759888,.y=0.47305298,.pressure=0.014831543}}}, -.{.t=28699792416,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25787354,.y=0.47280884,.pressure=0.01449585}}}, -.{.t=28711058720,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25784302,.y=0.47225952,.pressure=0.013763428}}}, -.{.t=28711073040,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25738525,.y=0.472229,.pressure=0.014129639}}}, -.{.t=28722312593,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25720215,.y=0.4717102,.pressure=0.013763428}}}, -.{.t=28722328533,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2572937,.y=0.47213745,.pressure=0.012329102}}}, -.{.t=28722335123,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2576294,.y=0.4721985,.pressure=0.01449585}}}, -.{.t=28733104547,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25784302,.y=0.4718933,.pressure=0.013763428}}}, -.{.t=28733113157,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2571411,.y=0.472229,.pressure=0.013763428}}}, -.{.t=28733116517,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.256958,.y=0.47235107,.pressure=0.010894775}}}, -.{.t=28744542840,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25598145,.y=0.47323608,.pressure=0.011962891}}}, -.{.t=28744554360,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25558472,.y=0.47372437,.pressure=0.012329102}}}, -.{.t=28744558310,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25463867,.y=0.47329712,.pressure=0.013061523}}}, -.{.t=28755164615,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2541809,.y=0.4736023,.pressure=0.013397217}}}, -.{.t=28755173055,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2536316,.y=0.47485352,.pressure=0.013397217}}}, -.{.t=28766369408,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2527771,.y=0.4749756,.pressure=0.011962891}}}, -.{.t=28766376998,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2524109,.y=0.47543335,.pressure=0.011962891}}}, -.{.t=28766380848,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2518921,.y=0.4761963,.pressure=0.011962891}}}, -.{.t=28777479342,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25073242,.y=0.4764099,.pressure=0.013397217}}}, -.{.t=28777487702,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24984741,.y=0.4772644,.pressure=0.015197754}}}, -.{.t=28777491542,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24942017,.y=0.47872925,.pressure=0.015563965}}}, -.{.t=28788858885,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24816895,.y=0.47982788,.pressure=0.016296387}}}, -.{.t=28788869705,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.247406,.y=0.48181152,.pressure=0.016998291}}}, -.{.t=28788873665,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24645996,.y=0.48260498,.pressure=0.015563965}}}, -.{.t=28800073548,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2456665,.y=0.48516846,.pressure=0.01663208}}}, -.{.t=28800082148,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24414062,.y=0.48757935,.pressure=0.018432617}}}, -.{.t=28800086718,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2437439,.y=0.48986816,.pressure=0.019165039}}}, -.{.t=28810881362,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2432251,.y=0.49273682,.pressure=0.017730713}}}, -.{.t=28810890602,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24337769,.y=0.4951172,.pressure=0.018432617}}}, -.{.t=28822223135,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24224854,.y=0.49868774,.pressure=0.018066406}}}, -.{.t=28822236725,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2409668,.y=0.5030823,.pressure=0.018432617}}}, -.{.t=28822243035,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24002075,.y=0.5093689,.pressure=0.017364502}}}, -.{.t=28833221849,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.23800659,.y=0.52023315,.pressure=0.017364502}}}, -.{.t=28833234799,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.23648071,.y=0.5312195,.pressure=0.018066406}}}, -.{.t=28833241859,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.23449707,.y=0.54260254,.pressure=0.018432617}}}, -.{.t=28844533292,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.23208618,.y=0.5539551,.pressure=0.019165039}}}, -.{.t=28844544902,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22930908,.y=0.5640869,.pressure=0.020599365}}}, -.{.t=28844549012,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22769165,.y=0.5701294,.pressure=0.022399902}}}, -.{.t=28855315576,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22613525,.y=0.57528687,.pressure=0.023468018}}}, -.{.t=28855325516,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22503662,.y=0.5812073,.pressure=0.02420044}}}, -.{.t=28866614540,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22335815,.y=0.5848694,.pressure=0.02420044}}}, -.{.t=28866626480,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22390747,.y=0.5887146,.pressure=0.024536133}}}, -.{.t=28866629910,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22283936,.y=0.59265137,.pressure=0.024536133}}}, -.{.t=28877415724,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22262573,.y=0.59625244,.pressure=0.025268555}}}, -.{.t=28877428004,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22128296,.y=0.6008606,.pressure=0.025268555}}}, -.{.t=28888551597,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2204895,.y=0.60409546,.pressure=0.025268555}}}, -.{.t=28888564767,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21896362,.y=0.61083984,.pressure=0.025634766}}}, -.{.t=28888571967,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21774292,.y=0.6156006,.pressure=0.025970459}}}, -.{.t=28899744701,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21542358,.y=0.62112427,.pressure=0.02633667}}}, -.{.t=28899757861,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21438599,.y=0.62576294,.pressure=0.027435303}}}, -.{.t=28899764601,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21298218,.y=0.63223267,.pressure=0.027069092}}}, -.{.t=28910731865,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21209717,.y=0.63708496,.pressure=0.02633667}}}, -.{.t=28910746485,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21133423,.y=0.6419983,.pressure=0.02670288}}}, -.{.t=28921990138,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21032715,.y=0.64730835,.pressure=0.027435303}}}, -.{.t=28922004158,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2090149,.y=0.65237427,.pressure=0.027069092}}}, -.{.t=28922010498,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.20770264,.y=0.6588135,.pressure=0.02670288}}}, -.{.t=28932967412,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.20559692,.y=0.6654968,.pressure=0.025970459}}}, -.{.t=28932979792,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.20404053,.y=0.67285156,.pressure=0.025634766}}}, -.{.t=28932983492,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.20187378,.y=0.6821594,.pressure=0.024536133}}}, -.{.t=28944345285,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19940186,.y=0.6911926,.pressure=0.02420044}}}, -.{.t=28944363135,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19662476,.y=0.703949,.pressure=0.022033691}}}, -.{.t=28944369185,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19250488,.y=0.71707153,.pressure=0.02130127}}}, -.{.t=28955070939,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.18859863,.y=0.7327881,.pressure=0.020599365}}}, -.{.t=28955080209,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.18469238,.y=0.7469177,.pressure=0.018798828}}}, -.{.t=28966644072,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.1803894,.y=0.76065063,.pressure=0.018066406}}}, -.{.t=28966660132,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17681885,.y=0.7729492,.pressure=0.019165039}}}, -.{.t=28966666102,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17303467,.y=0.78430176,.pressure=0.01953125}}}, -.{.t=28977523276,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17047119,.y=0.79385376,.pressure=0.019165039}}}, -.{.t=28977533506,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16790771,.y=0.8000183,.pressure=0.019866943}}}, -.{.t=28977538756,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16583252,.y=0.8055115,.pressure=0.018798828}}}, -.{.t=28988801809,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16448975,.y=0.8109131,.pressure=0.01953125}}}, -.{.t=28988815059,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16299438,.y=0.81552124,.pressure=0.02130127}}}, -.{.t=28988820159,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16275024,.y=0.8183899,.pressure=0.02166748}}}, -.{.t=29000005933,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16235352,.y=0.8191223,.pressure=0.022399902}}}, -.{.t=29000020133,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16220093,.y=0.820343,.pressure=0.023468018}}}, -.{.t=29000023943,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16268921,.y=0.8208618,.pressure=0.023834229}}}, -.{.t=29010879647,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.1618042,.y=0.82214355,.pressure=0.025634766}}}, -.{.t=29010893477,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16238403,.y=0.82196045,.pressure=0.02633667}}}, -.{.t=29022239700,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16329956,.y=0.82180786,.pressure=0.027069092}}}, -.{.t=29022255010,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16305542,.y=0.8227539,.pressure=0.027069092}}}, -.{.t=29022260530,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16360474,.y=0.8215027,.pressure=0.02670288}}}, -.{.t=29033423863,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16390991,.y=0.8215637,.pressure=0.02670288}}}, -.{.t=29033439393,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16513062,.y=0.820282,.pressure=0.02633667}}}, -.{.t=29033446553,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16571045,.y=0.82003784,.pressure=0.027069092}}}, -.{.t=29044100787,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16552734,.y=0.81985474,.pressure=0.024536133}}}, -.{.t=29044110747,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16653442,.y=0.8192444,.pressure=0.023468018}}}, -.{.t=29044114927,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16690063,.y=0.81710815,.pressure=0.023101807}}}, -.{.t=29055305531,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16772461,.y=0.81536865,.pressure=0.022766113}}}, -.{.t=29055315751,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16854858,.y=0.81365967,.pressure=0.022399902}}}, -.{.t=29066613054,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.16940308,.y=0.811615,.pressure=0.02166748}}}, -.{.t=29066629614,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17041016,.y=0.80908203,.pressure=0.02130127}}}, -.{.t=29066636804,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17147827,.y=0.8067322,.pressure=0.02130127}}}, -.{.t=29077513018,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17288208,.y=0.8036804,.pressure=0.019165039}}}, -.{.t=29077525768,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17391968,.y=0.8003235,.pressure=0.015197754}}}, -.{.t=29077531158,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17553711,.y=0.7965088,.pressure=0.014831543}}}, -.{.t=29088910511,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17697144,.y=0.7913208,.pressure=0.015563965}}}, -.{.t=29088924801,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17819214,.y=0.78622437,.pressure=0.01449585}}}, -.{.t=29088930391,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.17999268,.y=0.7813721,.pressure=0.013397217}}}, -.{.t=29100047575,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.18148804,.y=0.7752991,.pressure=0.014129639}}}, -.{.t=29100061535,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.1831665,.y=0.76898193,.pressure=0.014129639}}}, -.{.t=29100068045,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.184906,.y=0.7624817,.pressure=0.013763428}}}, -.{.t=29111067488,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.18692017,.y=0.7561035,.pressure=0.013061523}}}, -.{.t=29111083948,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.18884277,.y=0.7487488,.pressure=0.01449585}}}, -.{.t=29122288972,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19082642,.y=0.7409973,.pressure=0.01449585}}}, -.{.t=29122305542,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19223022,.y=0.73428345,.pressure=0.014831543}}}, -.{.t=29122313342,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19274902,.y=0.7257385,.pressure=0.014831543}}}, -.{.t=29133328146,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19299316,.y=0.714447,.pressure=0.015197754}}}, -.{.t=29133345356,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.1928711,.y=0.7018738,.pressure=0.01449585}}}, -.{.t=29133350306,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19335938,.y=0.6808777,.pressure=0.014831543}}}, -.{.t=29144200749,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19464111,.y=0.65582275,.pressure=0.014831543}}}, -.{.t=29144216579,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19668579,.y=0.63186646,.pressure=0.01449585}}}, -.{.t=29144223419,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.19927979,.y=0.6045227,.pressure=0.013763428}}}, -.{.t=29154998954,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.20211792,.y=0.57891846,.pressure=0.0126953125}}}, -.{.t=29155006203,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.20501709,.y=0.551239,.pressure=0.0126953125}}}, -.{.t=29166393667,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.20880127,.y=0.5248718,.pressure=0.012329102}}}, -.{.t=29166404147,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21270752,.y=0.499115,.pressure=0.013397217}}}, -.{.t=29166409197,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.21655273,.y=0.47366333,.pressure=0.013763428}}}, -.{.t=29177500380,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2204895,.y=0.45114136,.pressure=0.0101623535}}}, -.{.t=29177510970,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.22451782,.y=0.4290161,.pressure=0.0101623535}}}, -.{.t=29177516230,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2286377,.y=0.40975952,.pressure=0.0101623535}}}, -.{.t=29188832983,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.23208618,.y=0.39212036,.pressure=0.010528564}}}, -.{.t=29188846483,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.23532104,.y=0.375885,.pressure=0.007293701}}}, -.{.t=29188851103,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.23809814,.y=0.35943604,.pressure=0.009460449}}}, -.{.t=29200021967,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24072266,.y=0.34292603,.pressure=0.011260986}}}, -.{.t=29200037067,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24298096,.y=0.32809448,.pressure=0.011962891}}}, -.{.t=29200042877,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24493408,.y=0.3138733,.pressure=0.010528564}}}, -.{.t=29210884631,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24728394,.y=0.29989624,.pressure=0.012329102}}}, -.{.t=29221881625,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.24908447,.y=0.2866516,.pressure=0.011962891}}}, -.{.t=29221891355,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.250885,.y=0.2755432,.pressure=0.010528564}}}, -.{.t=29221896615,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.252594,.y=0.26571655,.pressure=0.011962891}}}, -.{.t=29233293918,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25378418,.y=0.2571106,.pressure=0.0126953125}}}, -.{.t=29233306418,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25476074,.y=0.24942017,.pressure=0.0126953125}}}, -.{.t=29233312238,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25534058,.y=0.24307251,.pressure=0.011260986}}}, -.{.t=29244359261,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25610352,.y=0.23760986,.pressure=0.0101623535}}}, -.{.t=29244375081,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25680542,.y=0.23291016,.pressure=0.0101623535}}}, -.{.t=29244383211,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25750732,.y=0.22824097,.pressure=0.0101623535}}}, -.{.t=29255381715,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25823975,.y=0.22570801,.pressure=0.007659912}}}, -.{.t=29255392615,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.25909424,.y=0.2234497,.pressure=0.007293701}}}, -.{.t=29266740458,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.2599182,.y=0.22180176,.pressure=0.006225586}}}, -.{.t=29266753748,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.26089478,.y=0.22140503,.pressure=0.0051574707}}}, -.{.t=29266758978,.pad=2,.ev=.{.touch=.{.touchpad=0,.finger=0,.phase=.motion,.x=0.26275635,.y=0.22149658,.pressure=0.0033569336}}}, + .{ .t = 28555347100, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.29483032, .y = 0.24435425, .pressure = 0.0022583008 } } }, + .{ .t = 28555355490, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2937622, .y = 0.24847412, .pressure = 0.0015563965 } } }, + .{ .t = 28566662333, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2920227, .y = 0.25350952, .pressure = 0.00048828125 } } }, + .{ .t = 28566669273, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .up, .x = 0.28912354, .y = 0.25863647, .pressure = 0 } } }, + .{ .t = 28633190705, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .down, .x = 0.26437378, .y = 0.44036865, .pressure = 0.0008239746 } } }, + .{ .t = 28644226129, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2635193, .y = 0.44857788, .pressure = 0.0008239746 } } }, + .{ .t = 28644235079, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.26348877, .y = 0.4538269, .pressure = 0.0015563965 } } }, + .{ .t = 28644241049, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.26272583, .y = 0.45950317, .pressure = 0.003692627 } } }, + .{ .t = 28655363472, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.26229858, .y = 0.46218872, .pressure = 0.0047912598 } } }, + .{ .t = 28655373032, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.26153564, .y = 0.46594238, .pressure = 0.005493164 } } }, + .{ .t = 28666533886, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2607727, .y = 0.46810913, .pressure = 0.008026123 } } }, + .{ .t = 28666541736, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.26037598, .y = 0.46969604, .pressure = 0.00982666 } } }, + .{ .t = 28666544986, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.26004028, .y = 0.47079468, .pressure = 0.010894775 } } }, + .{ .t = 28677510399, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25985718, .y = 0.47192383, .pressure = 0.011962891 } } }, + .{ .t = 28677516759, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25924683, .y = 0.47277832, .pressure = 0.013061523 } } }, + .{ .t = 28677520229, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25894165, .y = 0.47366333, .pressure = 0.01449585 } } }, + .{ .t = 28688736483, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25906372, .y = 0.47409058, .pressure = 0.015197754 } } }, + .{ .t = 28688747523, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25872803, .y = 0.47351074, .pressure = 0.013061523 } } }, + .{ .t = 28688752063, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25827026, .y = 0.4732666, .pressure = 0.013397217 } } }, + .{ .t = 28699780696, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2581787, .y = 0.47317505, .pressure = 0.014129639 } } }, + .{ .t = 28699788576, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25759888, .y = 0.47305298, .pressure = 0.014831543 } } }, + .{ .t = 28699792416, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25787354, .y = 0.47280884, .pressure = 0.01449585 } } }, + .{ .t = 28711058720, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25784302, .y = 0.47225952, .pressure = 0.013763428 } } }, + .{ .t = 28711073040, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25738525, .y = 0.472229, .pressure = 0.014129639 } } }, + .{ .t = 28722312593, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25720215, .y = 0.4717102, .pressure = 0.013763428 } } }, + .{ .t = 28722328533, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2572937, .y = 0.47213745, .pressure = 0.012329102 } } }, + .{ .t = 28722335123, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2576294, .y = 0.4721985, .pressure = 0.01449585 } } }, + .{ .t = 28733104547, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25784302, .y = 0.4718933, .pressure = 0.013763428 } } }, + .{ .t = 28733113157, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2571411, .y = 0.472229, .pressure = 0.013763428 } } }, + .{ .t = 28733116517, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.256958, .y = 0.47235107, .pressure = 0.010894775 } } }, + .{ .t = 28744542840, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25598145, .y = 0.47323608, .pressure = 0.011962891 } } }, + .{ .t = 28744554360, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25558472, .y = 0.47372437, .pressure = 0.012329102 } } }, + .{ .t = 28744558310, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25463867, .y = 0.47329712, .pressure = 0.013061523 } } }, + .{ .t = 28755164615, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2541809, .y = 0.4736023, .pressure = 0.013397217 } } }, + .{ .t = 28755173055, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2536316, .y = 0.47485352, .pressure = 0.013397217 } } }, + .{ .t = 28766369408, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2527771, .y = 0.4749756, .pressure = 0.011962891 } } }, + .{ .t = 28766376998, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2524109, .y = 0.47543335, .pressure = 0.011962891 } } }, + .{ .t = 28766380848, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2518921, .y = 0.4761963, .pressure = 0.011962891 } } }, + .{ .t = 28777479342, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25073242, .y = 0.4764099, .pressure = 0.013397217 } } }, + .{ .t = 28777487702, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24984741, .y = 0.4772644, .pressure = 0.015197754 } } }, + .{ .t = 28777491542, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24942017, .y = 0.47872925, .pressure = 0.015563965 } } }, + .{ .t = 28788858885, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24816895, .y = 0.47982788, .pressure = 0.016296387 } } }, + .{ .t = 28788869705, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.247406, .y = 0.48181152, .pressure = 0.016998291 } } }, + .{ .t = 28788873665, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24645996, .y = 0.48260498, .pressure = 0.015563965 } } }, + .{ .t = 28800073548, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2456665, .y = 0.48516846, .pressure = 0.01663208 } } }, + .{ .t = 28800082148, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24414062, .y = 0.48757935, .pressure = 0.018432617 } } }, + .{ .t = 28800086718, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2437439, .y = 0.48986816, .pressure = 0.019165039 } } }, + .{ .t = 28810881362, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2432251, .y = 0.49273682, .pressure = 0.017730713 } } }, + .{ .t = 28810890602, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24337769, .y = 0.4951172, .pressure = 0.018432617 } } }, + .{ .t = 28822223135, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24224854, .y = 0.49868774, .pressure = 0.018066406 } } }, + .{ .t = 28822236725, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2409668, .y = 0.5030823, .pressure = 0.018432617 } } }, + .{ .t = 28822243035, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24002075, .y = 0.5093689, .pressure = 0.017364502 } } }, + .{ .t = 28833221849, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.23800659, .y = 0.52023315, .pressure = 0.017364502 } } }, + .{ .t = 28833234799, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.23648071, .y = 0.5312195, .pressure = 0.018066406 } } }, + .{ .t = 28833241859, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.23449707, .y = 0.54260254, .pressure = 0.018432617 } } }, + .{ .t = 28844533292, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.23208618, .y = 0.5539551, .pressure = 0.019165039 } } }, + .{ .t = 28844544902, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22930908, .y = 0.5640869, .pressure = 0.020599365 } } }, + .{ .t = 28844549012, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22769165, .y = 0.5701294, .pressure = 0.022399902 } } }, + .{ .t = 28855315576, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22613525, .y = 0.57528687, .pressure = 0.023468018 } } }, + .{ .t = 28855325516, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22503662, .y = 0.5812073, .pressure = 0.02420044 } } }, + .{ .t = 28866614540, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22335815, .y = 0.5848694, .pressure = 0.02420044 } } }, + .{ .t = 28866626480, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22390747, .y = 0.5887146, .pressure = 0.024536133 } } }, + .{ .t = 28866629910, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22283936, .y = 0.59265137, .pressure = 0.024536133 } } }, + .{ .t = 28877415724, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22262573, .y = 0.59625244, .pressure = 0.025268555 } } }, + .{ .t = 28877428004, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22128296, .y = 0.6008606, .pressure = 0.025268555 } } }, + .{ .t = 28888551597, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2204895, .y = 0.60409546, .pressure = 0.025268555 } } }, + .{ .t = 28888564767, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21896362, .y = 0.61083984, .pressure = 0.025634766 } } }, + .{ .t = 28888571967, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21774292, .y = 0.6156006, .pressure = 0.025970459 } } }, + .{ .t = 28899744701, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21542358, .y = 0.62112427, .pressure = 0.02633667 } } }, + .{ .t = 28899757861, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21438599, .y = 0.62576294, .pressure = 0.027435303 } } }, + .{ .t = 28899764601, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21298218, .y = 0.63223267, .pressure = 0.027069092 } } }, + .{ .t = 28910731865, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21209717, .y = 0.63708496, .pressure = 0.02633667 } } }, + .{ .t = 28910746485, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21133423, .y = 0.6419983, .pressure = 0.02670288 } } }, + .{ .t = 28921990138, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21032715, .y = 0.64730835, .pressure = 0.027435303 } } }, + .{ .t = 28922004158, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2090149, .y = 0.65237427, .pressure = 0.027069092 } } }, + .{ .t = 28922010498, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.20770264, .y = 0.6588135, .pressure = 0.02670288 } } }, + .{ .t = 28932967412, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.20559692, .y = 0.6654968, .pressure = 0.025970459 } } }, + .{ .t = 28932979792, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.20404053, .y = 0.67285156, .pressure = 0.025634766 } } }, + .{ .t = 28932983492, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.20187378, .y = 0.6821594, .pressure = 0.024536133 } } }, + .{ .t = 28944345285, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19940186, .y = 0.6911926, .pressure = 0.02420044 } } }, + .{ .t = 28944363135, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19662476, .y = 0.703949, .pressure = 0.022033691 } } }, + .{ .t = 28944369185, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19250488, .y = 0.71707153, .pressure = 0.02130127 } } }, + .{ .t = 28955070939, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.18859863, .y = 0.7327881, .pressure = 0.020599365 } } }, + .{ .t = 28955080209, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.18469238, .y = 0.7469177, .pressure = 0.018798828 } } }, + .{ .t = 28966644072, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.1803894, .y = 0.76065063, .pressure = 0.018066406 } } }, + .{ .t = 28966660132, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17681885, .y = 0.7729492, .pressure = 0.019165039 } } }, + .{ .t = 28966666102, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17303467, .y = 0.78430176, .pressure = 0.01953125 } } }, + .{ .t = 28977523276, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17047119, .y = 0.79385376, .pressure = 0.019165039 } } }, + .{ .t = 28977533506, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16790771, .y = 0.8000183, .pressure = 0.019866943 } } }, + .{ .t = 28977538756, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16583252, .y = 0.8055115, .pressure = 0.018798828 } } }, + .{ .t = 28988801809, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16448975, .y = 0.8109131, .pressure = 0.01953125 } } }, + .{ .t = 28988815059, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16299438, .y = 0.81552124, .pressure = 0.02130127 } } }, + .{ .t = 28988820159, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16275024, .y = 0.8183899, .pressure = 0.02166748 } } }, + .{ .t = 29000005933, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16235352, .y = 0.8191223, .pressure = 0.022399902 } } }, + .{ .t = 29000020133, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16220093, .y = 0.820343, .pressure = 0.023468018 } } }, + .{ .t = 29000023943, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16268921, .y = 0.8208618, .pressure = 0.023834229 } } }, + .{ .t = 29010879647, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.1618042, .y = 0.82214355, .pressure = 0.025634766 } } }, + .{ .t = 29010893477, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16238403, .y = 0.82196045, .pressure = 0.02633667 } } }, + .{ .t = 29022239700, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16329956, .y = 0.82180786, .pressure = 0.027069092 } } }, + .{ .t = 29022255010, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16305542, .y = 0.8227539, .pressure = 0.027069092 } } }, + .{ .t = 29022260530, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16360474, .y = 0.8215027, .pressure = 0.02670288 } } }, + .{ .t = 29033423863, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16390991, .y = 0.8215637, .pressure = 0.02670288 } } }, + .{ .t = 29033439393, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16513062, .y = 0.820282, .pressure = 0.02633667 } } }, + .{ .t = 29033446553, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16571045, .y = 0.82003784, .pressure = 0.027069092 } } }, + .{ .t = 29044100787, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16552734, .y = 0.81985474, .pressure = 0.024536133 } } }, + .{ .t = 29044110747, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16653442, .y = 0.8192444, .pressure = 0.023468018 } } }, + .{ .t = 29044114927, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16690063, .y = 0.81710815, .pressure = 0.023101807 } } }, + .{ .t = 29055305531, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16772461, .y = 0.81536865, .pressure = 0.022766113 } } }, + .{ .t = 29055315751, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16854858, .y = 0.81365967, .pressure = 0.022399902 } } }, + .{ .t = 29066613054, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.16940308, .y = 0.811615, .pressure = 0.02166748 } } }, + .{ .t = 29066629614, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17041016, .y = 0.80908203, .pressure = 0.02130127 } } }, + .{ .t = 29066636804, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17147827, .y = 0.8067322, .pressure = 0.02130127 } } }, + .{ .t = 29077513018, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17288208, .y = 0.8036804, .pressure = 0.019165039 } } }, + .{ .t = 29077525768, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17391968, .y = 0.8003235, .pressure = 0.015197754 } } }, + .{ .t = 29077531158, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17553711, .y = 0.7965088, .pressure = 0.014831543 } } }, + .{ .t = 29088910511, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17697144, .y = 0.7913208, .pressure = 0.015563965 } } }, + .{ .t = 29088924801, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17819214, .y = 0.78622437, .pressure = 0.01449585 } } }, + .{ .t = 29088930391, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.17999268, .y = 0.7813721, .pressure = 0.013397217 } } }, + .{ .t = 29100047575, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.18148804, .y = 0.7752991, .pressure = 0.014129639 } } }, + .{ .t = 29100061535, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.1831665, .y = 0.76898193, .pressure = 0.014129639 } } }, + .{ .t = 29100068045, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.184906, .y = 0.7624817, .pressure = 0.013763428 } } }, + .{ .t = 29111067488, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.18692017, .y = 0.7561035, .pressure = 0.013061523 } } }, + .{ .t = 29111083948, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.18884277, .y = 0.7487488, .pressure = 0.01449585 } } }, + .{ .t = 29122288972, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19082642, .y = 0.7409973, .pressure = 0.01449585 } } }, + .{ .t = 29122305542, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19223022, .y = 0.73428345, .pressure = 0.014831543 } } }, + .{ .t = 29122313342, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19274902, .y = 0.7257385, .pressure = 0.014831543 } } }, + .{ .t = 29133328146, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19299316, .y = 0.714447, .pressure = 0.015197754 } } }, + .{ .t = 29133345356, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.1928711, .y = 0.7018738, .pressure = 0.01449585 } } }, + .{ .t = 29133350306, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19335938, .y = 0.6808777, .pressure = 0.014831543 } } }, + .{ .t = 29144200749, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19464111, .y = 0.65582275, .pressure = 0.014831543 } } }, + .{ .t = 29144216579, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19668579, .y = 0.63186646, .pressure = 0.01449585 } } }, + .{ .t = 29144223419, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.19927979, .y = 0.6045227, .pressure = 0.013763428 } } }, + .{ .t = 29154998954, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.20211792, .y = 0.57891846, .pressure = 0.0126953125 } } }, + .{ .t = 29155006203, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.20501709, .y = 0.551239, .pressure = 0.0126953125 } } }, + .{ .t = 29166393667, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.20880127, .y = 0.5248718, .pressure = 0.012329102 } } }, + .{ .t = 29166404147, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21270752, .y = 0.499115, .pressure = 0.013397217 } } }, + .{ .t = 29166409197, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.21655273, .y = 0.47366333, .pressure = 0.013763428 } } }, + .{ .t = 29177500380, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2204895, .y = 0.45114136, .pressure = 0.0101623535 } } }, + .{ .t = 29177510970, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.22451782, .y = 0.4290161, .pressure = 0.0101623535 } } }, + .{ .t = 29177516230, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2286377, .y = 0.40975952, .pressure = 0.0101623535 } } }, + .{ .t = 29188832983, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.23208618, .y = 0.39212036, .pressure = 0.010528564 } } }, + .{ .t = 29188846483, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.23532104, .y = 0.375885, .pressure = 0.007293701 } } }, + .{ .t = 29188851103, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.23809814, .y = 0.35943604, .pressure = 0.009460449 } } }, + .{ .t = 29200021967, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24072266, .y = 0.34292603, .pressure = 0.011260986 } } }, + .{ .t = 29200037067, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24298096, .y = 0.32809448, .pressure = 0.011962891 } } }, + .{ .t = 29200042877, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24493408, .y = 0.3138733, .pressure = 0.010528564 } } }, + .{ .t = 29210884631, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24728394, .y = 0.29989624, .pressure = 0.012329102 } } }, + .{ .t = 29221881625, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.24908447, .y = 0.2866516, .pressure = 0.011962891 } } }, + .{ .t = 29221891355, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.250885, .y = 0.2755432, .pressure = 0.010528564 } } }, + .{ .t = 29221896615, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.252594, .y = 0.26571655, .pressure = 0.011962891 } } }, + .{ .t = 29233293918, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25378418, .y = 0.2571106, .pressure = 0.0126953125 } } }, + .{ .t = 29233306418, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25476074, .y = 0.24942017, .pressure = 0.0126953125 } } }, + .{ .t = 29233312238, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25534058, .y = 0.24307251, .pressure = 0.011260986 } } }, + .{ .t = 29244359261, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25610352, .y = 0.23760986, .pressure = 0.0101623535 } } }, + .{ .t = 29244375081, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25680542, .y = 0.23291016, .pressure = 0.0101623535 } } }, + .{ .t = 29244383211, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25750732, .y = 0.22824097, .pressure = 0.0101623535 } } }, + .{ .t = 29255381715, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25823975, .y = 0.22570801, .pressure = 0.007659912 } } }, + .{ .t = 29255392615, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.25909424, .y = 0.2234497, .pressure = 0.007293701 } } }, + .{ .t = 29266740458, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.2599182, .y = 0.22180176, .pressure = 0.006225586 } } }, + .{ .t = 29266753748, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.26089478, .y = 0.22140503, .pressure = 0.0051574707 } } }, + .{ .t = 29266758978, .pad = 2, .ev = .{ .touch = .{ .touchpad = 0, .finger = 0, .phase = .motion, .x = 0.26275635, .y = 0.22149658, .pressure = 0.0033569336 } } }, } } diff --git a/test/deck/replay.zig b/test/deck/replay.zig index 49614b46..778f4191 100644 --- a/test/deck/replay.zig +++ b/test/deck/replay.zig @@ -45,12 +45,12 @@ fn replay(src: [:0]const u8) !Tally { tally.max_step = @max(tally.max_step, @max(@abs(mv.dx), @abs(mv.dy))); }, .click => |ck| if (ck.down) { - tally.click_down[@intFromEnum(ck.which)] += 1; + tally.click_down[@backingInt(ck.which)] += 1; } else { - tally.click_up[@intFromEnum(ck.which)] += 1; + tally.click_up[@backingInt(ck.which)] += 1; }, .wheel => |ticks| tally.wheel += ticks, - .key => |k| tally.keys[@intFromEnum(k)] += 1, + .key => |k| tally.keys[@backingInt(k)] += 1, .rumble => tally.rumbles += 1, }; } @@ -72,7 +72,7 @@ test "right-pad drag moves the pointer, fresh touches don't jump" { try std.testing.expectEqual(0, t.wheel); // a light-touch drag stays well under the click threshold — no phantom // select clicks (nor their rumble) - try std.testing.expectEqual(0, t.click_down[@intFromEnum(deck.Click.select)]); + try std.testing.expectEqual(0, t.click_down[@backingInt(deck.Click.select)]); try std.testing.expectEqual(0, t.rumbles); } @@ -82,11 +82,11 @@ test "trigger pull+release clicks exactly once each" { // through dozens of intermediate values, interleaved with ~500 stick // axis events: hysteresis must yield exactly one click apiece, only // the execute pull rumbles, and the sticks produce nothing - try std.testing.expectEqual(1, t.click_down[@intFromEnum(deck.Click.select)]); - try std.testing.expectEqual(1, t.click_up[@intFromEnum(deck.Click.select)]); - try std.testing.expectEqual(1, t.click_down[@intFromEnum(deck.Click.execute)]); - try std.testing.expectEqual(1, t.click_up[@intFromEnum(deck.Click.execute)]); - try std.testing.expectEqual(0, t.click_down[@intFromEnum(deck.Click.look)]); + try std.testing.expectEqual(1, t.click_down[@backingInt(deck.Click.select)]); + try std.testing.expectEqual(1, t.click_up[@backingInt(deck.Click.select)]); + try std.testing.expectEqual(1, t.click_down[@backingInt(deck.Click.execute)]); + try std.testing.expectEqual(1, t.click_up[@backingInt(deck.Click.execute)]); + try std.testing.expectEqual(0, t.click_down[@backingInt(deck.Click.look)]); try std.testing.expectEqual(1, t.rumbles); try std.testing.expectEqual(0, t.moves); } @@ -100,7 +100,7 @@ test "left-pad swipe scrolls" { try std.testing.expectEqual(5, t.wheel); try std.testing.expectEqual(0, t.moves); // the swipe presses lightly — no phantom look clicks - try std.testing.expectEqual(0, t.click_down[@intFromEnum(deck.Click.look)]); + try std.testing.expectEqual(0, t.click_down[@backingInt(deck.Click.look)]); try std.testing.expectEqual(0, t.rumbles); } @@ -166,15 +166,15 @@ test "buttons: dpad n/N, A Enter, Y Tab, L1 look + rumble" { const t = try replay(@embedFile("buttons.zon")); // every button press of a real all-buttons sweep: dpad-down x1, // dpad-up x3, A x2, Y x5, L1 x3; the other buttons map to nothing - try std.testing.expectEqual(1, t.keys[@intFromEnum(deck.Keytap.n)]); - try std.testing.expectEqual(3, t.keys[@intFromEnum(deck.Keytap.cap_n)]); - try std.testing.expectEqual(2, t.keys[@intFromEnum(deck.Keytap.enter)]); - try std.testing.expectEqual(5, t.keys[@intFromEnum(deck.Keytap.tab)]); - try std.testing.expectEqual(3, t.click_down[@intFromEnum(deck.Click.look)]); - try std.testing.expectEqual(3, t.click_up[@intFromEnum(deck.Click.look)]); + try std.testing.expectEqual(1, t.keys[@backingInt(deck.Keytap.n)]); + try std.testing.expectEqual(3, t.keys[@backingInt(deck.Keytap.cap_n)]); + try std.testing.expectEqual(2, t.keys[@backingInt(deck.Keytap.enter)]); + try std.testing.expectEqual(5, t.keys[@backingInt(deck.Keytap.tab)]); + try std.testing.expectEqual(3, t.click_down[@backingInt(deck.Click.look)]); + try std.testing.expectEqual(3, t.click_up[@backingInt(deck.Click.look)]); try std.testing.expectEqual(3, t.rumbles); - try std.testing.expectEqual(0, t.click_down[@intFromEnum(deck.Click.select)]); - try std.testing.expectEqual(0, t.click_down[@intFromEnum(deck.Click.execute)]); + try std.testing.expectEqual(0, t.click_down[@backingInt(deck.Click.select)]); + try std.testing.expectEqual(0, t.click_down[@backingInt(deck.Click.execute)]); try std.testing.expectEqual(0, t.moves); try std.testing.expectEqual(0, t.wheel); } diff --git a/test/deck/rpad-drag.zon b/test/deck/rpad-drag.zon index 20dea6ef..c7a82db9 100644 --- a/test/deck/rpad-drag.zon +++ b/test/deck/rpad-drag.zon @@ -1,223 +1,223 @@ .{ .version = 1, .events = .{ -.{.t=1557743788,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.down,.x=0.48794556,.y=0.3156128,.pressure=0.0004272461}}}, -.{.t=1557747308,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.49105835,.y=0.31570435,.pressure=0.0015563965}}}, -.{.t=1568667061,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.49325562,.y=0.31576538,.pressure=0.004638672}}}, -.{.t=1568677161,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.49591064,.y=0.31585693,.pressure=0.0035095215}}}, -.{.t=1568682171,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.4988098,.y=0.31588745,.pressure=0.0026855469}}}, -.{.t=1579851545,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.50076294,.y=0.31607056,.pressure=0.004638672}}}, -.{.t=1579859265,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.50289917,.y=0.31637573,.pressure=0.0063171387}}}, -.{.t=1579863375,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5050354,.y=0.31655884,.pressure=0.008026123}}}, -.{.t=1590959349,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.50717163,.y=0.31655884,.pressure=0.0063171387}}}, -.{.t=1590970369,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.50927734,.y=0.31698608,.pressure=0.0040893555}}}, -.{.t=1590975739,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5108948,.y=0.31750488,.pressure=0.0038146973}}}, -.{.t=1601902982,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5126953,.y=0.31808472,.pressure=0.005218506}}}, -.{.t=1601911482,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.51400757,.y=0.318573,.pressure=0.0066223145}}}, -.{.t=1613345665,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.51571655,.y=0.31878662,.pressure=0.007171631}}}, -.{.t=1613352235,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.51660156,.y=0.31936646,.pressure=0.0068969727}}}, -.{.t=1613356725,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5178528,.y=0.3199463,.pressure=0.0066223145}}}, -.{.t=1624412039,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5187378,.y=0.3206787,.pressure=0.0057678223}}}, -.{.t=1624425589,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.52023315,.y=0.32138062,.pressure=0.0043640137}}}, -.{.t=1624432009,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5215454,.y=0.3218689,.pressure=0.0040893555}}}, -.{.t=1635289123,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5227356,.y=0.3222351,.pressure=0.0018310547}}}, -.{.t=1635297503,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.52371216,.y=0.3229065,.pressure=0.0026855469}}}, -.{.t=1635301553,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5246887,.y=0.3234558,.pressure=0.002105713}}}, -.{.t=1646425097,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.52545166,.y=0.323761,.pressure=0.0007019043}}}, -.{.t=1646433957,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.up,.x=0.5263977,.y=0.3241577,.pressure=0}}}, -.{.t=1657611170,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.down,.x=0.52749634,.y=0.32489014,.pressure=0.0004272461}}}, -.{.t=1657620700,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.up,.x=0.52893066,.y=0.32543945,.pressure=0}}}, -.{.t=2568455904,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.down,.x=0.71746826,.y=0.4960022,.pressure=0.0026855469}}}, -.{.t=2568464274,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.72143555,.y=0.49996948,.pressure=0.0032348633}}}, -.{.t=2568468384,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.72436523,.y=0.5033264,.pressure=0.004638672}}}, -.{.t=2579442397,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7271118,.y=0.5065918,.pressure=0.0066223145}}}, -.{.t=2579450697,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.73065186,.y=0.51031494,.pressure=0.008850098}}}, -.{.t=2579455357,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7350464,.y=0.5145569,.pressure=0.010253906}}}, -.{.t=2590631621,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.74017334,.y=0.51916504,.pressure=0.012512207}}}, -.{.t=2590639051,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7455139,.y=0.52420044,.pressure=0.014190674}}}, -.{.t=2601728264,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7537842,.y=0.5307617,.pressure=0.01727295}}}, -.{.t=2601737594,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.76501465,.y=0.5390625,.pressure=0.017852783}}}, -.{.t=2601745184,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7758789,.y=0.54782104,.pressure=0.017578125}}}, -.{.t=2612868798,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.78726196,.y=0.55740356,.pressure=0.018676758}}}, -.{.t=2612877548,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.79766846,.y=0.56655884,.pressure=0.016998291}}}, -.{.t=2612881858,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8077698,.y=0.57421875,.pressure=0.016174316}}}, -.{.t=2624096121,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.81689453,.y=0.5804138,.pressure=0.0184021}}}, -.{.t=2624103861,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8230896,.y=0.58462524,.pressure=0.017578125}}}, -.{.t=2624108371,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8291321,.y=0.58810425,.pressure=0.016448975}}}, -.{.t=2635100225,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8328247,.y=0.5901184,.pressure=0.015594482}}}, -.{.t=2635107345,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.835022,.y=0.59017944,.pressure=0.016174316}}}, -.{.t=2635111905,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.83724976,.y=0.5899353,.pressure=0.016174316}}}, -.{.t=2646151229,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8390808,.y=0.5890198,.pressure=0.014770508}}}, -.{.t=2646160149,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8404541,.y=0.58709717,.pressure=0.014190674}}}, -.{.t=2657358812,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8408203,.y=0.58535767,.pressure=0.016448975}}}, -.{.t=2657364952,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8411865,.y=0.5831604,.pressure=0.015045166}}}, -.{.t=2657368602,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.84106445,.y=0.5809021,.pressure=0.0184021}}}, -.{.t=2668497496,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.84155273,.y=0.5791321,.pressure=0.018676758}}}, -.{.t=2668503176,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.84198,.y=0.5767517,.pressure=0.0184021}}}, -.{.t=2679574619,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8413696,.y=0.5749817,.pressure=0.01727295}}}, -.{.t=2679583429,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8410034,.y=0.57302856,.pressure=0.015594482}}}, -.{.t=2679588959,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8402405,.y=0.57077026,.pressure=0.016998291}}}, -.{.t=2690585493,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.83987427,.y=0.5680237,.pressure=0.017578125}}}, -.{.t=2690591573,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8392639,.y=0.5658264,.pressure=0.016998291}}}, -.{.t=2701710277,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8384094,.y=0.56329346,.pressure=0.015045166}}}, -.{.t=2701715427,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8366089,.y=0.5602722,.pressure=0.012512207}}}, -.{.t=2701719287,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8343506,.y=0.55578613,.pressure=0.013641357}}}, -.{.t=2712932260,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8309326,.y=0.5510254,.pressure=0.012512207}}}, -.{.t=2712941600,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8270569,.y=0.54504395,.pressure=0.013641357}}}, -.{.t=2712946870,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.82263184,.y=0.53845215,.pressure=0.012786865}}}, -.{.t=2724074464,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8186035,.y=0.5309448,.pressure=0.012237549}}}, -.{.t=2724081034,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8176575,.y=0.5210266,.pressure=0.011383057}}}, -.{.t=2724085114,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8161926,.y=0.5109863,.pressure=0.010253906}}}, -.{.t=2735041467,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.81481934,.y=0.49887085,.pressure=0.008575439}}}, -.{.t=2735049697,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8135681,.y=0.48706055,.pressure=0.0066223145}}}, -.{.t=2735053437,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8110962,.y=0.47451782,.pressure=0.0066223145}}}, -.{.t=2746200461,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8079529,.y=0.46011353,.pressure=0.008300781}}}, -.{.t=2746207531,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8046875,.y=0.44818115,.pressure=0.008850098}}}, -.{.t=2757301144,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.8004761,.y=0.4363098,.pressure=0.010253906}}}, -.{.t=2757308574,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.796051,.y=0.4248352,.pressure=0.009979248}}}, -.{.t=2757312724,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.79104614,.y=0.4133911,.pressure=0.013366699}}}, -.{.t=2775948317,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.78637695,.y=0.4032898,.pressure=0.012237549}}}, -.{.t=2775958817,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.78131104,.y=0.39471436,.pressure=0.015045166}}}, -.{.t=2775962507,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7763977,.y=0.38796997,.pressure=0.016723633}}}, -.{.t=2775966007,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.77178955,.y=0.38198853,.pressure=0.018127441}}}, -.{.t=2775969667,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.76724243,.y=0.37753296,.pressure=0.019805908}}}, -.{.t=2779448262,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7628784,.y=0.37338257,.pressure=0.018127441}}}, -.{.t=2790559265,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.75909424,.y=0.36990356,.pressure=0.020935059}}}, -.{.t=2790566225,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.75512695,.y=0.36654663,.pressure=0.021484375}}}, -.{.t=2801688299,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7513733,.y=0.36395264,.pressure=0.020385742}}}, -.{.t=2801695099,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7475891,.y=0.36190796,.pressure=0.020385742}}}, -.{.t=2801697739,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.74487305,.y=0.35958862,.pressure=0.020385742}}}, -.{.t=2812906962,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.74191284,.y=0.3572998,.pressure=0.022888184}}}, -.{.t=2812918202,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7388611,.y=0.35458374,.pressure=0.022338867}}}, -.{.t=2812924662,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7357178,.y=0.35250854,.pressure=0.021209717}}}, -.{.t=2824054786,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7324829,.y=0.3503418,.pressure=0.021484375}}}, -.{.t=2824059786,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7289429,.y=0.3484497,.pressure=0.022888184}}}, -.{.t=2824063716,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.72506714,.y=0.34591675,.pressure=0.022613525}}}, -.{.t=2835063039,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7218323,.y=0.34277344,.pressure=0.02319336}}}, -.{.t=2835070099,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7174072,.y=0.34020996,.pressure=0.020080566}}}, -.{.t=2835075929,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.71273804,.y=0.33743286,.pressure=0.020080566}}}, -.{.t=2846116163,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7079773,.y=0.3343506,.pressure=0.018676758}}}, -.{.t=2846123943,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7023926,.y=0.33081055,.pressure=0.019805908}}}, -.{.t=2857453356,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6963806,.y=0.32598877,.pressure=0.019805908}}}, -.{.t=2857460036,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6892395,.y=0.32144165,.pressure=0.020935059}}}, -.{.t=2857466116,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6821289,.y=0.31661987,.pressure=0.018127441}}}, -.{.t=2868624580,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6739197,.y=0.31192017,.pressure=0.018676758}}}, -.{.t=2868632160,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6664429,.y=0.3072815,.pressure=0.018981934}}}, -.{.t=2868637550,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6587219,.y=0.30307007,.pressure=0.017578125}}}, -.{.t=2879637654,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.65133667,.y=0.29888916,.pressure=0.017852783}}}, -.{.t=2879646144,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6444702,.y=0.29452515,.pressure=0.017852783}}}, -.{.t=2879653574,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6372986,.y=0.29092407,.pressure=0.016174316}}}, -.{.t=2890493398,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6305542,.y=0.28729248,.pressure=0.016448975}}}, -.{.t=2890500368,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.62493896,.y=0.28427124,.pressure=0.016448975}}}, -.{.t=2901904031,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6192627,.y=0.28234863,.pressure=0.015594482}}}, -.{.t=2901913451,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.61428833,.y=0.27990723,.pressure=0.014190674}}}, -.{.t=2901920201,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6097412,.y=0.277771,.pressure=0.013641357}}}, -.{.t=2913077524,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6056824,.y=0.27627563,.pressure=0.013641357}}}, -.{.t=2913084054,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6019287,.y=0.27560425,.pressure=0.012512207}}}, -.{.t=2913088274,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5984192,.y=0.27441406,.pressure=0.011657715}}}, -.{.t=2924138128,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.59536743,.y=0.27404785,.pressure=0.011962891}}}, -.{.t=2924146018,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5923767,.y=0.27398682,.pressure=0.013641357}}}, -.{.t=2924151648,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5900574,.y=0.2736206,.pressure=0.013366699}}}, -.{.t=2935179332,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5883484,.y=0.27407837,.pressure=0.014465332}}}, -.{.t=2935187861,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5866394,.y=0.27478027,.pressure=0.01586914}}}, -.{.t=2935191171,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.58551025,.y=0.2756958,.pressure=0.015045166}}}, -.{.t=2946370475,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5841675,.y=0.27648926,.pressure=0.01727295}}}, -.{.t=2946379375,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5830078,.y=0.27764893,.pressure=0.0184021}}}, -.{.t=2957467849,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5821533,.y=0.278656,.pressure=0.01953125}}}, -.{.t=2957477449,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5817566,.y=0.28030396,.pressure=0.016998291}}}, -.{.t=2957483529,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.58148193,.y=0.28225708,.pressure=0.015319824}}}, -.{.t=2968627182,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5809021,.y=0.2843933,.pressure=0.01586914}}}, -.{.t=2968643772,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.580719,.y=0.28659058,.pressure=0.014190674}}}, -.{.t=2979684996,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5805969,.y=0.28967285,.pressure=0.013641357}}}, -.{.t=2979694336,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.58026123,.y=0.29241943,.pressure=0.010559082}}}, -.{.t=2979699086,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.57995605,.y=0.29571533,.pressure=0.008575439}}}, -.{.t=2990715289,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.57958984,.y=0.29934692,.pressure=0.010253906}}}, -.{.t=2990723719,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5793457,.y=0.30322266,.pressure=0.008300781}}}, -.{.t=3002153093,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5791931,.y=0.30700684,.pressure=0.0060424805}}}, -.{.t=3002161152,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5791931,.y=0.3117981,.pressure=0.0060424805}}}, -.{.t=3002165632,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.57958984,.y=0.3164673,.pressure=0.00491333}}}, -.{.t=3012982186,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5806885,.y=0.3215027,.pressure=0.0068969727}}}, -.{.t=3012991236,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5819702,.y=0.32669067,.pressure=0.0057678223}}}, -.{.t=3012998166,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5845032,.y=0.3322754,.pressure=0.007446289}}}, -.{.t=3024201460,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5869446,.y=0.33740234,.pressure=0.008026123}}}, -.{.t=3024208990,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.59017944,.y=0.34225464,.pressure=0.009155273}}}, -.{.t=3024211980,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.5932617,.y=0.34698486,.pressure=0.012237549}}}, -.{.t=3035025244,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.59643555,.y=0.3517456,.pressure=0.013366699}}}, -.{.t=3035031374,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6001282,.y=0.35601807,.pressure=0.016998291}}}, -.{.t=3035034874,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.60409546,.y=0.3600464,.pressure=0.019805908}}}, -.{.t=3046541367,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.60775757,.y=0.36398315,.pressure=0.022338867}}}, -.{.t=3046548887,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.61169434,.y=0.36740112,.pressure=0.022613525}}}, -.{.t=3057532891,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6154785,.y=0.37051392,.pressure=0.025146484}}}, -.{.t=3057540471,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6194763,.y=0.37329102,.pressure=0.025421143}}}, -.{.t=3057545781,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6232605,.y=0.3761902,.pressure=0.026000977}}}, -.{.t=3068735374,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.62753296,.y=0.3789673,.pressure=0.025421143}}}, -.{.t=3068748304,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6313782,.y=0.3816223,.pressure=0.024017334}}}, -.{.t=3068754594,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.63513184,.y=0.38391113,.pressure=0.023742676}}}, -.{.t=3079554878,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6390991,.y=0.38616943,.pressure=0.023468018}}}, -.{.t=3079563518,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6433716,.y=0.38833618,.pressure=0.02178955}}}, -.{.t=3079568338,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.64767456,.y=0.39031982,.pressure=0.02319336}}}, -.{.t=3090741042,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.65234375,.y=0.3919983,.pressure=0.02319336}}}, -.{.t=3090749882,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.65689087,.y=0.39379883,.pressure=0.021209717}}}, -.{.t=3101724975,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6610718,.y=0.39520264,.pressure=0.022888184}}}, -.{.t=3101732005,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.66574097,.y=0.39642334,.pressure=0.021484375}}}, -.{.t=3101735255,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6701355,.y=0.3973999,.pressure=0.019805908}}}, -.{.t=3113361458,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6748352,.y=0.39767456,.pressure=0.0206604}}}, -.{.t=3113368498,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.67944336,.y=0.39797974,.pressure=0.022613525}}}, -.{.t=3113372028,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6838379,.y=0.39785767,.pressure=0.022338867}}}, -.{.t=3123796833,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6879883,.y=0.3970642,.pressure=0.01953125}}}, -.{.t=3123803053,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.69177246,.y=0.39624023,.pressure=0.018127441}}}, -.{.t=3123806563,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.69555664,.y=0.39569092,.pressure=0.016998291}}}, -.{.t=3134998596,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.69888306,.y=0.3942871,.pressure=0.016998291}}}, -.{.t=3135007066,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7023926,.y=0.39257812,.pressure=0.017578125}}}, -.{.t=3135011336,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7060852,.y=0.39056396,.pressure=0.017578125}}}, -.{.t=3146195970,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7102051,.y=0.38861084,.pressure=0.015594482}}}, -.{.t=3146202620,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.715271,.y=0.386261,.pressure=0.014190674}}}, -.{.t=3157408853,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7234802,.y=0.38327026,.pressure=0.01586914}}}, -.{.t=3157418073,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.730896,.y=0.38006592,.pressure=0.01586914}}}, -.{.t=3157423313,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.73880005,.y=0.37652588,.pressure=0.016448975}}}, -.{.t=3168334437,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.74557495,.y=0.37350464,.pressure=0.017578125}}}, -.{.t=3168341357,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.75097656,.y=0.37020874,.pressure=0.016723633}}}, -.{.t=3168344697,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7561035,.y=0.36791992,.pressure=0.013916016}}}, -.{.t=3179518520,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.75982666,.y=0.36517334,.pressure=0.013061523}}}, -.{.t=3179524910,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7633362,.y=0.3623352,.pressure=0.013061523}}}, -.{.t=3179530860,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.765625,.y=0.35949707,.pressure=0.013641357}}}, -.{.t=3190702424,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7669678,.y=0.3564453,.pressure=0.012786865}}}, -.{.t=3190710904,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.76849365,.y=0.3536682,.pressure=0.011383057}}}, -.{.t=3201886237,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7687378,.y=0.35095215,.pressure=0.010559082}}}, -.{.t=3201895897,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7681885,.y=0.34838867,.pressure=0.009155273}}}, -.{.t=3201900097,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7668457,.y=0.34570312,.pressure=0.009155273}}}, -.{.t=3212919591,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7654724,.y=0.34277344,.pressure=0.008850098}}}, -.{.t=3212927311,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7631836,.y=0.34002686,.pressure=0.0066223145}}}, -.{.t=3212932591,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7612915,.y=0.3373413,.pressure=0.0040893555}}}, -.{.t=3224127654,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7590027,.y=0.33529663,.pressure=0.0043640137}}}, -.{.t=3224134564,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7567444,.y=0.33319092,.pressure=0.0024108887}}}, -.{.t=3224138834,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7541809,.y=0.3307495,.pressure=0.00491333}}}, -.{.t=3234961798,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.75216675,.y=0.32843018,.pressure=0.0038146973}}}, -.{.t=3234967628,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7489929,.y=0.32583618,.pressure=0.0038146973}}}, -.{.t=3234971398,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7467346,.y=0.32296753,.pressure=0.005218506}}}, -.{.t=3246367272,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7436218,.y=0.32019043,.pressure=0.0043640137}}}, -.{.t=3246376701,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7402649,.y=0.3173523,.pressure=0.0038146973}}}, -.{.t=3257870675,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.73721313,.y=0.31466675,.pressure=0.0018310547}}}, -.{.t=3257881104,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7336731,.y=0.31219482,.pressure=0.0024108887}}}, -.{.t=3257886264,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.73062134,.y=0.3100891,.pressure=0.0015563965}}}, -.{.t=3268291019,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.72720337,.y=0.30807495,.pressure=0.0007019043}}}, -.{.t=3268298969,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7241516,.y=0.30593872,.pressure=0.0015563965}}}, -.{.t=3268303569,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7213135,.y=0.30371094,.pressure=0.0035095215}}}, -.{.t=3279746522,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.71810913,.y=0.302063,.pressure=0.002960205}}}, -.{.t=3279757542,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.7147217,.y=0.30056763,.pressure=0.00491333}}}, -.{.t=3279762862,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.71087646,.y=0.29907227,.pressure=0.00491333}}}, -.{.t=3290574016,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.70751953,.y=0.29745483,.pressure=0.0040893555}}}, -.{.t=3290581596,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.70376587,.y=0.29592896,.pressure=0.0040893555}}}, -.{.t=3301750300,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6994934,.y=0.2951355,.pressure=0.0038146973}}}, -.{.t=3301760370,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6951904,.y=0.29397583,.pressure=0.005218506}}}, -.{.t=3301767410,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6905823,.y=0.29284668,.pressure=0.00491333}}}, -.{.t=3312951293,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.685791,.y=0.29266357,.pressure=0.0068969727}}}, -.{.t=3312959893,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.68136597,.y=0.29257202,.pressure=0.005493164}}}, -.{.t=3312965373,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6772461,.y=0.29229736,.pressure=0.0068969727}}}, -.{.t=3324079267,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.672699,.y=0.29318237,.pressure=0.004638672}}}, -.{.t=3324090337,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.66882324,.y=0.294281,.pressure=0.004638672}}}, -.{.t=3324095997,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.66537476,.y=0.29525757,.pressure=0.004638672}}}, -.{.t=3335061800,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6620178,.y=0.2966919,.pressure=0.002960205}}}, -.{.t=3335068160,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6590576,.y=0.29788208,.pressure=0.0007019043}}}, -.{.t=3335073750,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.up,.x=0.6562805,.y=0.29956055,.pressure=0}}}, -.{.t=3390587188,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.down,.x=0.6447449,.y=0.33596802,.pressure=0.0007019043}}}, -.{.t=3390593138,.pad=2,.ev=.{.touch=.{.touchpad=1,.finger=0,.phase=.motion,.x=0.6447754,.y=0.3406067,.pressure=0.0035095215}}}, + .{ .t = 1557743788, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .down, .x = 0.48794556, .y = 0.3156128, .pressure = 0.0004272461 } } }, + .{ .t = 1557747308, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.49105835, .y = 0.31570435, .pressure = 0.0015563965 } } }, + .{ .t = 1568667061, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.49325562, .y = 0.31576538, .pressure = 0.004638672 } } }, + .{ .t = 1568677161, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.49591064, .y = 0.31585693, .pressure = 0.0035095215 } } }, + .{ .t = 1568682171, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.4988098, .y = 0.31588745, .pressure = 0.0026855469 } } }, + .{ .t = 1579851545, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.50076294, .y = 0.31607056, .pressure = 0.004638672 } } }, + .{ .t = 1579859265, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.50289917, .y = 0.31637573, .pressure = 0.0063171387 } } }, + .{ .t = 1579863375, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5050354, .y = 0.31655884, .pressure = 0.008026123 } } }, + .{ .t = 1590959349, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.50717163, .y = 0.31655884, .pressure = 0.0063171387 } } }, + .{ .t = 1590970369, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.50927734, .y = 0.31698608, .pressure = 0.0040893555 } } }, + .{ .t = 1590975739, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5108948, .y = 0.31750488, .pressure = 0.0038146973 } } }, + .{ .t = 1601902982, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5126953, .y = 0.31808472, .pressure = 0.005218506 } } }, + .{ .t = 1601911482, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.51400757, .y = 0.318573, .pressure = 0.0066223145 } } }, + .{ .t = 1613345665, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.51571655, .y = 0.31878662, .pressure = 0.007171631 } } }, + .{ .t = 1613352235, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.51660156, .y = 0.31936646, .pressure = 0.0068969727 } } }, + .{ .t = 1613356725, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5178528, .y = 0.3199463, .pressure = 0.0066223145 } } }, + .{ .t = 1624412039, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5187378, .y = 0.3206787, .pressure = 0.0057678223 } } }, + .{ .t = 1624425589, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.52023315, .y = 0.32138062, .pressure = 0.0043640137 } } }, + .{ .t = 1624432009, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5215454, .y = 0.3218689, .pressure = 0.0040893555 } } }, + .{ .t = 1635289123, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5227356, .y = 0.3222351, .pressure = 0.0018310547 } } }, + .{ .t = 1635297503, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.52371216, .y = 0.3229065, .pressure = 0.0026855469 } } }, + .{ .t = 1635301553, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5246887, .y = 0.3234558, .pressure = 0.002105713 } } }, + .{ .t = 1646425097, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.52545166, .y = 0.323761, .pressure = 0.0007019043 } } }, + .{ .t = 1646433957, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .up, .x = 0.5263977, .y = 0.3241577, .pressure = 0 } } }, + .{ .t = 1657611170, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .down, .x = 0.52749634, .y = 0.32489014, .pressure = 0.0004272461 } } }, + .{ .t = 1657620700, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .up, .x = 0.52893066, .y = 0.32543945, .pressure = 0 } } }, + .{ .t = 2568455904, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .down, .x = 0.71746826, .y = 0.4960022, .pressure = 0.0026855469 } } }, + .{ .t = 2568464274, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.72143555, .y = 0.49996948, .pressure = 0.0032348633 } } }, + .{ .t = 2568468384, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.72436523, .y = 0.5033264, .pressure = 0.004638672 } } }, + .{ .t = 2579442397, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7271118, .y = 0.5065918, .pressure = 0.0066223145 } } }, + .{ .t = 2579450697, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.73065186, .y = 0.51031494, .pressure = 0.008850098 } } }, + .{ .t = 2579455357, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7350464, .y = 0.5145569, .pressure = 0.010253906 } } }, + .{ .t = 2590631621, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.74017334, .y = 0.51916504, .pressure = 0.012512207 } } }, + .{ .t = 2590639051, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7455139, .y = 0.52420044, .pressure = 0.014190674 } } }, + .{ .t = 2601728264, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7537842, .y = 0.5307617, .pressure = 0.01727295 } } }, + .{ .t = 2601737594, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.76501465, .y = 0.5390625, .pressure = 0.017852783 } } }, + .{ .t = 2601745184, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7758789, .y = 0.54782104, .pressure = 0.017578125 } } }, + .{ .t = 2612868798, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.78726196, .y = 0.55740356, .pressure = 0.018676758 } } }, + .{ .t = 2612877548, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.79766846, .y = 0.56655884, .pressure = 0.016998291 } } }, + .{ .t = 2612881858, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8077698, .y = 0.57421875, .pressure = 0.016174316 } } }, + .{ .t = 2624096121, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.81689453, .y = 0.5804138, .pressure = 0.0184021 } } }, + .{ .t = 2624103861, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8230896, .y = 0.58462524, .pressure = 0.017578125 } } }, + .{ .t = 2624108371, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8291321, .y = 0.58810425, .pressure = 0.016448975 } } }, + .{ .t = 2635100225, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8328247, .y = 0.5901184, .pressure = 0.015594482 } } }, + .{ .t = 2635107345, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.835022, .y = 0.59017944, .pressure = 0.016174316 } } }, + .{ .t = 2635111905, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.83724976, .y = 0.5899353, .pressure = 0.016174316 } } }, + .{ .t = 2646151229, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8390808, .y = 0.5890198, .pressure = 0.014770508 } } }, + .{ .t = 2646160149, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8404541, .y = 0.58709717, .pressure = 0.014190674 } } }, + .{ .t = 2657358812, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8408203, .y = 0.58535767, .pressure = 0.016448975 } } }, + .{ .t = 2657364952, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8411865, .y = 0.5831604, .pressure = 0.015045166 } } }, + .{ .t = 2657368602, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.84106445, .y = 0.5809021, .pressure = 0.0184021 } } }, + .{ .t = 2668497496, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.84155273, .y = 0.5791321, .pressure = 0.018676758 } } }, + .{ .t = 2668503176, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.84198, .y = 0.5767517, .pressure = 0.0184021 } } }, + .{ .t = 2679574619, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8413696, .y = 0.5749817, .pressure = 0.01727295 } } }, + .{ .t = 2679583429, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8410034, .y = 0.57302856, .pressure = 0.015594482 } } }, + .{ .t = 2679588959, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8402405, .y = 0.57077026, .pressure = 0.016998291 } } }, + .{ .t = 2690585493, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.83987427, .y = 0.5680237, .pressure = 0.017578125 } } }, + .{ .t = 2690591573, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8392639, .y = 0.5658264, .pressure = 0.016998291 } } }, + .{ .t = 2701710277, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8384094, .y = 0.56329346, .pressure = 0.015045166 } } }, + .{ .t = 2701715427, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8366089, .y = 0.5602722, .pressure = 0.012512207 } } }, + .{ .t = 2701719287, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8343506, .y = 0.55578613, .pressure = 0.013641357 } } }, + .{ .t = 2712932260, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8309326, .y = 0.5510254, .pressure = 0.012512207 } } }, + .{ .t = 2712941600, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8270569, .y = 0.54504395, .pressure = 0.013641357 } } }, + .{ .t = 2712946870, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.82263184, .y = 0.53845215, .pressure = 0.012786865 } } }, + .{ .t = 2724074464, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8186035, .y = 0.5309448, .pressure = 0.012237549 } } }, + .{ .t = 2724081034, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8176575, .y = 0.5210266, .pressure = 0.011383057 } } }, + .{ .t = 2724085114, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8161926, .y = 0.5109863, .pressure = 0.010253906 } } }, + .{ .t = 2735041467, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.81481934, .y = 0.49887085, .pressure = 0.008575439 } } }, + .{ .t = 2735049697, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8135681, .y = 0.48706055, .pressure = 0.0066223145 } } }, + .{ .t = 2735053437, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8110962, .y = 0.47451782, .pressure = 0.0066223145 } } }, + .{ .t = 2746200461, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8079529, .y = 0.46011353, .pressure = 0.008300781 } } }, + .{ .t = 2746207531, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8046875, .y = 0.44818115, .pressure = 0.008850098 } } }, + .{ .t = 2757301144, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.8004761, .y = 0.4363098, .pressure = 0.010253906 } } }, + .{ .t = 2757308574, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.796051, .y = 0.4248352, .pressure = 0.009979248 } } }, + .{ .t = 2757312724, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.79104614, .y = 0.4133911, .pressure = 0.013366699 } } }, + .{ .t = 2775948317, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.78637695, .y = 0.4032898, .pressure = 0.012237549 } } }, + .{ .t = 2775958817, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.78131104, .y = 0.39471436, .pressure = 0.015045166 } } }, + .{ .t = 2775962507, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7763977, .y = 0.38796997, .pressure = 0.016723633 } } }, + .{ .t = 2775966007, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.77178955, .y = 0.38198853, .pressure = 0.018127441 } } }, + .{ .t = 2775969667, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.76724243, .y = 0.37753296, .pressure = 0.019805908 } } }, + .{ .t = 2779448262, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7628784, .y = 0.37338257, .pressure = 0.018127441 } } }, + .{ .t = 2790559265, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.75909424, .y = 0.36990356, .pressure = 0.020935059 } } }, + .{ .t = 2790566225, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.75512695, .y = 0.36654663, .pressure = 0.021484375 } } }, + .{ .t = 2801688299, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7513733, .y = 0.36395264, .pressure = 0.020385742 } } }, + .{ .t = 2801695099, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7475891, .y = 0.36190796, .pressure = 0.020385742 } } }, + .{ .t = 2801697739, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.74487305, .y = 0.35958862, .pressure = 0.020385742 } } }, + .{ .t = 2812906962, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.74191284, .y = 0.3572998, .pressure = 0.022888184 } } }, + .{ .t = 2812918202, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7388611, .y = 0.35458374, .pressure = 0.022338867 } } }, + .{ .t = 2812924662, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7357178, .y = 0.35250854, .pressure = 0.021209717 } } }, + .{ .t = 2824054786, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7324829, .y = 0.3503418, .pressure = 0.021484375 } } }, + .{ .t = 2824059786, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7289429, .y = 0.3484497, .pressure = 0.022888184 } } }, + .{ .t = 2824063716, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.72506714, .y = 0.34591675, .pressure = 0.022613525 } } }, + .{ .t = 2835063039, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7218323, .y = 0.34277344, .pressure = 0.02319336 } } }, + .{ .t = 2835070099, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7174072, .y = 0.34020996, .pressure = 0.020080566 } } }, + .{ .t = 2835075929, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.71273804, .y = 0.33743286, .pressure = 0.020080566 } } }, + .{ .t = 2846116163, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7079773, .y = 0.3343506, .pressure = 0.018676758 } } }, + .{ .t = 2846123943, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7023926, .y = 0.33081055, .pressure = 0.019805908 } } }, + .{ .t = 2857453356, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6963806, .y = 0.32598877, .pressure = 0.019805908 } } }, + .{ .t = 2857460036, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6892395, .y = 0.32144165, .pressure = 0.020935059 } } }, + .{ .t = 2857466116, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6821289, .y = 0.31661987, .pressure = 0.018127441 } } }, + .{ .t = 2868624580, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6739197, .y = 0.31192017, .pressure = 0.018676758 } } }, + .{ .t = 2868632160, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6664429, .y = 0.3072815, .pressure = 0.018981934 } } }, + .{ .t = 2868637550, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6587219, .y = 0.30307007, .pressure = 0.017578125 } } }, + .{ .t = 2879637654, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.65133667, .y = 0.29888916, .pressure = 0.017852783 } } }, + .{ .t = 2879646144, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6444702, .y = 0.29452515, .pressure = 0.017852783 } } }, + .{ .t = 2879653574, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6372986, .y = 0.29092407, .pressure = 0.016174316 } } }, + .{ .t = 2890493398, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6305542, .y = 0.28729248, .pressure = 0.016448975 } } }, + .{ .t = 2890500368, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.62493896, .y = 0.28427124, .pressure = 0.016448975 } } }, + .{ .t = 2901904031, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6192627, .y = 0.28234863, .pressure = 0.015594482 } } }, + .{ .t = 2901913451, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.61428833, .y = 0.27990723, .pressure = 0.014190674 } } }, + .{ .t = 2901920201, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6097412, .y = 0.277771, .pressure = 0.013641357 } } }, + .{ .t = 2913077524, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6056824, .y = 0.27627563, .pressure = 0.013641357 } } }, + .{ .t = 2913084054, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6019287, .y = 0.27560425, .pressure = 0.012512207 } } }, + .{ .t = 2913088274, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5984192, .y = 0.27441406, .pressure = 0.011657715 } } }, + .{ .t = 2924138128, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.59536743, .y = 0.27404785, .pressure = 0.011962891 } } }, + .{ .t = 2924146018, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5923767, .y = 0.27398682, .pressure = 0.013641357 } } }, + .{ .t = 2924151648, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5900574, .y = 0.2736206, .pressure = 0.013366699 } } }, + .{ .t = 2935179332, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5883484, .y = 0.27407837, .pressure = 0.014465332 } } }, + .{ .t = 2935187861, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5866394, .y = 0.27478027, .pressure = 0.01586914 } } }, + .{ .t = 2935191171, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.58551025, .y = 0.2756958, .pressure = 0.015045166 } } }, + .{ .t = 2946370475, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5841675, .y = 0.27648926, .pressure = 0.01727295 } } }, + .{ .t = 2946379375, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5830078, .y = 0.27764893, .pressure = 0.0184021 } } }, + .{ .t = 2957467849, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5821533, .y = 0.278656, .pressure = 0.01953125 } } }, + .{ .t = 2957477449, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5817566, .y = 0.28030396, .pressure = 0.016998291 } } }, + .{ .t = 2957483529, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.58148193, .y = 0.28225708, .pressure = 0.015319824 } } }, + .{ .t = 2968627182, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5809021, .y = 0.2843933, .pressure = 0.01586914 } } }, + .{ .t = 2968643772, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.580719, .y = 0.28659058, .pressure = 0.014190674 } } }, + .{ .t = 2979684996, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5805969, .y = 0.28967285, .pressure = 0.013641357 } } }, + .{ .t = 2979694336, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.58026123, .y = 0.29241943, .pressure = 0.010559082 } } }, + .{ .t = 2979699086, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.57995605, .y = 0.29571533, .pressure = 0.008575439 } } }, + .{ .t = 2990715289, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.57958984, .y = 0.29934692, .pressure = 0.010253906 } } }, + .{ .t = 2990723719, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5793457, .y = 0.30322266, .pressure = 0.008300781 } } }, + .{ .t = 3002153093, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5791931, .y = 0.30700684, .pressure = 0.0060424805 } } }, + .{ .t = 3002161152, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5791931, .y = 0.3117981, .pressure = 0.0060424805 } } }, + .{ .t = 3002165632, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.57958984, .y = 0.3164673, .pressure = 0.00491333 } } }, + .{ .t = 3012982186, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5806885, .y = 0.3215027, .pressure = 0.0068969727 } } }, + .{ .t = 3012991236, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5819702, .y = 0.32669067, .pressure = 0.0057678223 } } }, + .{ .t = 3012998166, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5845032, .y = 0.3322754, .pressure = 0.007446289 } } }, + .{ .t = 3024201460, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5869446, .y = 0.33740234, .pressure = 0.008026123 } } }, + .{ .t = 3024208990, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.59017944, .y = 0.34225464, .pressure = 0.009155273 } } }, + .{ .t = 3024211980, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.5932617, .y = 0.34698486, .pressure = 0.012237549 } } }, + .{ .t = 3035025244, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.59643555, .y = 0.3517456, .pressure = 0.013366699 } } }, + .{ .t = 3035031374, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6001282, .y = 0.35601807, .pressure = 0.016998291 } } }, + .{ .t = 3035034874, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.60409546, .y = 0.3600464, .pressure = 0.019805908 } } }, + .{ .t = 3046541367, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.60775757, .y = 0.36398315, .pressure = 0.022338867 } } }, + .{ .t = 3046548887, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.61169434, .y = 0.36740112, .pressure = 0.022613525 } } }, + .{ .t = 3057532891, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6154785, .y = 0.37051392, .pressure = 0.025146484 } } }, + .{ .t = 3057540471, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6194763, .y = 0.37329102, .pressure = 0.025421143 } } }, + .{ .t = 3057545781, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6232605, .y = 0.3761902, .pressure = 0.026000977 } } }, + .{ .t = 3068735374, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.62753296, .y = 0.3789673, .pressure = 0.025421143 } } }, + .{ .t = 3068748304, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6313782, .y = 0.3816223, .pressure = 0.024017334 } } }, + .{ .t = 3068754594, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.63513184, .y = 0.38391113, .pressure = 0.023742676 } } }, + .{ .t = 3079554878, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6390991, .y = 0.38616943, .pressure = 0.023468018 } } }, + .{ .t = 3079563518, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6433716, .y = 0.38833618, .pressure = 0.02178955 } } }, + .{ .t = 3079568338, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.64767456, .y = 0.39031982, .pressure = 0.02319336 } } }, + .{ .t = 3090741042, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.65234375, .y = 0.3919983, .pressure = 0.02319336 } } }, + .{ .t = 3090749882, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.65689087, .y = 0.39379883, .pressure = 0.021209717 } } }, + .{ .t = 3101724975, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6610718, .y = 0.39520264, .pressure = 0.022888184 } } }, + .{ .t = 3101732005, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.66574097, .y = 0.39642334, .pressure = 0.021484375 } } }, + .{ .t = 3101735255, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6701355, .y = 0.3973999, .pressure = 0.019805908 } } }, + .{ .t = 3113361458, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6748352, .y = 0.39767456, .pressure = 0.0206604 } } }, + .{ .t = 3113368498, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.67944336, .y = 0.39797974, .pressure = 0.022613525 } } }, + .{ .t = 3113372028, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6838379, .y = 0.39785767, .pressure = 0.022338867 } } }, + .{ .t = 3123796833, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6879883, .y = 0.3970642, .pressure = 0.01953125 } } }, + .{ .t = 3123803053, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.69177246, .y = 0.39624023, .pressure = 0.018127441 } } }, + .{ .t = 3123806563, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.69555664, .y = 0.39569092, .pressure = 0.016998291 } } }, + .{ .t = 3134998596, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.69888306, .y = 0.3942871, .pressure = 0.016998291 } } }, + .{ .t = 3135007066, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7023926, .y = 0.39257812, .pressure = 0.017578125 } } }, + .{ .t = 3135011336, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7060852, .y = 0.39056396, .pressure = 0.017578125 } } }, + .{ .t = 3146195970, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7102051, .y = 0.38861084, .pressure = 0.015594482 } } }, + .{ .t = 3146202620, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.715271, .y = 0.386261, .pressure = 0.014190674 } } }, + .{ .t = 3157408853, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7234802, .y = 0.38327026, .pressure = 0.01586914 } } }, + .{ .t = 3157418073, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.730896, .y = 0.38006592, .pressure = 0.01586914 } } }, + .{ .t = 3157423313, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.73880005, .y = 0.37652588, .pressure = 0.016448975 } } }, + .{ .t = 3168334437, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.74557495, .y = 0.37350464, .pressure = 0.017578125 } } }, + .{ .t = 3168341357, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.75097656, .y = 0.37020874, .pressure = 0.016723633 } } }, + .{ .t = 3168344697, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7561035, .y = 0.36791992, .pressure = 0.013916016 } } }, + .{ .t = 3179518520, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.75982666, .y = 0.36517334, .pressure = 0.013061523 } } }, + .{ .t = 3179524910, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7633362, .y = 0.3623352, .pressure = 0.013061523 } } }, + .{ .t = 3179530860, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.765625, .y = 0.35949707, .pressure = 0.013641357 } } }, + .{ .t = 3190702424, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7669678, .y = 0.3564453, .pressure = 0.012786865 } } }, + .{ .t = 3190710904, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.76849365, .y = 0.3536682, .pressure = 0.011383057 } } }, + .{ .t = 3201886237, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7687378, .y = 0.35095215, .pressure = 0.010559082 } } }, + .{ .t = 3201895897, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7681885, .y = 0.34838867, .pressure = 0.009155273 } } }, + .{ .t = 3201900097, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7668457, .y = 0.34570312, .pressure = 0.009155273 } } }, + .{ .t = 3212919591, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7654724, .y = 0.34277344, .pressure = 0.008850098 } } }, + .{ .t = 3212927311, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7631836, .y = 0.34002686, .pressure = 0.0066223145 } } }, + .{ .t = 3212932591, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7612915, .y = 0.3373413, .pressure = 0.0040893555 } } }, + .{ .t = 3224127654, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7590027, .y = 0.33529663, .pressure = 0.0043640137 } } }, + .{ .t = 3224134564, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7567444, .y = 0.33319092, .pressure = 0.0024108887 } } }, + .{ .t = 3224138834, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7541809, .y = 0.3307495, .pressure = 0.00491333 } } }, + .{ .t = 3234961798, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.75216675, .y = 0.32843018, .pressure = 0.0038146973 } } }, + .{ .t = 3234967628, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7489929, .y = 0.32583618, .pressure = 0.0038146973 } } }, + .{ .t = 3234971398, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7467346, .y = 0.32296753, .pressure = 0.005218506 } } }, + .{ .t = 3246367272, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7436218, .y = 0.32019043, .pressure = 0.0043640137 } } }, + .{ .t = 3246376701, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7402649, .y = 0.3173523, .pressure = 0.0038146973 } } }, + .{ .t = 3257870675, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.73721313, .y = 0.31466675, .pressure = 0.0018310547 } } }, + .{ .t = 3257881104, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7336731, .y = 0.31219482, .pressure = 0.0024108887 } } }, + .{ .t = 3257886264, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.73062134, .y = 0.3100891, .pressure = 0.0015563965 } } }, + .{ .t = 3268291019, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.72720337, .y = 0.30807495, .pressure = 0.0007019043 } } }, + .{ .t = 3268298969, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7241516, .y = 0.30593872, .pressure = 0.0015563965 } } }, + .{ .t = 3268303569, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7213135, .y = 0.30371094, .pressure = 0.0035095215 } } }, + .{ .t = 3279746522, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.71810913, .y = 0.302063, .pressure = 0.002960205 } } }, + .{ .t = 3279757542, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.7147217, .y = 0.30056763, .pressure = 0.00491333 } } }, + .{ .t = 3279762862, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.71087646, .y = 0.29907227, .pressure = 0.00491333 } } }, + .{ .t = 3290574016, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.70751953, .y = 0.29745483, .pressure = 0.0040893555 } } }, + .{ .t = 3290581596, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.70376587, .y = 0.29592896, .pressure = 0.0040893555 } } }, + .{ .t = 3301750300, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6994934, .y = 0.2951355, .pressure = 0.0038146973 } } }, + .{ .t = 3301760370, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6951904, .y = 0.29397583, .pressure = 0.005218506 } } }, + .{ .t = 3301767410, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6905823, .y = 0.29284668, .pressure = 0.00491333 } } }, + .{ .t = 3312951293, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.685791, .y = 0.29266357, .pressure = 0.0068969727 } } }, + .{ .t = 3312959893, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.68136597, .y = 0.29257202, .pressure = 0.005493164 } } }, + .{ .t = 3312965373, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6772461, .y = 0.29229736, .pressure = 0.0068969727 } } }, + .{ .t = 3324079267, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.672699, .y = 0.29318237, .pressure = 0.004638672 } } }, + .{ .t = 3324090337, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.66882324, .y = 0.294281, .pressure = 0.004638672 } } }, + .{ .t = 3324095997, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.66537476, .y = 0.29525757, .pressure = 0.004638672 } } }, + .{ .t = 3335061800, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6620178, .y = 0.2966919, .pressure = 0.002960205 } } }, + .{ .t = 3335068160, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6590576, .y = 0.29788208, .pressure = 0.0007019043 } } }, + .{ .t = 3335073750, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .up, .x = 0.6562805, .y = 0.29956055, .pressure = 0 } } }, + .{ .t = 3390587188, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .down, .x = 0.6447449, .y = 0.33596802, .pressure = 0.0007019043 } } }, + .{ .t = 3390593138, .pad = 2, .ev = .{ .touch = .{ .touchpad = 1, .finger = 0, .phase = .motion, .x = 0.6447754, .y = 0.3406067, .pressure = 0.0035095215 } } }, } } diff --git a/test/deck/triggers.zon b/test/deck/triggers.zon index ad5f7656..8cac4b66 100644 --- a/test/deck/triggers.zon +++ b/test/deck/triggers.zon @@ -1,576 +1,576 @@ .{ .version = 1, .events = .{ -.{.t=3100837937,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3100845387,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3100845387,.pad=2,.ev=.{.axis=.{.idx=1,.value=-1441}}}, -.{.t=3100845387,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3100849157,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3100849157,.pad=2,.ev=.{.axis=.{.idx=1,.value=-1411}}}, -.{.t=3100849157,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3111923010,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3111923010,.pad=2,.ev=.{.axis=.{.idx=1,.value=-1529}}}, -.{.t=3111923010,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3111936310,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3111936310,.pad=2,.ev=.{.axis=.{.idx=1,.value=-1323}}}, -.{.t=3111941850,.pad=2,.ev=.{.axis=.{.idx=1,.value=-1558}}}, -.{.t=3111941850,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3123013224,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3123013224,.pad=2,.ev=.{.axis=.{.idx=1,.value=-1294}}}, -.{.t=3123013224,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3123021794,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3123021794,.pad=2,.ev=.{.axis=.{.idx=1,.value=-941}}}, -.{.t=3123021794,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3134267607,.pad=2,.ev=.{.axis=.{.idx=5,.value=0}}}, -.{.t=3134267607,.pad=2,.ev=.{.axis=.{.idx=5,.value=214}}}, -.{.t=3134267607,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3134267607,.pad=2,.ev=.{.axis=.{.idx=1,.value=-647}}}, -.{.t=3134277137,.pad=2,.ev=.{.axis=.{.idx=5,.value=2674}}}, -.{.t=3134277137,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3134277137,.pad=2,.ev=.{.axis=.{.idx=1,.value=-500}}}, -.{.t=3134280727,.pad=2,.ev=.{.axis=.{.idx=5,.value=5436}}}, -.{.t=3134280727,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3134280727,.pad=2,.ev=.{.axis=.{.idx=1,.value=-206}}}, -.{.t=3134280727,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3146260210,.pad=2,.ev=.{.axis=.{.idx=5,.value=8198}}}, -.{.t=3146260210,.pad=2,.ev=.{.axis=.{.idx=0,.value=-774}}}, -.{.t=3146260210,.pad=2,.ev=.{.axis=.{.idx=1,.value=-176}}}, -.{.t=3146260210,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3146270520,.pad=2,.ev=.{.axis=.{.idx=5,.value=11211}}}, -.{.t=3146270520,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3146270520,.pad=2,.ev=.{.axis=.{.idx=1,.value=-29}}}, -.{.t=3146274870,.pad=2,.ev=.{.axis=.{.idx=5,.value=13671}}}, -.{.t=3146274870,.pad=2,.ev=.{.axis=.{.idx=1,.value=86}}}, -.{.t=3146274870,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3156416215,.pad=2,.ev=.{.axis=.{.idx=5,.value=16432}}}, -.{.t=3156416215,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3156416215,.pad=2,.ev=.{.axis=.{.idx=1,.value=288}}}, -.{.t=3156416215,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3156435465,.pad=2,.ev=.{.axis=.{.idx=5,.value=18893}}}, -.{.t=3156435465,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3156435465,.pad=2,.ev=.{.axis=.{.idx=1,.value=462}}}, -.{.t=3156441825,.pad=2,.ev=.{.axis=.{.idx=5,.value=21504}}}, -.{.t=3156441825,.pad=2,.ev=.{.axis=.{.idx=1,.value=491}}}, -.{.t=3156441825,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3167440508,.pad=2,.ev=.{.axis=.{.idx=5,.value=23915}}}, -.{.t=3167440508,.pad=2,.ev=.{.axis=.{.idx=1,.value=664}}}, -.{.t=3167440508,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3167449678,.pad=2,.ev=.{.axis=.{.idx=5,.value=26224}}}, -.{.t=3167449678,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3167449678,.pad=2,.ev=.{.axis=.{.idx=1,.value=779}}}, -.{.t=3167449678,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3178634312,.pad=2,.ev=.{.axis=.{.idx=5,.value=28384}}}, -.{.t=3178634312,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3178634312,.pad=2,.ev=.{.axis=.{.idx=1,.value=837}}}, -.{.t=3178634312,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3178646332,.pad=2,.ev=.{.axis=.{.idx=5,.value=30593}}}, -.{.t=3178646332,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3178646332,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3178651472,.pad=2,.ev=.{.axis=.{.idx=5,.value=32702}}}, -.{.t=3178651472,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3189737565,.pad=2,.ev=.{.axis=.{.idx=5,.value=32766}}}, -.{.t=3189737565,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=3189737565,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3189748175,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3189751215,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=3189751215,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3200899959,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3200909349,.pad=2,.ev=.{.axis=.{.idx=0,.value=-774}}}, -.{.t=3200909349,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=3200914229,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3200914229,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=3200914229,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3212027402,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3212027402,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=3212027402,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3212033902,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3222960156,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=3222960156,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3222967916,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3222967916,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=3222967916,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=3234186130,.pad=2,.ev=.{.axis=.{.idx=0,.value=-857}}}, -.{.t=3234186130,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=3234186130,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3234194710,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3234194710,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=3234194710,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3234198480,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3234198480,.pad=2,.ev=.{.axis=.{.idx=1,.value=1097}}}, -.{.t=3245272663,.pad=2,.ev=.{.axis=.{.idx=1,.value=1126}}}, -.{.t=3245272663,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3245280873,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3245280873,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3245284263,.pad=2,.ev=.{.axis=.{.idx=1,.value=1097}}}, -.{.t=3245284263,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3256351647,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3256351647,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3256361897,.pad=2,.ev=.{.axis=.{.idx=1,.value=1126}}}, -.{.t=3256361897,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3256366557,.pad=2,.ev=.{.axis=.{.idx=0,.value=-857}}}, -.{.t=3267453910,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3267461450,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3267461450,.pad=2,.ev=.{.axis=.{.idx=1,.value=1097}}}, -.{.t=3267461450,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3278671394,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3278679494,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3278679494,.pad=2,.ev=.{.axis=.{.idx=1,.value=1126}}}, -.{.t=3278679494,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3278684284,.pad=2,.ev=.{.axis=.{.idx=1,.value=1097}}}, -.{.t=3289747017,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3289757957,.pad=2,.ev=.{.axis=.{.idx=0,.value=-774}}}, -.{.t=3289757957,.pad=2,.ev=.{.axis=.{.idx=1,.value=1068}}}, -.{.t=3289757957,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3289764977,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3289764977,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3300894251,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3300894251,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3300904161,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3300904161,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3300908771,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3312130554,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3312130554,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=3312130554,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3312142164,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3312145624,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3312145624,.pad=2,.ev=.{.axis=.{.idx=1,.value=1068}}}, -.{.t=3312145624,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3323185928,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3323185928,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=3323197438,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=3334415941,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3334415941,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3334428191,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3334428191,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3334433441,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3345319335,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3345319335,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=3345329665,.pad=2,.ev=.{.axis=.{.idx=0,.value=-774}}}, -.{.t=3345329665,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=3345329665,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3345334835,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3356434069,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3356434069,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=3356434069,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3356449919,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3356449919,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=3356449919,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3367716072,.pad=2,.ev=.{.axis=.{.idx=0,.value=-857}}}, -.{.t=3367716072,.pad=2,.ev=.{.axis=.{.idx=1,.value=1068}}}, -.{.t=3367728332,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3367728332,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=3367728332,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3367733692,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3367733692,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=3367733692,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3378615526,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3389836929,.pad=2,.ev=.{.axis=.{.idx=0,.value=-774}}}, -.{.t=3389836929,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=3389836929,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3389847129,.pad=2,.ev=.{.axis=.{.idx=5,.value=31648}}}, -.{.t=3389847129,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3389847129,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=3389852719,.pad=2,.ev=.{.axis=.{.idx=5,.value=29137}}}, -.{.t=3389852719,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=3401186593,.pad=2,.ev=.{.axis=.{.idx=5,.value=26074}}}, -.{.t=3401186593,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3401194003,.pad=2,.ev=.{.axis=.{.idx=5,.value=23262}}}, -.{.t=3401194003,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3401194003,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=3401194003,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=3401198713,.pad=2,.ev=.{.axis=.{.idx=5,.value=20349}}}, -.{.t=3401198713,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3411932407,.pad=2,.ev=.{.axis=.{.idx=5,.value=17587}}}, -.{.t=3411932407,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3411932407,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=3411941077,.pad=2,.ev=.{.axis=.{.idx=5,.value=15127}}}, -.{.t=3411941077,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3411941077,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3411944947,.pad=2,.ev=.{.axis=.{.idx=5,.value=12617}}}, -.{.t=3411944947,.pad=2,.ev=.{.axis=.{.idx=0,.value=-829}}}, -.{.t=3411944947,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=3411944947,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3423178470,.pad=2,.ev=.{.axis=.{.idx=5,.value=10307}}}, -.{.t=3423178470,.pad=2,.ev=.{.axis=.{.idx=0,.value=-802}}}, -.{.t=3423178470,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=3423187080,.pad=2,.ev=.{.axis=.{.idx=5,.value=8298}}}, -.{.t=3423187080,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=3423187080,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3434307174,.pad=2,.ev=.{.axis=.{.idx=5,.value=6340}}}, -.{.t=3434307174,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=3434315334,.pad=2,.ev=.{.axis=.{.idx=5,.value=4532}}}, -.{.t=3434315334,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3434318744,.pad=2,.ev=.{.axis=.{.idx=5,.value=2975}}}, -.{.t=3434318744,.pad=2,.ev=.{.axis=.{.idx=1,.value=866}}}, -.{.t=3445336427,.pad=2,.ev=.{.axis=.{.idx=5,.value=1067}}}, -.{.t=3445336427,.pad=2,.ev=.{.axis=.{.idx=1,.value=635}}}, -.{.t=3445344507,.pad=2,.ev=.{.axis=.{.idx=4,.value=446}}}, -.{.t=3445344507,.pad=2,.ev=.{.axis=.{.idx=5,.value=0}}}, -.{.t=3445344507,.pad=2,.ev=.{.axis=.{.idx=1,.value=346}}}, -.{.t=3445344507,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=3445348567,.pad=2,.ev=.{.axis=.{.idx=4,.value=1854}}}, -.{.t=3445348567,.pad=2,.ev=.{.axis=.{.idx=1,.value=-59}}}, -.{.t=3456475621,.pad=2,.ev=.{.axis=.{.idx=4,.value=3310}}}, -.{.t=3456475621,.pad=2,.ev=.{.axis=.{.idx=1,.value=-176}}}, -.{.t=3456475621,.pad=2,.ev=.{.axis=.{.idx=3,.value=997}}}, -.{.t=3456483971,.pad=2,.ev=.{.axis=.{.idx=4,.value=4436}}}, -.{.t=3456483971,.pad=2,.ev=.{.axis=.{.idx=1,.value=-441}}}, -.{.t=3456487161,.pad=2,.ev=.{.axis=.{.idx=4,.value=5891}}}, -.{.t=3456487161,.pad=2,.ev=.{.axis=.{.idx=1,.value=-558}}}, -.{.t=22900269279,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=22900269279,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=22900269279,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=22900282319,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=22900282319,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=22900282319,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=22900282319,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=22900288339,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=22900288339,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=22900288339,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=22911078513,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=22911078513,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=22911078513,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=22911090183,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=22922174447,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=22922174447,.pad=2,.ev=.{.axis=.{.idx=2,.value=-527}}}, -.{.t=22922174447,.pad=2,.ev=.{.axis=.{.idx=3,.value=1148}}}, -.{.t=22922182927,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=22922182927,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=22922182927,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=22922182927,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=22922186907,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=22933453380,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=22933463530,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=22933463530,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=22933463530,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=22933463530,.pad=2,.ev=.{.axis=.{.idx=3,.value=1148}}}, -.{.t=22933469520,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=22933469520,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=22933469520,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=22944601464,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=22944601464,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=22944613874,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=22944613874,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=22944613874,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=22944619754,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=22955633677,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=22955633677,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=22955633677,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=22955633677,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=22955647207,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=22955647207,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=22955647207,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=22955647207,.pad=2,.ev=.{.axis=.{.idx=3,.value=1148}}}, -.{.t=22955652047,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=22955652047,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=22966619841,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=22966619841,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=22966628121,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=22966628121,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=22977745245,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=22977745245,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=22977745245,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=22977745245,.pad=2,.ev=.{.axis=.{.idx=3,.value=1148}}}, -.{.t=22977753905,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=22977753905,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=22977753905,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=22977757525,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=22988922908,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=22988922908,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=22988936008,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=22988936008,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=22988940638,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=22988940638,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23000140672,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23000140672,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=23000152872,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23000152872,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23000152872,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23000152872,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23000158442,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=23000158442,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23000158442,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23011247285,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23011247285,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23011247285,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23011260265,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23011260265,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23011260265,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23022366569,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23022366569,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23022366569,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=23022366569,.pad=2,.ev=.{.axis=.{.idx=3,.value=1148}}}, -.{.t=23022380099,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23022380099,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23022385329,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23022385329,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23033207513,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23033207513,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23033215483,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23033215483,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23033215483,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23033215483,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23033219653,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23044563226,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23044563226,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23044563226,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23044572856,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23044572856,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23044576806,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23044576806,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23044576806,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23055818709,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23055818709,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23055828779,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23055828779,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23055828779,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23055832789,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1410}}}, -.{.t=23055832789,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23066680603,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23066680603,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23066680603,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23066690143,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=23066690143,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23066690143,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23066690143,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23077703397,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23077703397,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23077703397,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23077711687,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23077711687,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23077711687,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23077715567,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=23077715567,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23077715567,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23077715567,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23088844720,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23088844720,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23088844720,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=23088844720,.pad=2,.ev=.{.axis=.{.idx=3,.value=1148}}}, -.{.t=23088853270,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23088853270,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23088853270,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23088856830,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23088856830,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23088856830,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23100184994,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23100184994,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23100184994,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23100197834,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23100202044,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23100202044,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23100202044,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23111316337,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23111328087,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23111328087,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23122579831,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23122579831,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=23122579831,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23122592031,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23122592031,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23122595681,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23122595681,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23122595681,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23133201565,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23133205635,.pad=2,.ev=.{.axis=.{.idx=4,.value=728}}}, -.{.t=23133205635,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23133205635,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23144628108,.pad=2,.ev=.{.axis=.{.idx=4,.value=3169}}}, -.{.t=23144628108,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=23144628108,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23144628108,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23144628108,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23144640728,.pad=2,.ev=.{.axis=.{.idx=4,.value=6314}}}, -.{.t=23144640728,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23144640728,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23144640728,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23144644338,.pad=2,.ev=.{.axis=.{.idx=4,.value=10679}}}, -.{.t=23144644338,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23144644338,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23144644338,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23155757852,.pad=2,.ev=.{.axis=.{.idx=4,.value=16500}}}, -.{.t=23155757852,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=23155757852,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23155767512,.pad=2,.ev=.{.axis=.{.idx=4,.value=23682}}}, -.{.t=23155767512,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23155767512,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23155773302,.pad=2,.ev=.{.axis=.{.idx=4,.value=32084}}}, -.{.t=23155773302,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23166856095,.pad=2,.ev=.{.axis=.{.idx=4,.value=32766}}}, -.{.t=23166856095,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23166856095,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23166869315,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23166869315,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23177937079,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23177937079,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23177947099,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23177947099,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23177950979,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23177950979,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23177950979,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23188909763,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23188909763,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23188919373,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=23188919373,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23188923533,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23188923533,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23188923533,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23188923533,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23200341706,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23200341706,.pad=2,.ev=.{.axis=.{.idx=1,.value=924}}}, -.{.t=23200341706,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23200357446,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23200360546,.pad=2,.ev=.{.axis=.{.idx=1,.value=866}}}, -.{.t=23200360546,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23211356329,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1493}}}, -.{.t=23211356329,.pad=2,.ev=.{.axis=.{.idx=1,.value=895}}}, -.{.t=23211356329,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23211369469,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23211369469,.pad=2,.ev=.{.axis=.{.idx=1,.value=808}}}, -.{.t=23211369469,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23211369469,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23222496653,.pad=2,.ev=.{.axis=.{.idx=1,.value=722}}}, -.{.t=23222496653,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23222496653,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23222508723,.pad=2,.ev=.{.axis=.{.idx=1,.value=664}}}, -.{.t=23222508723,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23222508723,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23222512923,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23222512923,.pad=2,.ev=.{.axis=.{.idx=1,.value=693}}}, -.{.t=23222512923,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23233616896,.pad=2,.ev=.{.axis=.{.idx=1,.value=404}}}, -.{.t=23233616896,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23233628876,.pad=2,.ev=.{.axis=.{.idx=1,.value=462}}}, -.{.t=23233628876,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23233628876,.pad=2,.ev=.{.axis=.{.idx=3,.value=1118}}}, -.{.t=23233634716,.pad=2,.ev=.{.axis=.{.idx=1,.value=375}}}, -.{.t=23233634716,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23244703810,.pad=2,.ev=.{.axis=.{.idx=1,.value=404}}}, -.{.t=23244703810,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23244703810,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23244716710,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23244716710,.pad=2,.ev=.{.axis=.{.idx=1,.value=288}}}, -.{.t=23244716710,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23244722470,.pad=2,.ev=.{.axis=.{.idx=1,.value=317}}}, -.{.t=23255891634,.pad=2,.ev=.{.axis=.{.idx=1,.value=260}}}, -.{.t=23255891634,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23255903964,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1410}}}, -.{.t=23255903964,.pad=2,.ev=.{.axis=.{.idx=1,.value=144}}}, -.{.t=23255903964,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23255909564,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23255909564,.pad=2,.ev=.{.axis=.{.idx=1,.value=115}}}, -.{.t=23266911057,.pad=2,.ev=.{.axis=.{.idx=4,.value=30723}}}, -.{.t=23266911057,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23266911057,.pad=2,.ev=.{.axis=.{.idx=1,.value=86}}}, -.{.t=23266924047,.pad=2,.ev=.{.axis=.{.idx=4,.value=27437}}}, -.{.t=23266924047,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23266924047,.pad=2,.ev=.{.axis=.{.idx=1,.value=115}}}, -.{.t=23266924047,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23278235081,.pad=2,.ev=.{.axis=.{.idx=4,.value=24292}}}, -.{.t=23278235081,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23278235081,.pad=2,.ev=.{.axis=.{.idx=1,.value=29}}}, -.{.t=23278246901,.pad=2,.ev=.{.axis=.{.idx=4,.value=21053}}}, -.{.t=23278246901,.pad=2,.ev=.{.axis=.{.idx=1,.value=57}}}, -.{.t=23278246901,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23278246901,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23278254110,.pad=2,.ev=.{.axis=.{.idx=4,.value=17814}}}, -.{.t=23278254110,.pad=2,.ev=.{.axis=.{.idx=1,.value=86}}}, -.{.t=23278254110,.pad=2,.ev=.{.axis=.{.idx=2,.value=-498}}}, -.{.t=23278254110,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23289217094,.pad=2,.ev=.{.axis=.{.idx=4,.value=14341}}}, -.{.t=23289217094,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1465}}}, -.{.t=23289217094,.pad=2,.ev=.{.axis=.{.idx=1,.value=144}}}, -.{.t=23289217094,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23289217094,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23289231434,.pad=2,.ev=.{.axis=.{.idx=4,.value=11384}}}, -.{.t=23289231434,.pad=2,.ev=.{.axis=.{.idx=1,.value=57}}}, -.{.t=23289236534,.pad=2,.ev=.{.axis=.{.idx=4,.value=8708}}}, -.{.t=23289236534,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1438}}}, -.{.t=23289236534,.pad=2,.ev=.{.axis=.{.idx=1,.value=0}}}, -.{.t=23300340478,.pad=2,.ev=.{.axis=.{.idx=4,.value=6126}}}, -.{.t=23300340478,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23300350538,.pad=2,.ev=.{.axis=.{.idx=4,.value=4014}}}, -.{.t=23300350538,.pad=2,.ev=.{.axis=.{.idx=1,.value=86}}}, -.{.t=23300354158,.pad=2,.ev=.{.axis=.{.idx=4,.value=2465}}}, -.{.t=23300354158,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1410}}}, -.{.t=23300354158,.pad=2,.ev=.{.axis=.{.idx=1,.value=288}}}, -.{.t=23311366832,.pad=2,.ev=.{.axis=.{.idx=4,.value=634}}}, -.{.t=23311366832,.pad=2,.ev=.{.axis=.{.idx=1,.value=462}}}, -.{.t=23311366832,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=23311379542,.pad=2,.ev=.{.axis=.{.idx=4,.value=0}}}, -.{.t=23311379542,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1355}}}, -.{.t=23311379542,.pad=2,.ev=.{.axis=.{.idx=1,.value=779}}}, -.{.t=23311379542,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23322638775,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1272}}}, -.{.t=23322638775,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23322638775,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23322649765,.pad=2,.ev=.{.axis=.{.idx=0,.value=-1051}}}, -.{.t=23322649765,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23322649765,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23322654995,.pad=2,.ev=.{.axis=.{.idx=0,.value=-885}}}, -.{.t=23322654995,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=23333351109,.pad=2,.ev=.{.axis=.{.idx=0,.value=-691}}}, -.{.t=23333351109,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23333359049,.pad=2,.ev=.{.axis=.{.idx=0,.value=-553}}}, -.{.t=23333359049,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23333362519,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=23333362519,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23333362519,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23344695372,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23344706662,.pad=2,.ev=.{.axis=.{.idx=0,.value=-525}}}, -.{.t=23344706662,.pad=2,.ev=.{.axis=.{.idx=1,.value=953}}}, -.{.t=23344711982,.pad=2,.ev=.{.axis=.{.idx=0,.value=-553}}}, -.{.t=23344711982,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23355868326,.pad=2,.ev=.{.axis=.{.idx=0,.value=-498}}}, -.{.t=23355868326,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=23355878956,.pad=2,.ev=.{.axis=.{.idx=0,.value=-525}}}, -.{.t=23355878956,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23355878956,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23355878956,.pad=2,.ev=.{.axis=.{.idx=3,.value=1087}}}, -.{.t=23355884866,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=23355884866,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23355884866,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=23366942749,.pad=2,.ev=.{.axis=.{.idx=0,.value=-553}}}, -.{.t=23366952219,.pad=2,.ev=.{.axis=.{.idx=0,.value=-525}}}, -.{.t=23366952219,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23366952219,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23366952219,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23378047613,.pad=2,.ev=.{.axis=.{.idx=0,.value=-553}}}, -.{.t=23378047613,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=23378064723,.pad=2,.ev=.{.axis=.{.idx=0,.value=-525}}}, -.{.t=23378064723,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23378064723,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23388957907,.pad=2,.ev=.{.axis=.{.idx=0,.value=-553}}}, -.{.t=23388957907,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=23388957907,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23388957907,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=23388967217,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=23388967217,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23388970117,.pad=2,.ev=.{.axis=.{.idx=0,.value=-525}}}, -.{.t=23388970117,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23388970117,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23388970117,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23400316180,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23400325960,.pad=2,.ev=.{.axis=.{.idx=0,.value=-580}}}, -.{.t=23400325960,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=23400325960,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23400330510,.pad=2,.ev=.{.axis=.{.idx=0,.value=-525}}}, -.{.t=23400330510,.pad=2,.ev=.{.axis=.{.idx=1,.value=981}}}, -.{.t=23400330510,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23411327274,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=23411337364,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=23411337364,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=23422593127,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23422593127,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23422603997,.pad=2,.ev=.{.axis=.{.idx=2,.value=-410}}}, -.{.t=23422603997,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=23422607677,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23422607677,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23433465571,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=23433465571,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, -.{.t=23433473571,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=23433473571,.pad=2,.ev=.{.axis=.{.idx=2,.value=-469}}}, -.{.t=23433473571,.pad=2,.ev=.{.axis=.{.idx=3,.value=1057}}}, -.{.t=23444613485,.pad=2,.ev=.{.axis=.{.idx=1,.value=1039}}}, -.{.t=23444623255,.pad=2,.ev=.{.axis=.{.idx=2,.value=-439}}}, -.{.t=23444626645,.pad=2,.ev=.{.axis=.{.idx=1,.value=1010}}}, -.{.t=23444626645,.pad=2,.ev=.{.axis=.{.idx=3,.value=1027}}}, + .{ .t = 3100837937, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3100845387, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3100845387, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -1441 } } }, + .{ .t = 3100845387, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3100849157, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3100849157, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -1411 } } }, + .{ .t = 3100849157, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3111923010, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3111923010, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -1529 } } }, + .{ .t = 3111923010, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3111936310, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3111936310, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -1323 } } }, + .{ .t = 3111941850, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -1558 } } }, + .{ .t = 3111941850, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3123013224, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3123013224, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -1294 } } }, + .{ .t = 3123013224, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3123021794, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3123021794, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -941 } } }, + .{ .t = 3123021794, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3134267607, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 0 } } }, + .{ .t = 3134267607, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 214 } } }, + .{ .t = 3134267607, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3134267607, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -647 } } }, + .{ .t = 3134277137, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 2674 } } }, + .{ .t = 3134277137, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3134277137, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -500 } } }, + .{ .t = 3134280727, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 5436 } } }, + .{ .t = 3134280727, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3134280727, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -206 } } }, + .{ .t = 3134280727, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3146260210, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 8198 } } }, + .{ .t = 3146260210, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -774 } } }, + .{ .t = 3146260210, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -176 } } }, + .{ .t = 3146260210, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3146270520, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 11211 } } }, + .{ .t = 3146270520, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3146270520, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -29 } } }, + .{ .t = 3146274870, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 13671 } } }, + .{ .t = 3146274870, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 86 } } }, + .{ .t = 3146274870, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3156416215, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 16432 } } }, + .{ .t = 3156416215, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3156416215, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 288 } } }, + .{ .t = 3156416215, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3156435465, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 18893 } } }, + .{ .t = 3156435465, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3156435465, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 462 } } }, + .{ .t = 3156441825, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 21504 } } }, + .{ .t = 3156441825, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 491 } } }, + .{ .t = 3156441825, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3167440508, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 23915 } } }, + .{ .t = 3167440508, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 664 } } }, + .{ .t = 3167440508, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3167449678, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 26224 } } }, + .{ .t = 3167449678, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3167449678, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 779 } } }, + .{ .t = 3167449678, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3178634312, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 28384 } } }, + .{ .t = 3178634312, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3178634312, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 837 } } }, + .{ .t = 3178634312, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3178646332, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 30593 } } }, + .{ .t = 3178646332, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3178646332, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3178651472, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 32702 } } }, + .{ .t = 3178651472, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3189737565, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 32766 } } }, + .{ .t = 3189737565, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 3189737565, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3189748175, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3189751215, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 3189751215, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3200899959, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3200909349, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -774 } } }, + .{ .t = 3200909349, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 3200914229, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3200914229, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 3200914229, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3212027402, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3212027402, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 3212027402, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3212033902, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3222960156, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 3222960156, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3222967916, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3222967916, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 3222967916, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 3234186130, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -857 } } }, + .{ .t = 3234186130, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 3234186130, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3234194710, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3234194710, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 3234194710, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3234198480, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3234198480, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1097 } } }, + .{ .t = 3245272663, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1126 } } }, + .{ .t = 3245272663, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3245280873, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3245280873, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3245284263, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1097 } } }, + .{ .t = 3245284263, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3256351647, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3256351647, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3256361897, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1126 } } }, + .{ .t = 3256361897, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3256366557, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -857 } } }, + .{ .t = 3267453910, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3267461450, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3267461450, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1097 } } }, + .{ .t = 3267461450, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3278671394, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3278679494, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3278679494, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1126 } } }, + .{ .t = 3278679494, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3278684284, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1097 } } }, + .{ .t = 3289747017, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3289757957, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -774 } } }, + .{ .t = 3289757957, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1068 } } }, + .{ .t = 3289757957, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3289764977, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3289764977, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3300894251, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3300894251, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3300904161, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3300904161, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3300908771, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3312130554, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3312130554, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 3312130554, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3312142164, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3312145624, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3312145624, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1068 } } }, + .{ .t = 3312145624, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3323185928, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3323185928, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 3323197438, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 3334415941, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3334415941, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3334428191, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3334428191, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3334433441, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3345319335, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3345319335, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 3345329665, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -774 } } }, + .{ .t = 3345329665, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 3345329665, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3345334835, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3356434069, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3356434069, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 3356434069, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3356449919, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3356449919, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 3356449919, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3367716072, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -857 } } }, + .{ .t = 3367716072, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1068 } } }, + .{ .t = 3367728332, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3367728332, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 3367728332, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3367733692, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3367733692, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 3367733692, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3378615526, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3389836929, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -774 } } }, + .{ .t = 3389836929, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 3389836929, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3389847129, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 31648 } } }, + .{ .t = 3389847129, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3389847129, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 3389852719, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 29137 } } }, + .{ .t = 3389852719, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 3401186593, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 26074 } } }, + .{ .t = 3401186593, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3401194003, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 23262 } } }, + .{ .t = 3401194003, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3401194003, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 3401194003, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 3401198713, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 20349 } } }, + .{ .t = 3401198713, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3411932407, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 17587 } } }, + .{ .t = 3411932407, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3411932407, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 3411941077, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 15127 } } }, + .{ .t = 3411941077, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3411941077, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3411944947, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 12617 } } }, + .{ .t = 3411944947, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -829 } } }, + .{ .t = 3411944947, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 3411944947, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3423178470, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 10307 } } }, + .{ .t = 3423178470, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -802 } } }, + .{ .t = 3423178470, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 3423187080, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 8298 } } }, + .{ .t = 3423187080, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 3423187080, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3434307174, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 6340 } } }, + .{ .t = 3434307174, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 3434315334, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 4532 } } }, + .{ .t = 3434315334, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3434318744, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 2975 } } }, + .{ .t = 3434318744, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 866 } } }, + .{ .t = 3445336427, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 1067 } } }, + .{ .t = 3445336427, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 635 } } }, + .{ .t = 3445344507, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 446 } } }, + .{ .t = 3445344507, .pad = 2, .ev = .{ .axis = .{ .idx = 5, .value = 0 } } }, + .{ .t = 3445344507, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 346 } } }, + .{ .t = 3445344507, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 3445348567, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 1854 } } }, + .{ .t = 3445348567, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -59 } } }, + .{ .t = 3456475621, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 3310 } } }, + .{ .t = 3456475621, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -176 } } }, + .{ .t = 3456475621, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 997 } } }, + .{ .t = 3456483971, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 4436 } } }, + .{ .t = 3456483971, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -441 } } }, + .{ .t = 3456487161, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 5891 } } }, + .{ .t = 3456487161, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = -558 } } }, + .{ .t = 22900269279, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 22900269279, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 22900269279, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 22900282319, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 22900282319, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 22900282319, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 22900282319, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 22900288339, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 22900288339, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 22900288339, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 22911078513, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 22911078513, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 22911078513, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 22911090183, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 22922174447, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 22922174447, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -527 } } }, + .{ .t = 22922174447, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1148 } } }, + .{ .t = 22922182927, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 22922182927, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 22922182927, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 22922182927, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 22922186907, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 22933453380, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 22933463530, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 22933463530, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 22933463530, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 22933463530, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1148 } } }, + .{ .t = 22933469520, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 22933469520, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 22933469520, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 22944601464, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 22944601464, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 22944613874, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 22944613874, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 22944613874, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 22944619754, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 22955633677, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 22955633677, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 22955633677, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 22955633677, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 22955647207, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 22955647207, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 22955647207, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 22955647207, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1148 } } }, + .{ .t = 22955652047, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 22955652047, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 22966619841, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 22966619841, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 22966628121, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 22966628121, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 22977745245, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 22977745245, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 22977745245, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 22977745245, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1148 } } }, + .{ .t = 22977753905, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 22977753905, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 22977753905, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 22977757525, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 22988922908, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 22988922908, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 22988936008, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 22988936008, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 22988940638, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 22988940638, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23000140672, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23000140672, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 23000152872, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23000152872, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23000152872, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23000152872, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23000158442, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 23000158442, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23000158442, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23011247285, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23011247285, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23011247285, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23011260265, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23011260265, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23011260265, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23022366569, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23022366569, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23022366569, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 23022366569, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1148 } } }, + .{ .t = 23022380099, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23022380099, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23022385329, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23022385329, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23033207513, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23033207513, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23033215483, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23033215483, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23033215483, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23033215483, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23033219653, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23044563226, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23044563226, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23044563226, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23044572856, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23044572856, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23044576806, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23044576806, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23044576806, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23055818709, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23055818709, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23055828779, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23055828779, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23055828779, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23055832789, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1410 } } }, + .{ .t = 23055832789, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23066680603, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23066680603, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23066680603, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23066690143, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 23066690143, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23066690143, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23066690143, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23077703397, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23077703397, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23077703397, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23077711687, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23077711687, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23077711687, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23077715567, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 23077715567, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23077715567, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23077715567, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23088844720, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23088844720, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23088844720, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 23088844720, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1148 } } }, + .{ .t = 23088853270, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23088853270, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23088853270, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23088856830, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23088856830, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23088856830, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23100184994, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23100184994, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23100184994, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23100197834, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23100202044, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23100202044, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23100202044, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23111316337, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23111328087, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23111328087, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23122579831, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23122579831, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 23122579831, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23122592031, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23122592031, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23122595681, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23122595681, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23122595681, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23133201565, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23133205635, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 728 } } }, + .{ .t = 23133205635, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23133205635, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23144628108, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 3169 } } }, + .{ .t = 23144628108, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 23144628108, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23144628108, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23144628108, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23144640728, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 6314 } } }, + .{ .t = 23144640728, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23144640728, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23144640728, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23144644338, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 10679 } } }, + .{ .t = 23144644338, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23144644338, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23144644338, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23155757852, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 16500 } } }, + .{ .t = 23155757852, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 23155757852, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23155767512, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 23682 } } }, + .{ .t = 23155767512, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23155767512, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23155773302, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 32084 } } }, + .{ .t = 23155773302, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23166856095, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 32766 } } }, + .{ .t = 23166856095, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23166856095, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23166869315, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23166869315, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23177937079, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23177937079, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23177947099, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23177947099, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23177950979, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23177950979, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23177950979, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23188909763, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23188909763, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23188919373, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 23188919373, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23188923533, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23188923533, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23188923533, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23188923533, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23200341706, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23200341706, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 924 } } }, + .{ .t = 23200341706, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23200357446, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23200360546, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 866 } } }, + .{ .t = 23200360546, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23211356329, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1493 } } }, + .{ .t = 23211356329, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 895 } } }, + .{ .t = 23211356329, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23211369469, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23211369469, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 808 } } }, + .{ .t = 23211369469, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23211369469, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23222496653, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 722 } } }, + .{ .t = 23222496653, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23222496653, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23222508723, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 664 } } }, + .{ .t = 23222508723, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23222508723, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23222512923, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23222512923, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 693 } } }, + .{ .t = 23222512923, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23233616896, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 404 } } }, + .{ .t = 23233616896, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23233628876, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 462 } } }, + .{ .t = 23233628876, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23233628876, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1118 } } }, + .{ .t = 23233634716, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 375 } } }, + .{ .t = 23233634716, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23244703810, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 404 } } }, + .{ .t = 23244703810, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23244703810, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23244716710, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23244716710, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 288 } } }, + .{ .t = 23244716710, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23244722470, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 317 } } }, + .{ .t = 23255891634, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 260 } } }, + .{ .t = 23255891634, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23255903964, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1410 } } }, + .{ .t = 23255903964, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 144 } } }, + .{ .t = 23255903964, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23255909564, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23255909564, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 115 } } }, + .{ .t = 23266911057, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 30723 } } }, + .{ .t = 23266911057, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23266911057, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 86 } } }, + .{ .t = 23266924047, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 27437 } } }, + .{ .t = 23266924047, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23266924047, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 115 } } }, + .{ .t = 23266924047, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23278235081, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 24292 } } }, + .{ .t = 23278235081, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23278235081, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 29 } } }, + .{ .t = 23278246901, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 21053 } } }, + .{ .t = 23278246901, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 57 } } }, + .{ .t = 23278246901, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23278246901, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23278254110, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 17814 } } }, + .{ .t = 23278254110, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 86 } } }, + .{ .t = 23278254110, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -498 } } }, + .{ .t = 23278254110, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23289217094, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 14341 } } }, + .{ .t = 23289217094, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1465 } } }, + .{ .t = 23289217094, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 144 } } }, + .{ .t = 23289217094, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23289217094, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23289231434, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 11384 } } }, + .{ .t = 23289231434, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 57 } } }, + .{ .t = 23289236534, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 8708 } } }, + .{ .t = 23289236534, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1438 } } }, + .{ .t = 23289236534, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 0 } } }, + .{ .t = 23300340478, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 6126 } } }, + .{ .t = 23300340478, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23300350538, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 4014 } } }, + .{ .t = 23300350538, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 86 } } }, + .{ .t = 23300354158, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 2465 } } }, + .{ .t = 23300354158, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1410 } } }, + .{ .t = 23300354158, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 288 } } }, + .{ .t = 23311366832, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 634 } } }, + .{ .t = 23311366832, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 462 } } }, + .{ .t = 23311366832, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 23311379542, .pad = 2, .ev = .{ .axis = .{ .idx = 4, .value = 0 } } }, + .{ .t = 23311379542, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1355 } } }, + .{ .t = 23311379542, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 779 } } }, + .{ .t = 23311379542, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23322638775, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1272 } } }, + .{ .t = 23322638775, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23322638775, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23322649765, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -1051 } } }, + .{ .t = 23322649765, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23322649765, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23322654995, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -885 } } }, + .{ .t = 23322654995, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 23333351109, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -691 } } }, + .{ .t = 23333351109, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23333359049, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -553 } } }, + .{ .t = 23333359049, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23333362519, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 23333362519, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23333362519, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23344695372, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23344706662, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -525 } } }, + .{ .t = 23344706662, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 953 } } }, + .{ .t = 23344711982, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -553 } } }, + .{ .t = 23344711982, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23355868326, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -498 } } }, + .{ .t = 23355868326, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 23355878956, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -525 } } }, + .{ .t = 23355878956, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23355878956, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23355878956, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1087 } } }, + .{ .t = 23355884866, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 23355884866, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23355884866, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 23366942749, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -553 } } }, + .{ .t = 23366952219, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -525 } } }, + .{ .t = 23366952219, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23366952219, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23366952219, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23378047613, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -553 } } }, + .{ .t = 23378047613, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 23378064723, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -525 } } }, + .{ .t = 23378064723, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23378064723, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23388957907, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -553 } } }, + .{ .t = 23388957907, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 23388957907, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23388957907, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 23388967217, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 23388967217, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23388970117, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -525 } } }, + .{ .t = 23388970117, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23388970117, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23388970117, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23400316180, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23400325960, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -580 } } }, + .{ .t = 23400325960, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 23400325960, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23400330510, .pad = 2, .ev = .{ .axis = .{ .idx = 0, .value = -525 } } }, + .{ .t = 23400330510, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 981 } } }, + .{ .t = 23400330510, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23411327274, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 23411337364, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 23411337364, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 23422593127, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23422593127, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23422603997, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -410 } } }, + .{ .t = 23422603997, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 23422607677, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23422607677, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23433465571, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 23433465571, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, + .{ .t = 23433473571, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 23433473571, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -469 } } }, + .{ .t = 23433473571, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1057 } } }, + .{ .t = 23444613485, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1039 } } }, + .{ .t = 23444623255, .pad = 2, .ev = .{ .axis = .{ .idx = 2, .value = -439 } } }, + .{ .t = 23444626645, .pad = 2, .ev = .{ .axis = .{ .idx = 1, .value = 1010 } } }, + .{ .t = 23444626645, .pad = 2, .ev = .{ .axis = .{ .idx = 3, .value = 1027 } } }, } } diff --git a/test/fs_bench.zig b/test/fs_bench.zig index 4764049f..a8a8fd8c 100644 --- a/test/fs_bench.zig +++ b/test/fs_bench.zig @@ -113,7 +113,7 @@ fn checkReply(s: *Session, req: ctlfs.Req, reply: ctlfs.Reply) !void { if (reply.payload != .staged or reply.payload.staged != bytes.len or bytes.len > req.size) return error.IncorrectReply; const pane = s.core.panes[s.file_id].?; - if (req.node == @intFromEnum(ctlfs.TopFile.index)) { + if (req.node == @backingInt(ctlfs.TopFile.index)) { var expected_buf: [4200]u8 = undefined; const expected = try std.fmt.bufPrint(&expected_buf, "{d} text {d} {s}\n", .{ s.file_serial, @intFromBool(pane.file.?.revision != pane.file.?.saved_revision), pane.file.?.path }); if (!std.mem.eql(u8, expected, bytes)) return error.IncorrectReply; @@ -134,7 +134,7 @@ fn checkReply(s: *Session, req: ctlfs.Req, reply: ctlfs.Reply) !void { if (reply.payload != .staged or reply.payload.staged != bytes.len or bytes.len > req.size) return error.IncorrectReply; const names = [_][]const u8{ "README", "index", "status", "focus", "ctl", "commands", "look", "exec", "log", "screen", "listeners", "pane", "os" }; - const nodes = [_]u64{ @intFromEnum(ctlfs.TopFile.README), @intFromEnum(ctlfs.TopFile.index), @intFromEnum(ctlfs.TopFile.status), @intFromEnum(ctlfs.TopFile.focus), @intFromEnum(ctlfs.TopFile.ctl), @intFromEnum(ctlfs.TopFile.commands), @intFromEnum(ctlfs.TopFile.look), @intFromEnum(ctlfs.TopFile.exec), @intFromEnum(ctlfs.TopFile.log), @intFromEnum(ctlfs.TopFile.screen), @intFromEnum(ctlfs.TopFile.listeners), @intFromEnum(ctlfs.TopFile.pane), filesystem.os_root }; + const nodes = [_]u64{ @backingInt(ctlfs.TopFile.README), @backingInt(ctlfs.TopFile.index), @backingInt(ctlfs.TopFile.status), @backingInt(ctlfs.TopFile.focus), @backingInt(ctlfs.TopFile.ctl), @backingInt(ctlfs.TopFile.commands), @backingInt(ctlfs.TopFile.look), @backingInt(ctlfs.TopFile.exec), @backingInt(ctlfs.TopFile.log), @backingInt(ctlfs.TopFile.screen), @backingInt(ctlfs.TopFile.listeners), @backingInt(ctlfs.TopFile.pane), filesystem.os_root }; var off: usize = 0; var entry: usize = 0; while (off < bytes.len) : (entry += 1) { @@ -253,7 +253,7 @@ pub fn main(init: std.process.Init) !void { try bench(&s, "read index", reps, .{ .tag = 6, .op = .read, - .node = @intFromEnum(ctlfs.TopFile.index), + .node = @backingInt(ctlfs.TopFile.index), .size = 4096, }, "one line per pane"); try bench(&s, "readdir root", reps, .{ diff --git a/test/lspfixture/broken.zig b/test/lspfixture/broken.zig index 22c86c9b..b27840cd 100644 --- a/test/lspfixture/broken.zig +++ b/test/lspfixture/broken.zig @@ -20,6 +20,6 @@ pub fn hasUnusedLocal() u32 { return 7; } -pub fn badly_spaced ( a : u32 , b : u32 ) u32 { - return a+b; +pub fn badly_spaced(a: u32, b: u32) u32 { + return a + b; } diff --git a/test/output.zig b/test/output.zig index 6ea6f6fa..8403effa 100644 --- a/test/output.zig +++ b/test/output.zig @@ -475,7 +475,7 @@ test "Mini syntax colors survive toggles themes and rendering without source acc try panes.mini.open(p, 0, "demo.zig"); const id = p.active; const mini = p.panes[id].?; - const keyword = std.mem.indexOfScalar(u8, mini.file.?.mini.?.colors, @intFromEnum(pardes.syntax.Syn.keyword)) orelse return error.MissingKeywordColor; + const keyword = std.mem.indexOfScalar(u8, mini.file.?.mini.?.colors, @backingInt(pardes.syntax.Syn.keyword)) orelse return error.MissingKeywordColor; // Direct pane construction bypasses the host update's layout sync. p.update(.{ .resize = .{ .cols = 80, .rows = 24 } }); const position = modal.positionAt(mini.file.?.content, keyword); @@ -1656,7 +1656,7 @@ test "stacked search and LSP results retain source tint navigation and dump owne } try std.testing.expectEqual(@as(usize, 6), marked); const number = std.mem.indexOf(u8, file.content, "42").?; - try std.testing.expectEqual(@intFromEnum(pardes.syntax.Syn.number), file.highlights[number]); + try std.testing.expectEqual(@backingInt(pardes.syntax.Syn.number), file.highlights[number]); p.active = id; pane.body.mode = .normal; pardes.look.armLookWalk(p, id); @@ -1815,7 +1815,7 @@ test "location cache eviction retains early colors and honors disk and unsaved r return error.MissingEarlyContext; } }; - try std.testing.expectEqual(@intFromEnum(pardes.syntax.Syn.comment), try Color.valueColor(file)); + try std.testing.expectEqual(@backingInt(pardes.syntax.Syn.comment), try Color.valueColor(file)); const single = "f00.c:4:1-6 needle();\n"; // Put the evicted file back before a same-size edit tests exact-byte keys. try panes.Output.fillResults(p, 0, dir, .search, "eviction", try p.gpa.dupe(u8, single), null); @@ -1823,14 +1823,14 @@ test "location cache eviction retains early colors and honors disk and unsaved r try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "f00.c", .data = code }); try panes.Output.fillResults(p, 0, dir, .search, "eviction", try p.gpa.dupe(u8, single), null); try std.testing.expect(p.locations_cache.analyses > analyses); - try std.testing.expectEqual(@intFromEnum(pardes.syntax.Syn.number), try Color.valueColor(file)); + try std.testing.expectEqual(@backingInt(pardes.syntax.Syn.number), try Color.valueColor(file)); // An open buffer has priority over that disk revision, even with equal size. p.gpa.free(source.file.?.path); source.file.?.path = try std.fs.path.join(p.gpa, &.{ dir, "f00.c" }); panes.File.setContent(p, &source.file.?, try p.gpa.dupe(u8, comment)); try panes.Output.fillResults(p, 0, dir, .search, "eviction", try p.gpa.dupe(u8, single), null); - try std.testing.expectEqual(@intFromEnum(pardes.syntax.Syn.comment), try Color.valueColor(file)); + try std.testing.expectEqual(@backingInt(pardes.syntax.Syn.comment), try Color.valueColor(file)); try std.testing.expectEqualStrings(comment, source.file.?.content); } diff --git a/test/panes.zig b/test/panes.zig index 54100f91..c8f4b7eb 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -3193,7 +3193,7 @@ const OutputTests = struct { p.update(.{ .mouse = .{ .button = config.select_button, .kind = .press, .col = x, .row = y } }); p.update(.{ .mouse = .{ .button = config.select_button, .kind = .drag, .col = x + 2, .row = y + 1 } }); try std.testing.expect(p.drag == .select); - try std.testing.expectEqual(.dragging, result.sel[@intFromEnum(config.select_button)].state); + try std.testing.expectEqual(.dragging, result.sel[@backingInt(config.select_button)].state); try fillResults(p, 0, "/", .{ .query = .hover }, "", try p.gpa.dupe(u8, "short\n"), null); try std.testing.expect(p.drag == .none); p.update(.{ .mouse = .{ .button = config.select_button, .kind = .release, .col = x + 2, .row = y + 1 } }); diff --git a/test/pdf.zig b/test/pdf.zig index a51fd1a9..6c9308d4 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -25,7 +25,7 @@ const themes = pardes.themes; const pdf_raster_policy = pardes.pdf_raster_policy; const PDF_PAGE_GAP_PX = pardes.PDF_PAGE_GAP_PX; const BOX_H = pardes.BOX_H; -const sel_slot = @intFromEnum(config.select_button); +const sel_slot = @backingInt(config.select_button); const pane_tail = " " ++ config.pdf_pane_builtins_str; fn hasPdf(pane: *const pardes.Pane) bool { @@ -483,10 +483,10 @@ test "`:N` on a PDF turns to page N, from the pane and from the root's look, and try std.testing.expectEqual(failures, p.fs.failures); // Over 9P too: the root's look at `@pN:2` answers ok and logs no err. const ctlfs = pardes.ctlfs; - const written = p.serveFs(.{ .tag = 1, .op = .write, .node = @intFromEnum(ctlfs.TopFile.look), .data = try std.fmt.bufPrint(&line, "@p{d}:2\n", .{doc.serial}) }); + const written = p.serveFs(.{ .tag = 1, .op = .write, .node = @backingInt(ctlfs.TopFile.look), .data = try std.fmt.bufPrint(&line, "@p{d}:2\n", .{doc.serial}) }); try std.testing.expectEqual(ctlfs.Status.ok, written.status); try std.testing.expectEqual(@as(usize, 1), doc.pdf.?.page); - const log = @intFromEnum(ctlfs.TopFile.log); + const log = @backingInt(ctlfs.TopFile.log); const h = p.serveFs(.{ .tag = 2, .op = .open, .node = log }).handle; const record = p.fsPayload(p.serveFs(.{ .tag = 3, .op = .read, .node = log, .handle = h, .size = 1 << 16 })); try std.testing.expect(std.mem.indexOf(u8, record, "\nerr ") == null); diff --git a/test/pdf_scroll_bench.zig b/test/pdf_scroll_bench.zig index fdc42660..0f93068d 100644 --- a/test/pdf_scroll_bench.zig +++ b/test/pdf_scroll_bench.zig @@ -475,7 +475,7 @@ const Recorder = struct { self.visual = mix(self.visual, place.w); self.visual = mix(self.visual, place.h); self.visual = mix(self.visual, place.native.page); - self.visual = mix(self.visual, @intFromEnum(place.native.fit)); + self.visual = mix(self.visual, @backingInt(place.native.fit)); self.visual = mix(self.visual, place.native.pan_x); self.visual = mix(self.visual, place.native.pan_y); self.visual = mix(self.visual, @as(u32, @bitCast(place.native.pixel_offset_y))); diff --git a/test/perf-baseline-gui-debug.json b/test/perf-baseline-gui-debug.json index 4b60520b..ffcd678f 100644 --- a/test/perf-baseline-gui-debug.json +++ b/test/perf-baseline-gui-debug.json @@ -1 +1 @@ -{"harness":"6cf9f4b8943e7e29","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1732,"med_us":1881,"p90_us":2035,"max_us":2072},{"op":"render","fixture":"medium","min_us":89,"med_us":92,"p90_us":101,"max_us":102},{"op":"key-down","fixture":"medium","min_us":92,"med_us":94,"p90_us":100,"max_us":100},{"op":"key-right","fixture":"medium","min_us":91,"med_us":93,"p90_us":105,"max_us":109},{"op":"page-down","fixture":"medium","min_us":91,"med_us":95,"p90_us":99,"max_us":106},{"op":"wheel","fixture":"medium","min_us":90,"med_us":95,"p90_us":101,"max_us":101},{"op":"edit-char","fixture":"medium","min_us":1226,"med_us":1678,"p90_us":2093,"max_us":2323},{"op":"edit-twin","fixture":"medium","min_us":2275,"med_us":2697,"p90_us":2868,"max_us":2920},{"op":"body-2m","fixture":"medium","min_us":5213,"med_us":11333,"p90_us":18974,"max_us":18999},{"op":"body-appends","fixture":"medium","min_us":175012,"med_us":260087,"p90_us":317184,"max_us":317469},{"op":"deep-sel","fixture":"medium","min_us":83,"med_us":85,"p90_us":86,"max_us":98}]} +{"harness":"15bee9f100e5ef64","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1744,"med_us":1832,"p90_us":2468,"max_us":2524},{"op":"render","fixture":"medium","min_us":88,"med_us":97,"p90_us":114,"max_us":115},{"op":"key-down","fixture":"medium","min_us":95,"med_us":98,"p90_us":104,"max_us":105},{"op":"key-right","fixture":"medium","min_us":92,"med_us":96,"p90_us":98,"max_us":105},{"op":"page-down","fixture":"medium","min_us":91,"med_us":95,"p90_us":97,"max_us":105},{"op":"wheel","fixture":"medium","min_us":87,"med_us":93,"p90_us":99,"max_us":100},{"op":"edit-char","fixture":"medium","min_us":1241,"med_us":1459,"p90_us":1691,"max_us":1724},{"op":"edit-twin","fixture":"medium","min_us":2592,"med_us":3003,"p90_us":3481,"max_us":3503},{"op":"body-2m","fixture":"medium","min_us":4576,"med_us":8262,"p90_us":15424,"max_us":17259},{"op":"body-appends","fixture":"medium","min_us":152003,"med_us":227268,"p90_us":272872,"max_us":326510},{"op":"deep-sel","fixture":"medium","min_us":82,"med_us":83,"p90_us":90,"max_us":93}]} diff --git a/test/perf-baseline-tty-debug.json b/test/perf-baseline-tty-debug.json index a01335bd..b8e534c4 100644 --- a/test/perf-baseline-tty-debug.json +++ b/test/perf-baseline-tty-debug.json @@ -1 +1 @@ -{"harness":"6cf9f4b8943e7e29","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2169,"med_us":2697,"p90_us":3126,"max_us":3207},{"op":"render","fixture":"medium","min_us":89,"med_us":96,"p90_us":101,"max_us":115},{"op":"key-down","fixture":"medium","min_us":93,"med_us":98,"p90_us":104,"max_us":115},{"op":"key-right","fixture":"medium","min_us":96,"med_us":97,"p90_us":102,"max_us":108},{"op":"page-down","fixture":"medium","min_us":96,"med_us":98,"p90_us":102,"max_us":103},{"op":"wheel","fixture":"medium","min_us":89,"med_us":100,"p90_us":128,"max_us":168},{"op":"edit-char","fixture":"medium","min_us":1821,"med_us":2274,"p90_us":2404,"max_us":2610},{"op":"edit-twin","fixture":"medium","min_us":2710,"med_us":3180,"p90_us":3413,"max_us":3636},{"op":"body-2m","fixture":"medium","min_us":9090,"med_us":14438,"p90_us":18158,"max_us":22063},{"op":"body-appends","fixture":"medium","min_us":241367,"med_us":375874,"p90_us":470623,"max_us":528094},{"op":"deep-sel","fixture":"medium","min_us":88,"med_us":89,"p90_us":90,"max_us":90}]} +{"harness":"15bee9f100e5ef64","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1747,"med_us":1912,"p90_us":2150,"max_us":2247},{"op":"render","fixture":"medium","min_us":89,"med_us":95,"p90_us":102,"max_us":104},{"op":"key-down","fixture":"medium","min_us":97,"med_us":101,"p90_us":107,"max_us":133},{"op":"key-right","fixture":"medium","min_us":93,"med_us":104,"p90_us":109,"max_us":112},{"op":"page-down","fixture":"medium","min_us":92,"med_us":96,"p90_us":106,"max_us":108},{"op":"wheel","fixture":"medium","min_us":90,"med_us":92,"p90_us":96,"max_us":96},{"op":"edit-char","fixture":"medium","min_us":1167,"med_us":1345,"p90_us":1483,"max_us":1627},{"op":"edit-twin","fixture":"medium","min_us":2319,"med_us":2921,"p90_us":3425,"max_us":3539},{"op":"body-2m","fixture":"medium","min_us":4333,"med_us":7752,"p90_us":15941,"max_us":17192},{"op":"body-appends","fixture":"medium","min_us":149149,"med_us":234177,"p90_us":285302,"max_us":295516},{"op":"deep-sel","fixture":"medium","min_us":83,"med_us":88,"p90_us":99,"max_us":119}]} diff --git a/test/perf-baseline-tty-fast.json b/test/perf-baseline-tty-fast.json index 04fc88d3..46125349 100644 --- a/test/perf-baseline-tty-fast.json +++ b/test/perf-baseline-tty-fast.json @@ -1 +1 @@ -{"harness":"6cf9f4b8943e7e29","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"fast","c_optimize":"fast","terminal_optimize":"fast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1695,"med_us":2024,"p90_us":2180,"max_us":2292},{"op":"render","fixture":"medium","min_us":79,"med_us":82,"p90_us":92,"max_us":94},{"op":"key-down","fixture":"medium","min_us":81,"med_us":82,"p90_us":83,"max_us":84},{"op":"key-right","fixture":"medium","min_us":80,"med_us":82,"p90_us":91,"max_us":91},{"op":"page-down","fixture":"medium","min_us":81,"med_us":84,"p90_us":90,"max_us":171},{"op":"wheel","fixture":"medium","min_us":79,"med_us":80,"p90_us":90,"max_us":101},{"op":"edit-char","fixture":"medium","min_us":1332,"med_us":1691,"p90_us":1967,"max_us":1987},{"op":"edit-twin","fixture":"medium","min_us":2160,"med_us":2457,"p90_us":2718,"max_us":2757},{"op":"body-2m","fixture":"medium","min_us":5047,"med_us":13525,"p90_us":16257,"max_us":20323},{"op":"body-appends","fixture":"medium","min_us":155834,"med_us":261597,"p90_us":329936,"max_us":333538},{"op":"deep-sel","fixture":"medium","min_us":75,"med_us":76,"p90_us":84,"max_us":96}]} +{"harness":"15bee9f100e5ef64","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"fast","c_optimize":"fast","terminal_optimize":"fast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1904,"med_us":2040,"p90_us":2290,"max_us":2600},{"op":"render","fixture":"medium","min_us":80,"med_us":83,"p90_us":88,"max_us":93},{"op":"key-down","fixture":"medium","min_us":81,"med_us":87,"p90_us":93,"max_us":109},{"op":"key-right","fixture":"medium","min_us":79,"med_us":82,"p90_us":86,"max_us":96},{"op":"page-down","fixture":"medium","min_us":79,"med_us":83,"p90_us":89,"max_us":93},{"op":"wheel","fixture":"medium","min_us":77,"med_us":79,"p90_us":82,"max_us":83},{"op":"edit-char","fixture":"medium","min_us":1139,"med_us":1338,"p90_us":1453,"max_us":1578},{"op":"edit-twin","fixture":"medium","min_us":2515,"med_us":2776,"p90_us":2879,"max_us":2907},{"op":"body-2m","fixture":"medium","min_us":4832,"med_us":7650,"p90_us":15076,"max_us":15371},{"op":"body-appends","fixture":"medium","min_us":165796,"med_us":240881,"p90_us":284919,"max_us":292573},{"op":"deep-sel","fixture":"medium","min_us":73,"med_us":75,"p90_us":83,"max_us":93}]} diff --git a/test/perf.zig b/test/perf.zig index d01d1bb5..7662d028 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -517,8 +517,8 @@ fn gate(cells: *const [std.enums.values(Op).len][fixtures.len]Cell, base: *const }; // Typing beside a twin costs about what typing alone does, whatever the // baseline: the twin takes the splice, never a copy of the text. - const twin_op = @intFromEnum(Op.edit_twin); - const alone_op = @intFromEnum(Op.edit_char); + const twin_op = @backingInt(Op.edit_twin); + const alone_op = @backingInt(Op.edit_char); for (fixtures, 0..) |fx, fi| { const twin = cells[twin_op][fi].min_us; const alone = cells[alone_op][fi].min_us; @@ -1220,7 +1220,7 @@ fn measureMini(io: std.Io, fallback: std.mem.Allocator, reps: usize, json: bool) break :blk try pardes.syntax.highlightFileRange(gpa, path, source, 0, source.len); }; defer gpa.free(styles); - if (styles.len != source.len or std.mem.indexOfScalar(u8, styles, @intFromEnum(pardes.syntax.Syn.comment)) == null) + if (styles.len != source.len or std.mem.indexOfScalar(u8, styles, @backingInt(pardes.syntax.Syn.comment)) == null) return error.MiniSyntaxUnavailable; const expected = try pardes.panes.mini.generate(gpa, source, styles); defer expected.deinit(gpa); diff --git a/test/unit_profile.zig b/test/unit_profile.zig index 59794df9..941efeb2 100644 --- a/test/unit_profile.zig +++ b/test/unit_profile.zig @@ -6,7 +6,7 @@ const Memory = struct { rss_after_bytes: ?usize = null, cumulative_peak_rss_byte fn send(io: std.Io, file: std.Io.File, tag: Client.Tag, body: []const u8, deadline: std.Io.Timeout) !void { var header: [8]u8 = undefined; - std.mem.writeInt(u32, header[0..4], @intFromEnum(tag), .little); + std.mem.writeInt(u32, header[0..4], @backingInt(tag), .little); std.mem.writeInt(u32, header[4..8], @intCast(body.len), .little); for ([_][]const u8{ &header, body }) |part| { var offset: usize = 0; @@ -36,7 +36,7 @@ fn readAll(io: std.Io, file: std.Io.File, bytes: []u8, deadline: std.Io.Timeout) fn receive(io: std.Io, file: std.Io.File, gpa: std.mem.Allocator, deadline: std.Io.Timeout) !struct { tag: Server.Tag, body: []u8 } { var header: [8]u8 = undefined; try readAll(io, file, &header, deadline); - const tag: Server.Tag = @enumFromInt(std.mem.readInt(u32, header[0..4], .little)); + const tag: Server.Tag = @fromBackingInt(@intCast(std.mem.readInt(u32, header[0..4], .little))); const len = std.mem.readInt(u32, header[4..8], .little); if (len > 16 * 1024 * 1024) return error.MessageTooLarge; const bytes = try gpa.alloc(u8, len); -- cgit v1.3 From 0073d05329335dbb0eb85f5c3044e42805d144e5 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 23 Oct 2026 17:10:58 -0300 Subject: Callstack lists every caller and pages a tree too big for one query; memory bounds and resident-size fixes Callstack walks while the server answers, counts on the message row past a second, puts test callers last at each level, and ends a tree past one query's memory (memory.limits.arena.lsp_query, a 256 MiB region taken and given back per query) in a row whose Callstack shows the next page. Grep reads whole files. New hard limits: undo text per file, image decode pixels, the LSP snapshot of other open files, one paste. Safe builds no longer fill worst-case buffers with 0xAA (memory.unfilled), big regions are kept off transparent huge pages, and malloc_trim runs after big results. Also: Look's git show pages into a +Diff, and dropped marks in File. Co-Authored-By: Claude Opus 5.5 --- build.zig.zon | 4 +- docs/typ/guide.typ | 14 +- docs/typ/reference.typ | 9 +- src/9p.zig | 24 -- src/9p_io.zig | 121 +++--- src/File.zig | 141 +++++-- src/Registers.zig | 13 + src/ShaderBuild.zig | 23 +- src/builtins.zig | 3 + src/colors.zig | 2 +- src/config.zig | 66 +--- src/crash.zig | 6 + src/detached/server.zig | 29 +- src/dump.zig | 11 - src/edit.zig | 190 ++++++++-- src/exec.zig | 6 + src/fs.zig | 82 ++-- src/gui/gui.zig | 329 ++++++---------- src/gui/pet.zig | 29 +- src/host_io.zig | 103 ++++-- src/hunks.zig | 19 +- src/image.zig | 8 +- src/locations.zig | 135 +++++-- src/look.zig | 61 ++- src/lsp/lsp.zig | 17 +- src/lsp/lsp_client.zig | 761 ++++++++++++++++++++++++++------------ src/macos.zig | 17 +- src/main.zig | 12 +- src/memory.zig | 98 +++++ src/mini.zig | 16 +- src/modal.zig | 139 +++++-- src/mouse.zig | 11 +- src/ninep/addr.zig | 42 ++- src/ninep/ctl.zig | 4 + src/panes.zig | 3 + src/pardes.zig | 42 ++- src/regexp.zig | 11 +- src/sam_edit.zig | 15 + src/selection_pipe.zig | 11 +- src/surface.zig | 5 - src/terminal.zig | 86 +---- src/tty/tty.zig | 51 ++- test/lspbench.zig | 22 +- test/panes.zig | 3 - test/perf-baseline-gui-debug.json | 2 +- test/perf-baseline-tty-debug.json | 2 +- test/perf-baseline-tty-fast.json | 2 +- test/perf.zig | 21 +- 48 files changed, 1843 insertions(+), 978 deletions(-) (limited to 'src/File.zig') diff --git a/build.zig.zon b/build.zig.zon index 292bd479..7885fd4e 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -9,8 +9,8 @@ // read-only HTTPS URL is what a manifest can carry. Re-pin with // `zig fetch --save=cloud9 git+https://git.sr.ht/~gbrls/cloud9#`. .cloud9 = .{ - .url = "git+https://git.sr.ht/~gbrls/cloud9#d5c37d9122240fe95d308fbe15874e14dd786c5a", - .hash = "cloud9-0.1.0-yt86qnAvHgB1dEWGakukcJ54GZ7J3mv_lm_kApzAuEOY", + .url = "git+https://git.sr.ht/~gbrls/cloud9#0702e33bcfadf0abd9ccbaa8b681a19a84c332fe", + .hash = "cloud9-0.1.0-yt86qkExHgCRI7_eJsztRECamioWguBj2mTFsJ5N-AOn", }, // Pinned to the exact libvaxis commit ghostty is built against, so it // is compatible with ghostty's uucode configuration (the one we share diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index a5327a44..e60b4231 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -240,11 +240,19 @@ wrapping. Cross-directory Look paths are shortened when possible. pane. #word("LookNext") / #word("LookPrev") (#keys("SPC j n", "SPC j p")) select locations without opening them. The view follows the language server's static call hierarchy; recursive paths are marked `↻`, and a -large hierarchy invites continuing from another function. +hierarchy deeper than the limit invites continuing from another function. +Every caller is listed: the walk runs as long as the server keeps answering, +says how many callers it has found on the message row once it takes more +than a second, and shows what it found if the server stops answering. +Asking anything else stops it. A tree too big for one page (about 100,000 +rows, the memory one query may use) ends in a row saying so: running +#word("Callstack") in `+Callstack` shows the next page, from where this +one stopped, with that caller's own callers above it again. +At each level, callers whose function or file name contains "test" come +after the rest. #word("CallstackDepth") reports the current caller depth; `CallstackDepth 16` changes it for subsequent queries. The default is 8 -levels, and the accepted range is 1–64. The view also caps collection at -64 callers. +levels, and the accepted range is 1–64. `CallstackLayout stacked` (the default) puts each signature and call snippet below its location, aligned with the location text; `CallstackLayout inline` puts it diff --git a/docs/typ/reference.typ b/docs/typ/reference.typ index bb13b011..c14ad659 100644 --- a/docs/typ/reference.typ +++ b/docs/typ/reference.typ @@ -264,7 +264,9 @@ A line written to #file("exec") is #word("Exec"): a declaration; from a use it reaches every file); #word("Callstack") (#key("g c") or #key("SPC l b")) opens and focuses `+Callstack`, with static caller ancestry, tree-sitter signatures and Look locations - for callers and call sites. #word("CallstackDepth") reports or sets the + for callers and call sites, test callers after the rest at each level; run + in `+Callstack` itself, it shows the next page of a tree too big for one. + #word("CallstackDepth") reports or sets the runtime depth (1–64, default 8) for subsequent queries. `CallstackLayout stacked` (the default) aligns snippets below their locations; `CallstackLayout inline` places the snippets beside them. @@ -971,12 +973,11 @@ one a #file("exec") open still holds is never reused. In a command pane, #key("n = Find and Grep #word("Find") matches file names, #word("Grep") the text of lines, both literally and -ignoring ASCII case. #word("Grep") reads at most 256 KiB of a file and stops at 512 +ignoring ASCII case. #word("Grep") reads whole files and stops at 512 hits, #word("Find") at 512 names. The walk stops at 20000 files or 100000 entries, 16 deep, and passes over `.git`, `.jj`, `target`, `node_modules`, `.venv`, `__pycache__`, `.zig-cache` and `zig-out`. A cap hit, or a -directory it could not open, is said at the end: `cut at 512 hits`, `N -files read only in part (first 256 KiB)`, `walk cut at N entries`, `N +directory it could not open, is said at the end: `cut at 512 hits`, `walk cut at N entries`, `N directories skipped: permission denied`. A search that finds nothing and skipped nothing fails, `Grep: text not found`, and leaves the `+Search` as it was. diff --git a/src/9p.zig b/src/9p.zig index 67b3b39a..0979b66a 100644 --- a/src/9p.zig +++ b/src/9p.zig @@ -5,16 +5,10 @@ const cloud9 = @import("cloud9"); pub const fs = cloud9.fs; pub const Server = cloud9.fs.Server; -pub const Error = cloud9.Error; -pub const Type = cloud9.Type; -pub const isT = cloud9.isT; pub const header_len = cloud9.header_len; -pub const qid_len = cloud9.qid_len; -pub const stat_fixed = cloud9.stat_fixed; pub const notag = cloud9.notag; pub const nofid = cloud9.nofid; pub const max_welem = cloud9.max_welem; -pub const iohdrsz = cloud9.iohdrsz; pub const Qid = cloud9.Qid; pub const Stat = cloud9.Stat; pub const Msg = cloud9.Msg; @@ -23,29 +17,11 @@ pub const frameLen = cloud9.frameLen; pub const encode = cloud9.encode; pub const decode = cloud9.decode; pub const qtdir = cloud9.qtdir; -pub const qtappend = cloud9.qtappend; -pub const qtexcl = cloud9.qtexcl; -pub const qtmount = cloud9.qtmount; -pub const qtauth = cloud9.qtauth; -pub const qttmp = cloud9.qttmp; -pub const qtfile = cloud9.qtfile; -pub const dmdir = cloud9.dmdir; -pub const dmappend = cloud9.dmappend; -pub const dmexcl = cloud9.dmexcl; -pub const dmmount = cloud9.dmmount; -pub const dmauth = cloud9.dmauth; -pub const dmtmp = cloud9.dmtmp; -pub const dmperm = cloud9.dmperm; pub const Client = cloud9.Client; -pub const ClientError = cloud9.ClientError; -pub const max_tags = cloud9.max_tags; pub const oread = cloud9.oread; pub const owrite = cloud9.owrite; pub const ordwr = cloud9.ordwr; -pub const oexec = cloud9.oexec; pub const otrunc = cloud9.otrunc; -pub const ocexec = cloud9.ocexec; -pub const orclose = cloud9.orclose; pub const errmax = cloud9.fs.errmax; pub const errString = cloud9.fs.errString; pub const msize_min = cloud9.fs.msize_min; diff --git a/src/9p_io.zig b/src/9p_io.zig index 446c24de..87972b43 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -174,8 +174,15 @@ pub const Listener = struct { io: std.Io, /// The core that answers; `reset` puts a replacement in. core: *pardes.Pardes, - runner: Runner = undefined, + /// cloud9's runner, sized for every connection's buffers and parks (some + /// 136 MiB): pages of its own (`allocRunner`), written only as clients + /// take slots, so an idle session does not hold them resident. + runner: *Runner = undefined, stopping: std.atomic.Value(bool) = .init(false), + /// The watchers of held Edit writes (watchEdit): canceled and awaited + /// by `deinit`, once the turn lets a waiting one through, so none wakes + /// into a freed Listener. + edit_watchers: std.Io.Group = .init, /// A connection wrote the Restore and has yet to answer it. restore_writer: std.atomic.Value(bool) = .init(false), /// Clients turned away with every slot taken, since the log last said so. @@ -354,8 +361,7 @@ pub const Listener = struct { const later: pardes.ctlfs.Reply = .{ .tag = req.tag, .status = .again }; const ticket = conn.hold(&later) orelse return; core.fs.edit_hold = .{ .asker = conn, .slot = ticket.slot, .seq = ticket.seq, .tag = req.tag, .node = req.node, .handle = req.handle, .written = reply.written }; - const watcher = std.Thread.spawn(.{}, watchEdit, .{ l, conn, ticket }) catch return; - watcher.detach(); + l.edit_watchers.concurrent(l.io, watchEdit, .{ l, conn, ticket }) catch {}; return; } const restoring = core.restore_req != null; @@ -457,13 +463,13 @@ pub const Listener = struct { /// flush, so it is looked for, every 100 ms; a park out for a retry is /// not waiting either, so only three looks in a row with no write being /// served count. - fn watchEdit(l: *Listener, conn: *Runner.Conn, ticket: cloud9.fs.Ticket) void { - const io = pardes.turn.io orelse return; + fn watchEdit(l: *Listener, conn: *Runner.Conn, ticket: cloud9.fs.Ticket) error{Canceled}!void { var misses: u8 = 0; while (!l.stopping.load(.acquire)) { - io.sleep(.fromMilliseconds(100), .awake) catch return; + try l.io.sleep(.fromMilliseconds(100), .awake); _ = pardes.turn.take(); defer pardes.turn.give(); + if (l.stopping.load(.acquire)) return; const core = l.core; const h = core.fs.edit_hold orelse return; if (h.slot != ticket.slot or h.seq != ticket.seq or h.asker != @as(*anyopaque, conn)) return; @@ -914,6 +920,7 @@ pub const Listener = struct { // A connection task may be waiting for the turn; it answers // nothing more once stopping, but the wait itself must end. pardes.turn.rest(); + l.edit_watchers.cancel(l.io); // An answer given as the editor quit (a Kill written to /ctl) // may still be on its way out: let it go before the cut. const deadline = nowMs() +| 200; @@ -942,10 +949,26 @@ pub const Listener = struct { z[l.path_len] = 0; _ = libc.unlink(z[0..l.path_len :0]); } + freeRunner(l.runner); gpa.destroy(l); } }; +/// The runner's memory, from the page allocator with no fill: an Allocator's +/// `create` writes `undefined` over all of it in a safe build, which would make +/// every page resident at startup. +fn allocRunner() ?*Runner { + if (comptime !supported) return @constCast(&@as(Runner, {})); + const bytes = std.heap.page_allocator.rawAlloc(@sizeOf(Runner), .of(Runner), @returnAddress()) orelse return null; + @import("memory.zig").sparse(bytes[0..@sizeOf(Runner)]); + return @ptrCast(@alignCast(bytes)); +} + +fn freeRunner(runner: *Runner) void { + if (comptime !supported) return; + std.heap.page_allocator.rawFree(@as([*]u8, @ptrCast(runner))[0..@sizeOf(Runner)], .of(Runner), @returnAddress()); +} + /// The socket this process listens on, kept where a fatal signal's handler /// can reach it without allocating (unlinkOwnSocket); empty when none. var own_socket: [sun_path_len:0]u8 = undefined; @@ -1065,6 +1088,10 @@ pub fn listen(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes, named: [ } const l = gpa.create(Listener) catch return null; l.* = .{ .io = io, .core = core }; + l.runner = allocRunner() orelse { + gpa.destroy(l); + return null; + }; pardes.turn.start(io); pardes.turn.wake_parked = Listener.wakeParked; pardes.turn.answer_held = Listener.answerHeld; @@ -1551,7 +1578,7 @@ test "a socket path too long for sun_path is no listener, and leaves the editor' defer if (old_copy) |o| { _ = setenv("XDG_RUNTIME_DIR", o, 1); } else { - _ = unsetenv("XDG_RUNTIME_DIR"); + _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); }; const long = &@as([120]u8, @splat('n')); try testing.expect(listen(testing.io, testing.allocator, p, long, "", null, null) == null); @@ -1572,7 +1599,7 @@ test "a listening editor posts itself into the 9P registry and unposts on stop" if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); gpa.free(v); - } else _ = unsetenv("XDG_RUNTIME_DIR"); + } else _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); } try testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", &directory, 1)); @@ -1633,7 +1660,7 @@ test "Unix TCP and QUIC share one listener through reads writes reconnects and r if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); gpa.free(v); - } else _ = unsetenv("XDG_RUNTIME_DIR"); + } else _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); } try testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", &directory, 1)); const replacement = try gpa.alloc(u8, 3 * msize + 27); @@ -1754,7 +1781,7 @@ test "a change waits while the editor is out mid-step, a read does not, and the if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); gpa.free(v); - } else _ = unsetenv("XDG_RUNTIME_DIR"); + } else _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); } try testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", &directory, 1)); @@ -1829,7 +1856,7 @@ test "a held read is answered when the log has news, and a flushed one spends no if (old_runtime) |v| { _ = setenv("XDG_RUNTIME_DIR", v, 1); gpa.free(v); - } else _ = unsetenv("XDG_RUNTIME_DIR"); + } else _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); } try testing.expectEqual(@as(c_int, 0), setenv("XDG_RUNTIME_DIR", &directory, 1)); @@ -2001,28 +2028,22 @@ pub fn exportSessionEnv(serial: u32, adopts: bool) void { exportEnv(if (own_socket_len > 0) own_socket[0..own_socket_len] else null, serial, adopts); } +/// Told to children through host_io.ChildEnv, never set into this process's +/// own environment (see ChildEnv.exportVar for why). fn exportEnv(socket: ?[]const u8, serial: u32, adopts: bool) void { - var announced = false; - if (adopts) announcing: { - var buf: [16]u8 = undefined; - const text = std.fmt.bufPrintSentinel(&buf, "{d}", .{@as(u32, @intCast(libc.getpid()))}, 0) catch - break :announcing; - announced = setenv("PARDES_PID", text, 1) == 0; - } - if (!announced) _ = unsetenv("PARDES_PID"); - - if (socket) |own| exporting: { - var sock: [sun_path_len]u8 = undefined; - const path = std.fmt.bufPrintSentinel(&sock, "{s}", .{own}, 0) catch break :exporting; + const ChildEnv = @import("host_io.zig").ChildEnv; + var pid_buf: [16]u8 = undefined; + ChildEnv.exportVar("PARDES_PID", if (adopts) std.fmt.bufPrint(&pid_buf, "{d}", .{@as(u32, @intCast(libc.getpid()))}) catch null else null); + if (socket) |own| { var buf: [16]u8 = undefined; - const id = std.fmt.bufPrintSentinel(&buf, "{d}", .{serial}, 0) catch break :exporting; - if (setenv("PARDES_9P", path, 1) != 0) break :exporting; + ChildEnv.exportVar("PARDES_9P", own); exportMount(own); - if (setenv("PARDES_PANE", id, 1) == 0) return; + ChildEnv.exportVar("PARDES_PANE", std.fmt.bufPrint(&buf, "{d}", .{serial}) catch unreachable); + return; } - _ = unsetenv("PARDES_9P"); - _ = unsetenv("PARDES_PANE"); - _ = unsetenv("PARDES_MOUNT"); + ChildEnv.exportVar("PARDES_9P", null); + ChildEnv.exportVar("PARDES_PANE", null); + ChildEnv.exportVar("PARDES_MOUNT", null); } /// $PARDES_MOUNT, the session's own directory, when the environment says @@ -2040,11 +2061,11 @@ fn exportMount(sock_path: []const u8) void { const suffix = ".sock"; if (mntgen and root.len > 0 and std.mem.startsWith(u8, base, sock_prefix) and std.mem.endsWith(u8, base, suffix) and base.len > sock_prefix.len + suffix.len) { var buf: [4096]u8 = undefined; - if (std.fmt.bufPrintSentinel(&buf, "{s}/pardes/{s}", .{ std.mem.trimEnd(u8, root, "/"), base[sock_prefix.len .. base.len - suffix.len] }, 0)) |mount| { - if (setenv("PARDES_MOUNT", mount, 1) == 0) return; + if (std.fmt.bufPrint(&buf, "{s}/pardes/{s}", .{ std.mem.trimEnd(u8, root, "/"), base[sock_prefix.len .. base.len - suffix.len] })) |mount| { + return @import("host_io.zig").ChildEnv.exportVar("PARDES_MOUNT", mount); } else |_| {} } - _ = unsetenv("PARDES_MOUNT"); + @import("host_io.zig").ChildEnv.exportVar("PARDES_MOUNT", null); } test "a pane's PARDES_MOUNT is the session's directory under 9ns --mntgen, and unset when not known" { @@ -2057,16 +2078,16 @@ test "a pane's PARDES_MOUNT is the session's directory under 9ns --mntgen, and u if (value) |old| { _ = setenv(name, old, 1); testing.allocator.free(old); - } else _ = unsetenv(name); + } else _ = @import("host_io.zig").testUnsetenv(name); }; _ = setenv("NINE_MOUNT", "/mnt/9p", 1); _ = setenv("NINE_MNTGEN", "1", 1); exportMount("/run/user/1000/pardes-9p-work.sock"); - try testing.expectEqualStrings("/mnt/9p/pardes/work", std.mem.span(libc.getenv("PARDES_MOUNT").?)); + try testing.expectEqualStrings("/mnt/9p/pardes/work", @import("host_io.zig").ChildEnv.exported("PARDES_MOUNT").?); // A mount of another server (9ns --unix): not this session's. - _ = unsetenv("NINE_MNTGEN"); + _ = @import("host_io.zig").testUnsetenv("NINE_MNTGEN"); exportMount("/run/user/1000/pardes-9p-work.sock"); - try testing.expect(libc.getenv("PARDES_MOUNT") == null); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_MOUNT") == null); } test "9P shell environment states being inside pardes apart from how to reach it" { @@ -2079,16 +2100,16 @@ test "9P shell environment states being inside pardes apart from how to reach it if (value) |old| { _ = setenv(name, old, 1); testing.allocator.free(old); - } else _ = unsetenv(name); + } else _ = @import("host_io.zig").testUnsetenv(name); }; var dir: [sun_path_len:0]u8 = undefined; _ = setenv("XDG_RUNTIME_DIR", "/run/user/1000", 1); try testing.expectEqualStrings("/run/user/1000", socketDir(&dir).?); - _ = unsetenv("XDG_RUNTIME_DIR"); + _ = @import("host_io.zig").testUnsetenv("XDG_RUNTIME_DIR"); _ = setenv("HOME", "/home/example", 1); try testing.expectEqualStrings("/home/example/.local/state/pardes", socketDir(&dir).?); - _ = unsetenv("HOME"); + _ = @import("host_io.zig").testUnsetenv("HOME"); try testing.expect(socketDir(&dir) == null); const listener = try testing.allocator.create(Listener); @@ -2104,25 +2125,25 @@ test "9P shell environment states being inside pardes apart from how to reach it // parent, so a pardes started in one of its shells runs a session of // its own instead of handing its argument over. exportPaneEnv(listener, 7, false); - try testing.expectEqualStrings(path, std.mem.span(libc.getenv("PARDES_9P").?)); - try testing.expectEqualStrings("7", std.mem.span(libc.getenv("PARDES_PANE").?)); - try testing.expect(libc.getenv("PARDES_PID") == null); + try testing.expectEqualStrings(path, @import("host_io.zig").ChildEnv.exported("PARDES_9P").?); + try testing.expectEqualStrings("7", @import("host_io.zig").ChildEnv.exported("PARDES_PANE").?); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PID") == null); exportPaneEnv(listener, 8, true); - try testing.expectEqualStrings("8", std.mem.span(libc.getenv("PARDES_PANE").?)); - try testing.expectEqualStrings(own_pid, std.mem.span(libc.getenv("PARDES_PID").?)); + try testing.expectEqualStrings("8", @import("host_io.zig").ChildEnv.exported("PARDES_PANE").?); + try testing.expectEqualStrings(own_pid, @import("host_io.zig").ChildEnv.exported("PARDES_PID").?); // A session whose listener never came up is still the session this shell // is inside: the pid stands on its own, and only the address is missing. exportPaneEnv(null, 0, true); - try testing.expect(libc.getenv("PARDES_9P") == null); - try testing.expect(libc.getenv("PARDES_PANE") == null); - try testing.expectEqualStrings(own_pid, std.mem.span(libc.getenv("PARDES_PID").?)); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_9P") == null); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PANE") == null); + try testing.expectEqualStrings(own_pid, @import("host_io.zig").ChildEnv.exported("PARDES_PID").?); exportPaneEnv(null, 0, false); - try testing.expect(libc.getenv("PARDES_9P") == null); - try testing.expect(libc.getenv("PARDES_PANE") == null); - try testing.expect(libc.getenv("PARDES_PID") == null); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_9P") == null); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PANE") == null); + try testing.expect(@import("host_io.zig").ChildEnv.exported("PARDES_PID") == null); } pub const Client = struct { diff --git a/src/File.zig b/src/File.zig index 59b04e3f..7e05ac9f 100644 --- a/src/File.zig +++ b/src/File.zig @@ -43,14 +43,14 @@ pub const Snapshot = struct { saved_len: ?usize = null, fn deinit(s: Snapshot, gpa: std.mem.Allocator) void { - gpa.free(s.content); + pardes.memory.freeUnfilled(gpa, s.content); } }; /// The pane's text, place and name now, for an undo or redo step. fn snapshotOf(gpa: std.mem.Allocator, pane: *const Pane, f: *const State) ?Snapshot { return .{ - .content = gpa.dupe(u8, f.content) catch return null, + .content = pardes.memory.dupeUnfilled(gpa, f.content) catch return null, .cur_row = pane.body.cur_row, .cur_col = pane.body.cur_col, .vsel = pane.body.vsel, @@ -105,6 +105,8 @@ pub const History = struct { undo_len: usize = 0, redo: [limits.undo_max]Snapshot = undefined, redo_len: usize = 0, + /// The text `undo` and `redo` hold, kept near limits.undo_bytes. + bytes: usize = 0, /// The names the file had, each with the rename generation it ended /// (Snapshot.gen), and the generation now. @@ -115,6 +117,7 @@ pub const History = struct { const history = try gpa.create(History); history.undo_len = 0; history.redo_len = 0; + history.bytes = 0; history.names = .empty; history.gen = 0; return history; @@ -165,6 +168,9 @@ pub const State = struct { /// edit drops them (setContentSpan); shifting them through the splice, /// as pane.zig's shiftOne moves dot, would keep them. pager_spans: []pardes.pager.Span = &.{}, + /// The rows and spans an edit dropped, with the text they were for: an + /// edit (an undo) back to that very text takes them again. + dropped_marks: ?DroppedMarks = null, /// Seconds of the last content change, for the filesystem's stat; zero until edited. mtime: u32 = 0, /// Non-null for a generated output buffer rather than an on-disk file. @@ -457,10 +463,6 @@ test "an invalid byte in a grapheme is one cell, and never reaches vaxis's width try std.testing.expectEqual(@as(usize, 4), fitEnd(text, 0, 10)); } -pub fn byteDisplayWidth(byte: u8) usize { - return if (byte == '\t') config.tab_now else 1; -} - pub fn displayWidth(text: []const u8) usize { var width: usize = 0; var at: usize = 0; @@ -787,18 +789,9 @@ pub fn lineIndex(gpa: std.mem.Allocator, f: *State) ![]const usize { pub const Span = struct { head: usize, tail: usize }; fn editedLineStarts(gpa: std.mem.Allocator, starts: []const usize, old: []const u8, new: []const u8, known: ?Span) ![]usize { - const n = @min(old.len, new.len); - var head: usize = 0; - var tail: usize = 0; - if (known) |span| { - head = span.head; - tail = span.tail; - } else { - while (head + 64 <= n and std.mem.eql(u8, old[head..][0..64], new[head..][0..64])) head += 64; - while (head < n and old[head] == new[head]) head += 1; - while (tail + 64 <= n - head and std.mem.eql(u8, old[old.len - tail - 64 ..][0..64], new[new.len - tail - 64 ..][0..64])) tail += 64; - while (tail < n - head and old[old.len - tail - 1] == new[new.len - tail - 1]) tail += 1; - } + const span = known orelse spanOf(old, new); + const head = span.head; + const tail = span.tail; // A start s follows the newline at s-1: kept while that newline is in // the common head, shifted while it is in the common tail. const kept = std.sort.upperBound(usize, starts, head, struct { @@ -1123,6 +1116,7 @@ pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { if (file.highlights.len > 0) p.tree_sitter_gpa.free(file.highlights); p.gpa.free(file.pager_spans); locations.freeRows(p.gpa, file.location_rows); + if (file.dropped_marks) |m| m.deinit(p.gpa); if (file.context_declarations.len > 0) p.tree_sitter_gpa.free(file.context_declarations); if (file.node_tree) |tree| syntax.freeTree(tree); for (file.node_history.items) |step| p.gpa.free(step.ranges); @@ -1140,6 +1134,18 @@ fn reportEdit(p: *Pardes, f: *State, new: []const u8) void { pardes.ctlfs.events.noteReplace(p, id, false, f.content, new); } +pub const DroppedMarks = struct { + len: usize, + hash: u64, + rows: []locations.Row, + spans: []pardes.pager.Span, + + fn deinit(m: DroppedMarks, gpa: std.mem.Allocator) void { + locations.freeRows(gpa, m.rows); + gpa.free(m.spans); + } +}; + pub fn setContent(p: *Pardes, f: *State, new: []u8) void { setContentSpan(p, f, new, null); } @@ -1160,10 +1166,16 @@ pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void { moved[i] = .{ .cursor = spliced(@min(at, f.content.len), f.content.len, new.len, span.?), .scroll = spliced(lineStart(p.gpa, tf, tf.scroll), f.content.len, new.len, span.?) }; } const old_starts = f.line_starts.ptr; - locations.freeRows(p.gpa, f.location_rows); - f.location_rows = &.{}; - p.gpa.free(f.pager_spans); - f.pager_spans = &.{}; + if (f.location_rows.len > 0 or f.pager_spans.len > 0) { + if (f.dropped_marks) |m| m.deinit(p.gpa); + f.dropped_marks = .{ .len = f.content.len, .hash = std.hash.Wyhash.hash(0, f.content), .rows = f.location_rows, .spans = f.pager_spans }; + f.location_rows = &.{}; + f.pager_spans = &.{}; + } else if (f.dropped_marks) |m| if (m.len == new.len and m.hash == std.hash.Wyhash.hash(0, new)) { + f.location_rows = m.rows; + f.pager_spans = m.spans; + f.dropped_marks = null; + }; for (p.panes) |slot| if (slot) |pane| { if (pane.file) |*file| if (file == f) { for (0..pane.sel.len) |button| { @@ -1182,7 +1194,9 @@ pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void { f.saved_hash = std.hash.Wyhash.hash(0, f.content); f.saved_len = f.content.len; } - p.gpa.free(f.content); + // Raw: `free` overwrites a safe build's freed memory, a whole file's + // worth per keystroke. + if (f.content.len > 0) p.gpa.rawFree(f.content, .of(u8), @returnAddress()); f.content = new; f.revision +%= 1; if (f.saved_hash) |h| if ((f.saved_len orelse new.len) == new.len and std.hash.Wyhash.hash(0, new) == h) { @@ -1241,14 +1255,43 @@ fn spliced(at: usize, old_len: usize, new_len: usize, span: Span) usize { } /// What `old` and `new` agree on at either end. -fn spanOf(old: []const u8, new: []const u8) Span { +/// What `new` kept of `old` at either end, compared 32 bytes at a time +/// (a byte at a time was most of a `d` in a 7 MB file). +pub fn spanOf(old: []const u8, new: []const u8) Span { + const block = 32; const n = @min(old.len, new.len); - const head = std.mem.indexOfDiff(u8, old[0..n], new[0..n]) orelse n; + var head: usize = 0; + while (head + block <= n and std.mem.eql(u8, old[head..][0..block], new[head..][0..block])) head += block; + while (head < n and old[head] == new[head]) head += 1; var tail: usize = 0; + while (tail + block <= n - head and std.mem.eql(u8, old[old.len - tail - block ..][0..block], new[new.len - tail - block ..][0..block])) tail += block; while (tail < n - head and old[old.len - 1 - tail] == new[new.len - 1 - tail]) tail += 1; return .{ .head = head, .tail = tail }; } +test "spanOf by blocks finds the byte loop's ends" { + var prng: std.Random.DefaultPrng = .init(5); + const random = prng.random(); + var a: [160]u8 = undefined; + var b: [160]u8 = undefined; + for (0..4000) |_| { + const la = random.uintLessThan(usize, a.len); + const lb = random.uintLessThan(usize, b.len); + for (a[0..la]) |*c| c.* = "ab"[random.uintLessThan(usize, 2)]; + const keep = @min(la, lb); + @memcpy(b[0..keep], a[0..keep]); + for (b[keep..lb]) |*c| c.* = "ab"[random.uintLessThan(usize, 2)]; + if (lb > 0 and random.boolean()) b[random.uintLessThan(usize, lb)] ^= 1; + const old = a[0..la]; + const new = b[0..lb]; + const n = @min(old.len, new.len); + const head = std.mem.indexOfDiff(u8, old[0..n], new[0..n]) orelse n; + var tail: usize = 0; + while (tail < n - head and old[old.len - 1 - tail] == new[new.len - 1 - tail]) tail += 1; + try std.testing.expectEqual(Span{ .head = head, .tail = tail }, spanOf(old, new)); + } +} + fn positionIn(gpa: std.mem.Allocator, f: *State, at: usize) struct { row: usize, col: usize } { const index = lineIndex(gpa, f) catch { const c = modal.positionAt(f.content, at); @@ -1492,14 +1535,18 @@ pub fn restoreSnap(pane: *Pane, f: *State, snap: Snapshot) void { pane.ensureCursorVisible(); } -fn pushHistory(gpa: std.mem.Allocator, slots: []Snapshot, len: *usize, snap: Snapshot) void { - if (len.* == slots.len) { +/// Bounded in steps and in bytes: the oldest go first, though the one +/// pushed always stays. +fn pushHistory(gpa: std.mem.Allocator, history: *History, slots: []Snapshot, len: *usize, snap: Snapshot) void { + while (len.* > 0 and (len.* == slots.len or history.bytes + snap.content.len > limits.undo_bytes)) { + history.bytes -= slots[0].content.len; slots[0].deinit(gpa); - std.mem.copyForwards(Snapshot, slots[0 .. slots.len - 1], slots[1..]); + std.mem.copyForwards(Snapshot, slots[0 .. len.* - 1], slots[1..len.*]); len.* -= 1; } slots[len.*] = snap; len.* += 1; + history.bytes += snap.content.len; } pub fn pushUndo(p: *Pardes, pane: *Pane) void { @@ -1510,9 +1557,12 @@ pub fn pushUndo(p: *Pardes, pane: *Pane) void { if (std.mem.eql(u8, last.content, f.content) and last.gen == history.gen) return; } const snap = snapshotOf(p.gpa, pane, f) orelse return; - pushHistory(p.gpa, &history.undo, &history.undo_len, snap); - for (history.redo[0..history.redo_len]) |item| item.deinit(p.gpa); + for (history.redo[0..history.redo_len]) |item| { + history.bytes -= item.content.len; + item.deinit(p.gpa); + } history.redo_len = 0; + pushHistory(p.gpa, history, &history.undo, &history.undo_len, snap); } pub fn undo(p: *Pardes, pane: *Pane) void { @@ -1520,9 +1570,10 @@ pub fn undo(p: *Pardes, pane: *Pane) void { const history = f.history; if (history.undo_len == 0) return; const current = snapshotOf(p.gpa, pane, f) orelse return; - pushHistory(p.gpa, &history.redo, &history.redo_len, current); + pushHistory(p.gpa, history, &history.redo, &history.redo_len, current); history.undo_len -= 1; const previous = history.undo[history.undo_len]; + history.bytes -= previous.content.len; // the file's text now setContent(p, f, previous.content); restoreName(p, pane, f, previous); restoreSnap(pane, f, previous); @@ -1533,9 +1584,10 @@ pub fn redo(p: *Pardes, pane: *Pane) void { const history = f.history; if (history.redo_len == 0) return; const current = snapshotOf(p.gpa, pane, f) orelse return; - pushHistory(p.gpa, &history.undo, &history.undo_len, current); + pushHistory(p.gpa, history, &history.undo, &history.undo_len, current); history.redo_len -= 1; const next = history.redo[history.redo_len]; + history.bytes -= next.content.len; // the file's text now setContent(p, f, next.content); restoreName(p, pane, f, next); restoreSnap(pane, f, next); @@ -2266,3 +2318,28 @@ pub fn paintWordSelection( } } } + +test "undo keeps its steps within a byte bound, the newest always" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = try p.setTestFile(""); + const f = &pane.file.?; + const step = limits.undo_bytes / 4 + 1; + const text = try gpa.alloc(u8, step); + defer gpa.free(text); + for (0..8) |i| { + @memset(text, 'a' + @as(u8, @intCast(i))); + pushUndo(p, pane); + setContent(p, f, try gpa.dupe(u8, text)); + } + pushUndo(p, pane); + const history = f.history; + try std.testing.expect(history.undo_len > 0 and history.undo_len < 8); + try std.testing.expect(history.bytes <= limits.undo_bytes + step); + var sum: usize = 0; + for (history.undo[0..history.undo_len]) |snap| sum += snap.content.len; + try std.testing.expectEqual(sum, history.bytes); + undo(p, pane); + try std.testing.expectEqualStrings(text[0..1], f.content[0..1]); +} diff --git a/src/Registers.zig b/src/Registers.zig index 3f2486cd..5e23da5b 100644 --- a/src/Registers.zig +++ b/src/Registers.zig @@ -81,6 +81,7 @@ pub fn text(r: *Registers, gpa: std.mem.Allocator, name: u21) ?[]const u8 { const reg = r.get(name) orelse return null; if (reg.joined) |j| return j; var out: std.ArrayList(u8) = .empty; + defer out.deinit(gpa); // what a failed append left; empty once owned for (reg.values, 0..) |v, i| { if (i > 0 and !std.mem.endsWith(u8, reg.values[i - 1], "\n")) out.append(gpa, '\n') catch return null; out.appendSlice(gpa, v) catch return null; @@ -105,3 +106,15 @@ test "a register holds a value per range and joins them for one-text readers" { try std.testing.expectEqualStrings("x", r.text(gpa, 'a').?); try std.testing.expectEqualStrings("one\ntwo", r.text(gpa, default).?); } + +test "joining a register that runs out of memory partway leaks nothing" { + var r: Registers = .{}; + defer r.deinit(std.testing.allocator); + r.put(std.testing.allocator, default, "one", 0, 2, true); + r.put(std.testing.allocator, default, "two", 1, 2, false); + r.put(std.testing.allocator, default, &(@as([4096]u8, @splat('x'))), 1, 2, false); + // The first append allocates; growing for the 4096 bytes fails. + var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 1, .resize_fail_index = 0 }); + try std.testing.expect(r.text(failing.allocator(), default) == null); + try std.testing.expectEqual(failing.allocated_bytes, failing.freed_bytes); +} diff --git a/src/ShaderBuild.zig b/src/ShaderBuild.zig index b50999a5..e5b6680b 100644 --- a/src/ShaderBuild.zig +++ b/src/ShaderBuild.zig @@ -76,7 +76,8 @@ const Result = union(enum) { spirv: struct { bytes: []u8, source: u64, animated: bool }, }; -/// One compile of the stale files, on its own thread. +/// One compile of the stale files, a task of its own: `deinit` cancels it +/// (glslc's wait is a cancelation point) rather than waiting out a glslc. const Job = struct { io: std.Io, gpa: std.mem.Allocator, @@ -86,7 +87,10 @@ const Job = struct { results: [max]Result = @splat(.none), len: usize = 0, done: std.atomic.Value(bool) = .init(false), - thread: std.Thread = undefined, + /// Set before the cancel: the files after the one it stopped are not + /// compiled either (a cancel is said once, to the wait it lands in). + stop: std.atomic.Value(bool) = .init(false), + future: std.Io.Future(void) = undefined, }; files: [max]File = @splat(.{}), @@ -105,7 +109,7 @@ pub fn sync(b: *Build, gpa: std.mem.Allocator, io: std.Io, core: *pardes.Pardes, var collected = false; if (b.job) |job| { if (!job.done.load(.acquire)) return false; - job.thread.join(); + job.future.await(job.io); b.job = null; b.collect(gpa, core, job); collected = true; @@ -148,7 +152,7 @@ pub fn sync(b: *Build, gpa: std.mem.Allocator, io: std.Io, core: *pardes.Pardes, job.len += 1; file.stale = false; } - job.thread = std.Thread.spawn(.{}, compile, .{job}) catch { + job.future = io.concurrent(compile, .{job}) catch { for (job.paths[0..job.len]) |path| gpa.free(path); gpa.destroy(job); return collected; @@ -174,7 +178,8 @@ pub fn view(b: *const Build, chain: *const Chain, out: *[max]Pass) []const Pass pub fn deinit(b: *Build, gpa: std.mem.Allocator, fd: c_int, watches: *file_watch.Table) void { if (b.job) |job| { - job.thread.join(); + job.stop.store(true, .release); + job.future.cancel(job.io); freeJob(gpa, job); } for (b.files[0..b.len]) |file| free(gpa, file); @@ -245,7 +250,10 @@ fn expand(buf: *[4096]u8, path: []const u8) []const u8 { /// build's own flags (build.zig compileGlsl), source on stdin, SPIR-V on /// stdout. fn compile(job: *Job) void { - for (job.paths[0..job.len], 0..) |path, i| job.results[i] = compileOne(job.gpa, job.io, path, job.known[i]); + for (job.paths[0..job.len], 0..) |path, i| { + if (job.stop.load(.acquire)) break; + job.results[i] = compileOne(job.gpa, job.io, path, job.known[i]); + } job.done.store(true, .release); if (job.wake.call) |call| call(job.wake.ctx); } @@ -378,7 +386,8 @@ test "a save that changes a file compiles it again, a failed one keeps the last fn run(build: *Build, c: *pardes.Pardes, f: c_int, w: *file_watch.Table) void { _ = build.sync(std.testing.allocator, std.testing.io, c, f, w, .{}); while (build.job) |job| { - while (!job.done.load(.acquire)) std.Thread.yield() catch {}; + job.future.await(std.testing.io); + job.done.store(true, .release); _ = build.sync(std.testing.allocator, std.testing.io, c, f, w, .{}); } } diff --git a/src/builtins.zig b/src/builtins.zig index cc7d1d4a..fdce534b 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1971,6 +1971,9 @@ pub const WsDiagnostics = struct { /// Show outermost callers first, with signatures and call sites (gc). pub const Callstack = struct { pub fn run(c: Ctx) void { + // In +Callstack itself: the next page of what it shows. + if (c.pane.file) |f| if (f.output) |o| if (std.meta.eql(o.from, panes.Output.Origin{ .query = .callstack })) + return c.p.callstackMore(c.id); c.p.lspRequest(c.id, .callstack, ""); } }; diff --git a/src/colors.zig b/src/colors.zig index dd0d8938..28136975 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -840,7 +840,7 @@ pub fn loadThemeFile(p: *Pardes, generation: u32, bytes: []const u8, animate: bo @memcpy(settled[0..request.path.len], request.path); _ = p.theme_file_loaded.set(settled[0..request.path.len]); invalidateThemeDependentRasters(p); - _ = p.scratch.reset(.retain_capacity); + _ = p.scratch.reset(.{ .retain_with_limit = pardes.memory.limits.scratch_kept }); p.sync(); return true; } diff --git a/src/config.zig b/src/config.zig index a92aabb6..5251b1e5 100644 --- a/src/config.zig +++ b/src/config.zig @@ -1230,27 +1230,12 @@ pub const Runtime = struct { if (!state.shell.requested.set(value)) return false; state.shell.pending = true; }, - .tagline_size => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); - const percent = std.fmt.parseInt(u16, text, 10) catch return false; - if (percent < tagline_percent_min or percent > tagline_percent_max) return false; - state.font.tagline_percent = @intCast(percent); - }, + .tagline_size => state.font.tagline_percent = @intCast(number(u16, argument, " \t\r\n", tagline_percent_min, tagline_percent_max) orelse return false), .window_opacity => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); - for (text) |byte| if (!std.ascii.isDigit(byte)) return false; - const percent = std.fmt.parseInt(u8, text, 10) catch return false; - if (percent > 100) return false; - state.window_opacity = percent; + state.window_opacity = number(u8, argument, " \t\r\n", 0, 100) orelse return false; state.window_opacity_pending = true; }, - .window_blur => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); - for (text) |byte| if (!std.ascii.isDigit(byte)) return false; - const percent = std.fmt.parseInt(u8, text, 10) catch return false; - if (percent > 100) return false; - state.window_blur = percent; - }, + .window_blur => state.window_blur = number(u8, argument, " \t\r\n", 0, 100) orelse return false, // Bare, it returns to the default directory. Else an absolute or // `~` path, to a directory there or to be made, that may be // written: a Dump there could never be, refused now. @@ -1264,10 +1249,7 @@ pub const Runtime = struct { if (!state.dump_dir.set(text)) return false; }, .message_ms => |which| { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); - for (text) |byte| if (!std.ascii.isDigit(byte)) return false; - const ms = std.fmt.parseInt(u16, text, 10) catch return false; - if (ms > message_ms_max) return false; + const ms = number(u16, argument, " \t\r\n", 0, message_ms_max) orelse return false; switch (which) { inline else => |w| @field(state, "message_" ++ @tagName(w) ++ "_ms") = ms, } @@ -1330,30 +1312,10 @@ pub const Runtime = struct { std.meta.stringToEnum(LiftStyle, text) orelse return false; }, .motion => state.motion = stepped(animation.Motion.Flavour, state.motion, argument) orelse return false, - .inactive_dim => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n%"); - const percent = std.fmt.parseInt(u8, text, 10) catch return false; - if (percent > 100) return false; - state.inactive_dim = percent; - }, - .grip_width => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n%"); - const percent = std.fmt.parseInt(u16, text, 10) catch return false; - if (percent < 50 or percent > 300) return false; - state.grip_width = percent; - }, - .callstack_depth => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); - const depth = std.fmt.parseInt(u8, text, 10) catch return false; - if (depth < 1 or depth > @import("lsp/lsp.zig").callstack_max_depth) return false; - state.callstack_depth = depth; - }, - .tab => { - const text = std.mem.trim(u8, argument orelse return false, " \t\r\n"); - const width = std.fmt.parseInt(u16, text, 10) catch return false; - if (width < 1 or width > 16) return false; - state.tab = width; - }, + .inactive_dim => state.inactive_dim = number(u8, argument, " \t\r\n%", 0, 100) orelse return false, + .grip_width => state.grip_width = number(u16, argument, " \t\r\n%", 50, 300) orelse return false, + .callstack_depth => state.callstack_depth = number(u8, argument, " \t\r\n", 1, @import("lsp/lsp.zig").callstack_max_depth) orelse return false, + .tab => state.tab = number(u16, argument, " \t\r\n", 1, 16) orelse return false, .theme, .font => return false, } return true; @@ -1411,6 +1373,16 @@ pub const Runtime = struct { return all[(at + 1) % all.len]; } + /// A setting's number: digits only (parseInt alone takes a sign and `_`), + /// trimmed of `trim`, within lo..hi. + fn number(comptime T: type, argument: ?[]const u8, trim: []const u8, lo: T, hi: T) ?T { + const text = std.mem.trim(u8, argument orelse return null, trim); + if (text.len == 0) return null; + for (text) |byte| if (!std.ascii.isDigit(byte)) return null; + const n = std.fmt.parseInt(T, text, 10) catch return null; + return if (n < lo or n > hi) null else n; + } + /// What `on`, `off` or nothing after a switch word asks for: null flips /// it, as a bare tagline word does. fn switchedTo(argument: ?[]const u8) error{NotOnOrOff}!?bool { @@ -2523,7 +2495,7 @@ test "CallstackDepth is bounded and keeps the last valid runtime limit" { try std.testing.expect(Runtime.apply(&state, Runtime.find("CallstackDepth").?, value)); try std.testing.expectEqual(try std.fmt.parseInt(u8, value, 10), state.callstack_depth); } - for ([_][]const u8{ "0", "65", "256", "-1", "eight", "" }) |value| { + for ([_][]const u8{ "0", "65", "256", "-1", "+8", "1_6", "eight", "" }) |value| { try std.testing.expect(!Runtime.apply(&state, Runtime.find("CallstackDepth").?, value)); try std.testing.expectEqual(@as(u8, 64), state.callstack_depth); } diff --git a/src/crash.zig b/src/crash.zig index 34dc1b3d..a432fb87 100644 --- a/src/crash.zig +++ b/src/crash.zig @@ -34,6 +34,9 @@ pub const name = "crashes"; /// A panic handler is the one caller that cannot check whether its input is /// still alive, so it does not borrow. var dir_buf: [1024]u8 = undefined; + +/// The crash file's bound (see `record`). +const max_log_bytes = 256 * 1024; var dir_len: usize = 0; /// Called where the launcher sets `Options.config_dir`. Ignores a path too long @@ -109,6 +112,9 @@ pub fn record(msg: []const u8) void { }, @as(std.c.mode_t, 0o600)); if (fd < 0) return; defer _ = std.c.close(fd); + // Bounded: a file past `max_log_bytes` starts over, so it keeps the + // newest records rather than every crash since it was first made. + if (std.c.lseek(fd, 0, std.c.SEEK.END) > max_log_bytes) _ = std.c.ftruncate(fd, 0); var w: std.Io.Writer = .fixed(&scratch); diff --git a/src/detached/server.zig b/src/detached/server.zig index d6a1f553..6c8d4352 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -107,17 +107,19 @@ const Mailbox = struct { status: ?[]u8 = null, }; - mutex: std.atomic.Mutex = .unlocked, + /// Taken by the workers and the loop; `io` is the session's (initAsync). + mutex: std.Io.Mutex = .init, + io: std.Io = undefined, batch: Batch = .{}, wake: [2]c_int = .{ -1, -1 }, fn post(box: *Mailbox, completion: Completion) void { - while (!box.mutex.tryLock()) std.atomic.spinLoopHint(); + box.mutex.lockUncancelable(box.io); // Tasks retain their slot until the owner consumes their one completion. std.debug.assert(box.batch.len < capacity); box.batch.items[box.batch.len] = completion; box.batch.len += 1; - box.mutex.unlock(); + box.mutex.unlock(box.io); box.signal(); } @@ -130,8 +132,8 @@ const Mailbox = struct { fn take(box: *Mailbox) Batch { var bytes: [128]u8 = undefined; while (libc.recv(box.wake[0], &bytes, bytes.len, 0) > 0) {} - while (!box.mutex.tryLock()) std.atomic.spinLoopHint(); - defer box.mutex.unlock(); + box.mutex.lockUncancelable(box.io); + defer box.mutex.unlock(box.io); const batch = box.batch; box.batch.len = 0; box.batch.status = null; @@ -184,6 +186,7 @@ pub const Session = struct { accept_paused_ms: i64 = 0, pub fn initAsync(s: *Session) !void { + s.mailbox.io = s.io; var pair: [2]c_int = undefined; if (libc.socketpair(libc.AF.UNIX, libc.SOCK.STREAM, 0, &pair) != 0) return error.SocketFailed; errdefer for (pair) |fd| { @@ -410,7 +413,7 @@ pub const Session = struct { s.core.update(.{ .lsp_resp = .{ .id = request.id, .rows = null } }); return s.core.reportError(request.pane, "lsp", err); }; - const future = s.io.concurrent(lspWorker, .{ s.worker_gpa, job, &s.mailbox }) catch |err| { + const future = s.io.concurrent(lspWorker, .{ s.io, s.worker_gpa, job, &s.mailbox }) catch |err| { job.free(s.worker_gpa); s.core.update(.{ .lsp_resp = .{ .id = request.id, .rows = null } }); return s.core.reportError(request.pane, "lsp", err); @@ -418,8 +421,8 @@ pub const Session = struct { s.lsp_task = .{ .id = request.id, .future = future }; } - fn lspWorker(gpa: std.mem.Allocator, job: *host_io.Lsp.Job, box: *Mailbox) anyerror!void { - host_io.Lsp.work(gpa, job, box, deliverLspRows); + fn lspWorker(io: std.Io, gpa: std.mem.Allocator, job: *host_io.Lsp.Job, box: *Mailbox) anyerror!void { + host_io.Lsp.work(io, gpa, job, box, deliverLspRows); } fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { @@ -430,10 +433,10 @@ pub const Session = struct { fn lspStatus(ctx: ?*anyopaque, text: []const u8) void { const s = of(ctx); const copy = s.worker_gpa.dupe(u8, text) catch return; - while (!s.mailbox.mutex.tryLock()) std.atomic.spinLoopHint(); + s.mailbox.mutex.lockUncancelable(s.io); if (s.mailbox.batch.status) |old| s.worker_gpa.free(old); s.mailbox.batch.status = copy; - s.mailbox.mutex.unlock(); + s.mailbox.mutex.unlock(s.io); s.mailbox.signal(); } @@ -529,7 +532,8 @@ pub const Session = struct { if (pane >= s.ptys.len) return; const pt = &s.ptys[pane]; if (pt.fd < 0) return; - if (pt.out.items.len > pty_backlog) { + // The bound holds with this write in: queued and new together. + if (pt.out.items.len + bytes.len > pty_backlog) { var mbuf: [256]u8 = undefined; const text = std.fmt.bufPrint( &mbuf, @@ -1145,6 +1149,9 @@ pub const Session = struct { s.queue(c, bytes); } + /// A client's queued output is at most `out_backlog + wire.max_payload`: + /// past the backlog it is closed, and one frame lands on top of it first + /// (a frame bigger than the backlog must still go out whole). fn queue(s: *Session, c: *Client, bytes: []const u8) void { if (c.out.items.len > out_backlog) return s.close(c, .backlog); s.account(); diff --git a/src/dump.zig b/src/dump.zig index 76a6de85..67934e0a 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -394,17 +394,6 @@ test "oversized recognized output argument is rejected before restore" { ); } -pub fn writeFile(io: std.Io, gpa: std.mem.Allocator, path: []const u8, state: State) !void { - try validate(state); - var out: std.Io.Writer.Allocating = .init(gpa); - defer out.deinit(); - try std.zon.stringify.serialize(state, .{ .whitespace = true }, &out.writer); - - var file = try std.Io.Dir.createFileAbsolute(io, path, .{}); - defer file.close(io); - try file.writeStreamingAll(io, out.written()); -} - pub const Parsed = struct { value: State, arena: std.heap.ArenaAllocator, diff --git a/src/edit.zig b/src/edit.zig index 466b5cdb..55365692 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -119,7 +119,15 @@ pub fn typeToTty(p: *Pardes, id: usize, pane: *const Pane, text: []const u8) voi for (panes.terminal.encodePaste(pane, cp)) |part| if (part.len > 0) p.emitWrite(id, part); } -pub fn applyPaste(p: *Pardes, bytes: []const u8) void { +pub fn applyPaste(p: *Pardes, whole: []const u8) void { + // Every shell's paste comes through here, bounded: what is past the + // limit is left out, at a character's start, and said. + const limit = @import("memory.zig").limits.max_paste_bytes; + const bytes = if (whole.len > limit) whole[0..modal.graphemeStart(whole, limit)] else whole; + if (whole.len > limit) { + var said: [96]u8 = undefined; + p.setMessage(p.active, std.fmt.bufPrint(&said, "paste cut at its limit, {d} KiB: the rest left out", .{limit / 1024}) catch "paste cut at its limit"); + } // A prompt answering for a header takes the paste, as it takes keys. const asking = if (p.panes[p.active]) |active| active.prompt != .none else false; if (!asking) if (tagline.focusedHeader(p)) |t| { @@ -466,8 +474,10 @@ fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) ?panes.EditText { fn editTextEol(p: *Pardes, t: *Text, b: Bounds) ?panes.EditText { const eb = editText(p, t, b.lo_row, b.hi_row, -1) orelse return null; const r: usize = @intCast(@max(0, b.hi_row - eb.row0)); - if (r + 1 < modal.lineCount(eb.text)) return eb; - if (b.hi_col < @as(i32, @intCast(modal.lineSlice(eb.text, r).len))) return eb; + // A file's own line count and line, from its index. + const lines = if (indexedLine(p, t, eb.text, 0) != null) panes.File.nlines(p.gpa, &t.pane().?.file.?) else modal.lineCount(eb.text); + if (r + 1 < lines) return eb; + if (b.hi_col < @as(i32, @intCast(lineAt(p, t, eb.text, r).line.len))) return eb; return editText(p, t, b.lo_row, b.hi_row + 1, -1); } @@ -476,6 +486,47 @@ pub fn setEditText(p: *Pardes, t: *Text, new: []u8) void { setEditTextEnd(p, t, new, null); } +const LineAt = struct { start: usize, line: []const u8 }; + +/// `text`'s line count: the file's index when `text` is the pane's file. +fn lineCountOf(p: *Pardes, t: *Text, text: []const u8) usize { + if (indexedLine(p, t, text, 0) != null) return panes.File.nlines(p.gpa, &t.pane().?.file.?); + return modal.cursorLineCount(text); +} + +/// The row offset `off` is on: a search of the file's index when `text` is +/// the pane's file, else the newlines before it counted (modal.lineAtOffset). +fn rowOf(p: *Pardes, t: *Text, text: []const u8, off: usize) usize { + if (indexedLine(p, t, text, 0) != null) { + const index = panes.File.lineIndex(p.gpa, &t.pane().?.file.?) catch return modal.lineAtOffset(text, off); + return std.sort.upperBound(usize, index, @min(off, text.len), struct { + fn order(key: usize, item: usize) std.math.Order { + return std.math.order(key, item); + } + }.order) -| 1; + } + return modal.lineAtOffset(text, off); +} + +/// Line `row` of `text` and where it starts: through the file's line index +/// when `text` is the pane's file (a lookup), else counted from the top. +/// Finding line 94000 by counting was most of a keystroke in a 7 MB file. +fn lineAt(p: *Pardes, t: *Text, text: []const u8, row: usize) LineAt { + return indexedLine(p, t, text, row) orelse .{ .start = modal.lineStartOffset(text, row), .line = modal.lineSlice(text, row) }; +} + +/// lineAt's lookup, null when `text` is not the pane's file or `row` is past its last line. +fn indexedLine(p: *Pardes, t: *Text, text: []const u8, row: usize) ?LineAt { + if (t.what != .body) return null; + const pane = t.pane() orelse return null; + const f = if (pane.file) |*f| f else return null; + if (f.content.ptr != text.ptr or f.content.len != text.len) return null; + if (row >= panes.File.nlines(p.gpa, f)) return null; + const start = @min(panes.File.lineStart(p.gpa, f, row), text.len); + const end = std.mem.indexOfScalarPos(u8, text, start, '\n') orelse text.len; + return .{ .start = start, .line = text[start..end] }; +} + /// Where text `s` put in at `c` ends: `g.`'s place after typing it. fn insertedEnd(c: modal.Cursor, s: []const u8) modal.Cursor { const nl = std.mem.lastIndexOfScalar(u8, s, '\n') orelse return .{ .row = c.row, .col = c.col + s.len }; @@ -486,6 +537,13 @@ fn insertedEnd(c: modal.Cursor, s: []const u8) modal.Cursor { /// rows) when the caller knows it, as typing does: then nothing scans the /// whole text to find it. Null, it is found by comparing the texts. pub fn setEditTextEnd(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor) void { + setEditTextSpan(p, t, new, known_end, null); +} + +/// `setEditTextEnd` with what a file's splice left alone at either end, when +/// the caller knows it (typing): the line index is then not found again by +/// comparing the whole old and new texts, which a keystroke in a 7 MB file did. +fn setEditTextSpan(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor, span: ?panes.File.Span) void { if (t.what == .tag) { // A tag is edited as it is shown, but only what follows its // prefix is its own: an edit that changed the prefix is refused. @@ -511,16 +569,13 @@ pub fn setEditTextEnd(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor) const pane = t.pane() orelse return retireEditText(p, new); // what changed ended where the texts agree again from their ends const old: []const u8, const row0: i32 = if (pane.file) |f| .{ f.content, 0 } else if (pane.ovl) |o| .{ o.text, o.row } else .{ "", 0 }; - const end = known_end orelse found: { - // ponytail: O(file), for the edits that do not say where they ended - // (paste, a pipe, s): typing passes its end and never comes here. - const front = std.mem.indexOfDiff(u8, old, new) orelse @min(old.len, new.len); - var back: usize = 0; - while (back < @min(old.len, new.len) - front and old[old.len - 1 - back] == new[new.len - 1 - back]) back += 1; - break :found modal.positionAt(new, new.len - back); - }; + // ponytail: O(file), for the edits that do not say what they changed + // (paste, a pipe, d, s): compared once, block by block, here; the same + // span then spares the line index a second comparison. + const found = span orelse if (known_end == null or pane.file != null) panes.File.spanOf(old, new) else null; + const end = known_end orelse modal.positionAt(new, new.len - found.?.tail); t.last_edit = .{ .row = @as(i32, @intCast(end.row)) + row0, .col = @intCast(end.col) }; - if (pane.file) |*f| return panes.File.setContent(p, f, new); + if (pane.file) |*f| return panes.File.setContentSpan(p, f, new, found); panes.terminal.setEditText(p, pane, new); } @@ -815,8 +870,10 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) void { const text = eb.text; const c = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - eb.row0)), .col = @intCast(@max(0, t.cur_col)) }; if (key.text.len > 0 and !key.ctrl and !key.alt) { - const new = modal.insertAt(p.gpa, text, c, key.text) catch return; - setEditTextEnd(p, t, new, insertedEnd(c, key.text)); + // insertAt's offset (col clamped to the line), the line found once. + const at = if (indexedLine(p, t, text, c.row)) |l| l.start + @min(c.col, l.line.len) else modal.insertOffset(text, c); + const new = modal.spliceAlloc(p.gpa, text, at, at, key.text) catch return; + setEditTextSpan(p, t, new, insertedEnd(c, key.text), .{ .head = at, .tail = text.len - at }); for (key.text) |ch| { if (ch == '\n') { t.cur_row += 1; @@ -918,7 +975,8 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) void { }, Key.backspace => { if (t.cur_col > 0) { - const line = modal.lineSlice(text, c.row); + const found = lineAt(p, t, text, c.row); + const line = found.line; var prev = modal.prevGrapheme(line, c.col); // in leading blanks, back to the previous indent stop (helix // dedent): a whole unit when on one, else the part past it @@ -931,8 +989,12 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) void { prev = c.col; while (drop > 0 and prev > 0 and line[prev - 1] == ' ') : (drop -= 1) prev -= 1; } - const new = modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = prev }, c) catch return; - setEditTextEnd(p, t, new, .{ .row = c.row, .col = prev }); + // deleteSpan's splice, the line found once. + const s = found.start + @min(prev, line.len); + const e = found.start + @min(c.col, line.len); + const new = if (e > s) modal.spliceAlloc(p.gpa, text, s, e, "") catch return else p.gpa.dupe(u8, text) catch return; + const span: panes.File.Span = if (e > s) .{ .head = s, .tail = text.len - e } else .{ .head = text.len, .tail = 0 }; + setEditTextSpan(p, t, new, .{ .row = c.row, .col = prev }, span); t.cur_col = @intCast(prev); t.cur_pinned = true; t.show(); @@ -1479,26 +1541,33 @@ pub fn normalJoin(p: *Pardes, t: *Text, select_space: bool) void { const text = eb.text; var rs: [Text.max_selections]modal.Selection = undefined; const got = t.ranges(text, eb.row0, &rs); - const nlines = modal.cursorLineCount(text); + // Lines, their count and rows from the file's index when it has one: + // counted from the top, a J in a 7 MB file was 8 ms. + const nlines = lineCountOf(p, t, text); const arena = p.scratch.allocator(); - const chs = arena.alloc(TextChange, nlines) catch return; - var chs_len: usize = 0; + var changes: std.ArrayList(TextChange) = .empty; var next: usize = 0; // lines below this one are joined already for (rs[0..got.n]) |r| { - const span = Text.rangeLineSpan(text, r); + // Text.rangeLineSpan, through rowOf + const lo = @min(r.anchor, r.head); + const hi = @max(r.anchor, r.head); + const span = .{ .start = rowOf(p, t, text, lo), .end = rowOf(p, t, text, if (lo == hi) hi else @max(modal.prevGrapheme(text, hi), lo)) }; var end = span.end; if (span.start == end) end = @min(end + 1, nlines - 1); var l = @max(span.start, next); while (l < end) : (l += 1) { - const from = modal.lineEndOffset(text, l); - var to = if (l + 1 >= nlines) text.len else modal.lineStartOffset(text, l + 1); + const here = lineAt(p, t, text, l); + const from = here.start + here.line.len; + var to = if (l + 1 >= nlines) text.len else lineAt(p, t, text, l + 1).start; while (to < text.len and (text[to] == ' ' or text[to] == '\t')) to += 1; - const sep: []const u8 = if (to == modal.lineEndOffset(text, @min(l + 1, nlines - 1))) "" else " "; - chs[chs_len] = .{ .from = from, .to = to, .ins = sep }; - chs_len += 1; + const last = lineAt(p, t, text, @min(l + 1, nlines - 1)); + const sep: []const u8 = if (to == last.start + last.line.len) "" else " "; + changes.append(arena, .{ .from = from, .to = to, .ins = sep }) catch return; } next = @max(next, end); } + const chs = changes.items; + const chs_len = chs.len; if (chs_len == 0) return; pushUndo(p, t); const new = applyChanges(p, text, chs[0..chs_len]) catch return; @@ -2459,3 +2528,72 @@ test "a paste into a terminal is xterm's: bracketed when the program asked, cont p.update(.{ .paste = "x\x1b[201~y\n" }); try std.testing.expectEqualStrings("\x1b[200~x [201~y\n\x1b[201~", try take(p, &out)); } + +test "a paste past the limit is cut at it, and says so" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = try p.setTestFile(""); + pane.body.mode = .insert; + const limit = @import("memory.zig").limits.max_paste_bytes; + const big = try gpa.alloc(u8, limit + 100); + defer gpa.free(big); + @memset(big, 'x'); + applyPaste(p, big); + try std.testing.expect(pane.file.?.content.len <= limit); + try std.testing.expect(pane.file.?.content.len > 0); + try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "paste cut") != null); +} + +test "typing and backspace through the line index keep the text and the index as a rebuild has them" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile("one\n two\n\nthree four\n"); + pane.body.mode = .insert; + var prng: std.Random.DefaultPrng = .init(11); + const random = prng.random(); + for (0..300) |_| { + _ = panes.File.lineIndex(gpa, &pane.file.?) catch unreachable; + const f = &pane.file.?; + const row = random.uintLessThan(usize, panes.File.nlines(gpa, f)); + const line = modal.lineSlice(f.content, row); + pane.body.cur_row = @intCast(row); + pane.body.cur_col = @intCast(random.uintLessThan(usize, line.len + 1)); + pane.body.cur_pinned = true; + if (random.boolean()) { + insertKey(p, &pane.body, .{ .cp = 'x', .text = "x" }); + } else { + insertKey(p, &pane.body, .{ .cp = Key.backspace }); + } + // the index the edits kept, against one built from the text + const kept = try gpa.dupe(usize, try panes.File.lineIndex(gpa, &pane.file.?)); + defer gpa.free(kept); + gpa.free(pane.file.?.line_starts); + pane.file.?.line_starts = &.{}; + try std.testing.expectEqualSlices(usize, try panes.File.lineIndex(gpa, &pane.file.?), kept); + } +} + +test "J joins a line with the next, its indent dropped, a space between unless the next is empty" { + const gpa = std.testing.allocator; + const cases = [_]struct { text: []const u8, row: i32, rows: i32 = 0, want: []const u8 }{ + .{ .text = "a\n b\nc\n", .row = 0, .want = "a b\nc\n" }, + .{ .text = "a\n\nc\n", .row = 0, .want = "a\nc\n" }, + .{ .text = "a\nb", .row = 1, .want = "a\nb" }, + .{ .text = "one\n\ttwo\nthree\nfour\n", .row = 0, .rows = 2, .want = "one two three\nfour\n" }, + }; + for (cases) |case| { + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile(case.text); + pane.body.mode = .normal; + pane.body.cur_row = case.row; + pane.body.cur_col = 0; + if (case.rows > 0) pane.body.vsel = .{ .active = true, .row = case.row + case.rows, .col = 0, .explicit = true }; + normalJoin(p, &pane.body, false); + try std.testing.expectEqualStrings(case.want, pane.file.?.content); + } +} diff --git a/src/exec.zig b/src/exec.zig index d03a4a48..c9f304b0 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -913,6 +913,12 @@ pub fn commandDone(p: *Pardes, id: usize, status: ?u8) void { pane.repl = null; pane.command_status = status; pane.body.mode = .normal; + // Look's `git show`: its output went to a +Pager, the +Diff now; only a + // failure is worth the pane. + if (pane.command_pages) { + pane.command_pages = false; + if (status == 0) return p.removePane(id, null) catch {}; + } var buf: [16]u8 = undefined; const code = if (status) |n| std.fmt.bufPrint(&buf, "{d}", .{n}) catch "?" else "?"; var said: [32]u8 = undefined; diff --git a/src/fs.zig b/src/fs.zig index 061d4225..032ab9c0 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1087,17 +1087,17 @@ pub const platform_has_fs = !pardes.isolated and switch (pardes.platform) { const find_max_hits = 512; /// What a Find or Grep walk passed over, said under its hits: directories -/// it might not open, files read only in part, and caps it stopped at. +/// it might not open, and caps it stopped at. pub const WalkNotes = struct { skipped: usize = 0, - /// Files longer than grep_max_bytes, searched in their first part only. - partial: usize = 0, hits_cut: bool = false, + /// A pane search's matching lines it stopped at, its rows filling + /// look.search_text_output_bytes; 0 if none. + rows_cut: usize = 0, /// The cap on entries walked it stopped at, 0 if none. walk_cut: usize = 0, pub const max_hits = find_max_hits; - pub const max_file_bytes = grep_max_bytes; pub const max_files = grep_max_files; pub const max_depth = find_max_depth; @@ -1105,7 +1105,7 @@ pub const WalkNotes = struct { pub fn write(n: WalkNotes, out: []u8) usize { var w = std.Io.Writer.fixed(out); if (n.hits_cut) w.print("cut at {d} hits\n", .{max_hits}) catch {}; - if (n.partial > 0) w.print("{d} file{s} read only in part (first {d} KiB)\n", .{ n.partial, if (n.partial == 1) "" else "s", max_file_bytes / 1024 }) catch {}; + if (n.rows_cut > 0) w.print("cut at {d} lines\n", .{n.rows_cut}) catch {}; if (n.walk_cut > 0) w.print("walk cut at {d} entries\n", .{n.walk_cut}) catch {}; if (n.skipped > 0) w.print("{d} director{s} skipped: permission denied\n", .{ n.skipped, if (n.skipped == 1) "y" else "ies" }) catch {}; return w.buffered().len; @@ -1124,7 +1124,8 @@ pub const WalkNotes = struct { }; const find_max_depth = 16; const find_max_steps = 100_000; -pub const search_max_output_bytes = pardes.MAX_PANES * find_max_hits * (4096 + 320); +/// One root's Find or Grep rows at most: its hits, each a path and a line. +pub const search_root_output_bytes = find_max_hits * (4096 + 320); const find_skip = [_][]const u8{ ".git", ".jj", "target", "node_modules", @@ -1194,9 +1195,10 @@ const grep_max_files = 20_000; const GrepResult = struct { bytes: usize, hits: usize }; -fn grepText(path: []const u8, text: []const u8, pat: []const u8, out: []u8, budget: usize) GrepResult { +/// `text` starts at line `first_line` + 1 of its file. +fn grepText(path: []const u8, text: []const u8, pat: []const u8, out: []u8, budget: usize, first_line: usize) GrepResult { var result: GrepResult = .{ .bytes = 0, .hits = 0 }; - var line: usize = 0; + var line: usize = first_line; var it = std.mem.splitScalar(u8, text, '\n'); while (it.next()) |raw| { line += 1; @@ -1220,7 +1222,7 @@ pub fn grep(arena: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8, b if (!platform_has_fs) { for (sources) |s| { if (hits >= find_max_hits or written == out.len) break; - const result = grepText(s.path, s.contents, pat, out[written..], find_max_hits - hits); + const result = grepText(s.path, s.contents, pat, out[written..], find_max_hits - hits, 0); hits += result.hits; written += result.bytes; } @@ -1276,30 +1278,39 @@ pub fn grep(arena: std.mem.Allocator, gpa: std.mem.Allocator, dir: []const u8, b const path_z = std.fmt.bufPrintSentinel(&pathbuf, "{s}", .{path}, 0) catch return error.PathTooLong; const fd = libc.open(path_z, .{ .ACCMODE = .RDONLY, .CLOEXEC = true, .NONBLOCK = true }); if (fd < 0) continue; + defer _ = libc.close(fd); + // The whole file, a buffer at a time: each searched through its last + // whole line, the rest carried into the next. + const shown = lsp.rel(home, path); var len: usize = 0; - var readable = true; - while (len < buf.len) { - const n = libc.read(fd, buf[len..].ptr, buf.len - len); - if (n < 0) { - if (libc.errno(n) == .INTR) continue; - readable = false; - break; + var lines_before: usize = 0; + var first = true; + file: while (true) { + var eof = false; + while (len < buf.len) { + const n = libc.read(fd, buf[len..].ptr, buf.len - len); + if (n < 0) { + if (libc.errno(n) == .INTR) continue; + break :file; + } + if (n == 0) { + eof = true; + break; + } + len += @intCast(n); } - if (n == 0) break; - len += @intCast(n); + if (first and std.mem.indexOfScalar(u8, buf[0..@min(len, 1024)], 0) != null) break; + first = false; + // A line longer than the buffer is searched in buffer-sized parts. + const end = if (eof) len else if (std.mem.lastIndexOfScalar(u8, buf[0..len], '\n')) |nl| nl + 1 else len; + const result = grepText(shown, buf[0..end], pat, out[written..], find_max_hits - hits, lines_before); + hits += result.hits; + written += result.bytes; + if (eof or hits >= find_max_hits or written == out.len) break; + lines_before += std.mem.count(u8, buf[0..end], "\n"); + std.mem.copyForwards(u8, buf[0 .. len - end], buf[end..len]); + len -= end; } - // Read to its cap with more behind it: searched in part, and said. - var more: [1]u8 = undefined; - const longer = readable and len == buf.len and libc.read(fd, &more, 1) > 0; - _ = libc.close(fd); - if (!readable) continue; - const text = buf[0..len]; - if (std.mem.indexOfScalar(u8, text[0..@min(len, 1024)], 0) != null) continue; - if (longer) notes.partial += 1; - const shown = lsp.rel(home, path); - const result = grepText(shown, text, pat, out[written..], find_max_hits - hits); - hits += result.hits; - written += result.bytes; if (hits >= find_max_hits) notes.hits_cut = true; } return written; @@ -1366,14 +1377,14 @@ test "a directory the walk may not open is skipped and counted: Grep and Find ke try std.testing.expectEqual(@as(usize, 1), notes.skipped); } -test "Grep says when a cap hid what it might have found: a file read in part, the hits cut" { +test "Grep reads a long file to its end, and says when its hits were cut" { if (!platform_has_fs) return; const gpa = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var base_buf: [std.fs.max_path_bytes]u8 = undefined; const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; - // The match past the first 256 KiB of a long file. + // A match past the first buffer of a long file, on its own line number. const long = try gpa.alloc(u8, grep_max_bytes + 64); defer gpa.free(long); @memset(long, 'x'); @@ -1386,8 +1397,9 @@ test "Grep says when a cap hid what it might have found: a file read in part, th defer gpa.free(out); var notes: WalkNotes = .{}; var n = try grep(arena.allocator(), gpa, dir, dir, "needle", out, ¬es); - try std.testing.expectEqual(@as(usize, 0), n); - try std.testing.expectEqual(@as(usize, 1), notes.partial); + var want_buf: [64]u8 = undefined; + const want = try std.fmt.bufPrint(&want_buf, "long.txt:{d}:", .{std.mem.count(u8, long, "\n")}); + try std.testing.expect(std.mem.startsWith(u8, out[0..n], want)); // More hits than the cap. var many: std.ArrayList(u8) = .empty; defer many.deinit(gpa); @@ -1398,7 +1410,7 @@ test "Grep says when a cap hid what it might have found: a file read in part, th try std.testing.expect(notes.hits_cut); var said: [256]u8 = undefined; const lines = said[0..notes.write(&said)]; - try std.testing.expectEqualStrings("cut at 512 hits\n1 file read only in part (first 256 KiB)\n", lines); + try std.testing.expectEqualStrings("cut at 512 hits\n", lines); try std.testing.expect(WalkNotes.isNote("cut at 512 hits") and WalkNotes.isNote("2 directories skipped: permission denied") and !WalkNotes.isNote("src/2 directories.txt")); } diff --git a/src/gui/gui.zig b/src/gui/gui.zig index f9921111..9cd37b6b 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -828,18 +828,13 @@ fn emitTouchClick(t: *Touch, in: *Input, point: TouchNormPoint, button: pardes.M in.post(.{ .mouse = .{ .button = button, .kind = .release, .col = cell.col, .row = cell.row, .tag_hit = cell.tag_hit, .body_hit = cell.body_hit } }); } -fn normCell(norm: f32, win: f32, cell: f32) u16 { - const px = std.math.clamp(norm, 0.0, 1.0) * win; - return @intFromFloat(@max(0, @floor(px / cell))); -} - const Pty = struct { fd: c_int, pid: libc.pid_t, serial: u32, kill_at: i64 = 0, - reader: ?std.Thread = null, - stop: [2]c_int = .{ -1, -1 }, + /// Its reader, blocked in an Io read: `closePty` cancels it. + reader: ?std.Io.Future(void) = null, /// A command pane's child, watched to its exit (host_io.watchExit); /// the pty stays open until both its end of file and its exit. cmd: host_io.CommandWatch = .{}, @@ -876,31 +871,6 @@ const Msg = union(enum) { } }; -const LspWorkers = struct { - const capacity = 16; - active: std.atomic.Value(usize) = .init(0), - - fn start(workers: *LspWorkers) bool { - var count = workers.active.load(.monotonic); - while (count < capacity) - count = workers.active.cmpxchgWeak(count, count + 1, .monotonic, .monotonic) orelse return true; - return false; - } - - fn finish(workers: *LspWorkers) void { - const previous = workers.active.fetchSub(1, .release); - std.debug.assert(previous > 0); - } - - fn wait(workers: *LspWorkers) void { - var spins: u8 = 0; - while (workers.active.load(.acquire) != 0) { - spins +%= 1; - if (spins == 0) std.Thread.yield() catch {} else std.atomic.spinLoopHint(); - } - } -}; - const PipeTasks = selection_pipe.Tasks; const queue_capacity = 512; @@ -918,10 +888,13 @@ const MessageBatch = struct { const Queue = struct { gpa: std.mem.Allocator, lsp_allocator: std.mem.Allocator, - lsp_workers: *LspWorkers, + /// The query in flight; the UI thread's alone (spawnLsp, teardown). + lsp_task: ?host_io.Lsp.Task = null, sdl_wake: bool, // wake a blocking SDL_WaitEventTimeout on cross-thread push - mutex: libc.pthread_mutex_t = .{}, - space: libc.pthread_cond_t = .{}, + /// The process's Io: its terminal readers wait for space on `space`. + io: std.Io, + mutex: std.Io.Mutex = .init, + space: std.Io.Condition = .init, items: [queue_capacity]Msg = undefined, head: usize = 0, len: usize = 0, @@ -934,13 +907,11 @@ const Queue = struct { completion_len: usize = 0, fn lock(q: *Queue) void { - // unreachable failures: pthread calls on this queue's own initialised, non-recursive - // mutex and condition fail only on misuse (EINVAL, EDEADLK), never on input. - std.debug.assert(libc.pthread_mutex_lock(&q.mutex) == .SUCCESS); + q.mutex.lockUncancelable(q.io); } fn unlock(q: *Queue) void { - std.debug.assert(libc.pthread_mutex_unlock(&q.mutex) == .SUCCESS); + q.mutex.unlock(q.io); } fn wake(q: *Queue) void { @@ -973,14 +944,14 @@ const Queue = struct { }; if (matches) q.removeAt(i).deinit(q.gpa, q.lsp_allocator) else i += 1; } - std.debug.assert(libc.pthread_cond_broadcast(&q.space) == .SUCCESS); + q.space.broadcast(q.io); } fn pushOutput(q: *Queue, pane: u8, gen: u32, bytes: []u8) bool { q.lock(); while (!q.closed and q.readers[pane] == gen and q.len >= output_capacity) { q.waiting += 1; - std.debug.assert(libc.pthread_cond_wait(&q.space, &q.mutex) == .SUCCESS); + q.space.waitUncancelable(q.io, &q.mutex); q.waiting -= 1; } if (q.closed or q.readers[pane] != gen) { @@ -1088,7 +1059,7 @@ const Queue = struct { @memcpy(batch.items[batch.len..][0..q.completion_len], q.completions[0..q.completion_len]); batch.len += q.completion_len; q.completion_len = 0; - std.debug.assert(libc.pthread_cond_broadcast(&q.space) == .SUCCESS); + q.space.broadcast(q.io); } fn discardCompletions(q: *Queue) void { @@ -1104,7 +1075,7 @@ const Queue = struct { q.closed = true; q.files_changed = false; q.readers = @splat(null); - std.debug.assert(libc.pthread_cond_broadcast(&q.space) == .SUCCESS); + q.space.broadcast(q.io); q.unlock(); q.discardCompletions(); q.lock(); @@ -1121,15 +1092,12 @@ const Queue = struct { fn deinit(q: *Queue) void { q.close(); std.debug.assert(q.waiting == 0); - std.debug.assert(libc.pthread_cond_destroy(&q.space) == .SUCCESS); - std.debug.assert(libc.pthread_mutex_destroy(&q.mutex) == .SUCCESS); } }; test "GUI completion survives a full output queue" { const gpa = std.testing.allocator; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false, .lsp_id = 7 }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false, .lsp_id = 7 }; defer queue.deinit(); queue.acceptReader(0, 1); for (0..output_capacity) |_| queue.push(.{ .output = .{ @@ -1185,8 +1153,7 @@ const PtyTests = struct { test "GUI PTY backpressure retains byte order and tail before EOF" { const gpa = std.testing.allocator; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); queue.acceptReader(0, 1); for (0..output_capacity) |_| queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "before") } }); @@ -1220,8 +1187,7 @@ test "GUI PTY backpressure retains byte order and tail before EOF" { test "GUI PTY backpressure cancellation and close release owned producers" { const gpa = std.testing.allocator; for ([_]bool{ false, true }) |close| { - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); queue.acceptReader(0, 1); for (0..output_capacity) |_| queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "before") } }); @@ -1252,8 +1218,7 @@ test "GUI PTY backpressure cancellation and close release owned producers" { test "GUI PTY EOF reserve cannot evict terminal output" { const gpa = std.testing.allocator; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); for (0..pardes.MAX_PANES) |pane| queue.acceptReader(@intCast(pane), 1); for (0..output_capacity) |_| queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "before") } }); @@ -1269,8 +1234,7 @@ test "GUI PTY reader delivers a real shell tail before EOF and joins on close" { const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); var ptys: [pardes.MAX_PANES]?Pty = @splat(null); var gens: [pardes.MAX_PANES]u32 = @splat(1); @@ -1320,8 +1284,7 @@ test "GUI PTY Restore joins a real reader waiting for queue space" { var core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); try dump.dumpState(core); - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); queue.acceptReader(1, 1); for (0..output_capacity) |_| queue.push(.{ .output = .{ .pane = 1, .gen = 1, .bytes = try gpa.dupe(u8, "other pane") } }); @@ -1365,8 +1328,7 @@ test "GUI PTY deletion joins an idle reader and retains only its owned child for const gpa = std.testing.allocator; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); var ptys: [pardes.MAX_PANES]?Pty = @splat(null); var gens: [pardes.MAX_PANES]u32 = @splat(1); @@ -1397,8 +1359,7 @@ test "GUI PTY deletion joins an idle reader and retains only its owned child for test "GUI PTY file watcher stops and joins without closing its watched descriptor" { if (!file_watch.supported) return error.SkipZigTest; const gpa = std.testing.allocator; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); const fd = file_watch.init(true); if (fd < 0) return error.WatchInitFailed; @@ -1422,8 +1383,7 @@ test "GUI completion failure survives backlog and leaves the document unchanged" pane.body.cur_col = 1; core.lspRequest(core.active, .completion, ""); const id = core.lsp_wait.?.id; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false, .lsp_id = id }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false, .lsp_id = id }; defer queue.deinit(); queue.acceptReader(0, 1); for (0..output_capacity) |_| queue.push(.{ .output = .{ @@ -1452,8 +1412,7 @@ test "GUI completion failure survives backlog and leaves the document unchanged" test "GUI completions retain their arrival order across LSP and pipes" { const gpa = std.testing.allocator; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false, .lsp_id = 2 }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false, .lsp_id = 2 }; defer queue.deinit(); queue.push(.{ .pipe = .{ .id = 1, .success = true, .outputs = &.{} } }); queue.push(.{ .lsp = .{ .id = 2, .rows = try gpa.dupe(u8, "second") } }); @@ -1469,8 +1428,7 @@ test "GUI completions retain their arrival order across LSP and pipes" { test "GUI completion reset frees queued payloads and rejects late LSP workers" { const gpa = std.testing.allocator; - var workers: LspWorkers = .{}; - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false, .lsp_id = 9 }; + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false, .lsp_id = 9 }; defer queue.deinit(); queue.acceptReader(0, 1); queue.push(.{ .output = .{ .pane = 0, .gen = 1, .bytes = try gpa.dupe(u8, "retained") } }); @@ -1523,29 +1481,22 @@ fn lspStatusSink(ctx: ?*anyopaque, text: []const u8) void { q.push(.{ .lsp_status = copy }); } -fn readPtyThread(gpa: std.mem.Allocator, fd: c_int, stop: c_int, pane: u8, gen: u32, q: *Queue) void { +fn readPty(io: std.Io, gpa: std.mem.Allocator, fd: c_int, pane: u8, gen: u32, q: *Queue) void { + const pty: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; var buf: [0x10000]u8 = undefined; var failure: ?anyerror = null; while (true) { - var fds = [_]libc.pollfd{ - .{ .fd = stop, .events = libc.POLL.IN, .revents = 0 }, - .{ .fd = fd, .events = libc.POLL.IN, .revents = 0 }, + const n = pty.readStreaming(io, &.{&buf}) catch |err| switch (err) { + // A pty whose child has gone answers EIO: its end of file. + error.EndOfStream, error.InputOutput => break, + error.Canceled => return, + else => { + failure = err; + break; + }, }; - if (libc.poll(&fds, fds.len, -1) < 0) { - if (libc.errno(-1) == .INTR) continue; - failure = error.PollFailed; - break; - } - if (fds[0].revents != 0) return; - if (fds[1].revents == 0) continue; - const n = libc.read(fd, &buf, buf.len); - if (n < 0) { - if (libc.errno(n) == .INTR) continue; - if (libc.errno(n) != .IO) failure = error.ReadFailed; - break; - } - if (n == 0) break; - const bytes = gpa.dupe(u8, buf[0..@intCast(n)]) catch |err| { + if (n == 0) continue; + const bytes = gpa.dupe(u8, buf[0..n]) catch |err| { failure = err; break; }; @@ -1566,14 +1517,9 @@ fn stopPipe() ![2]c_int { fn spawnReader(gpa: std.mem.Allocator, pt: *Pty, pane: u8, gen: u32, q: *Queue) !void { std.debug.assert(pt.reader == null and pt.fd >= 0); - const stop = try stopPipe(); - errdefer for (stop) |fd| { - _ = libc.close(fd); - }; q.acceptReader(pane, gen); errdefer q.cancelReader(pane, gen); - pt.reader = try std.Thread.spawn(.{}, readPtyThread, .{ gpa, pt.fd, stop[0], pane, gen, q }); - pt.stop = stop; + pt.reader = try q.io.concurrent(readPty, .{ q.io, gpa, pt.fd, pane, gen, q }); } fn watchThread(fd: c_int, stop: c_int, q: *Queue) void { @@ -1592,9 +1538,8 @@ fn watchThread(fd: c_int, stop: c_int, q: *Queue) void { } } -fn lspThread(lsp_allocator: std.mem.Allocator, workers: *LspWorkers, job: *host_io.Lsp.Job, q: *Queue) void { - defer workers.finish(); - host_io.Lsp.work(lsp_allocator, job, q, pushLspRows); +fn lspThread(io: std.Io, lsp_allocator: std.mem.Allocator, job: *host_io.Lsp.Job, q: *Queue) anyerror!void { + host_io.Lsp.work(io, lsp_allocator, job, q, pushLspRows); } fn pushLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { @@ -1602,107 +1547,52 @@ fn pushLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { q.push(.{ .lsp = .{ .id = id, .rows = rows } }); } -fn spawnLsp(core: *pardes.Pardes, q: *Queue, e: host_io.Lsp.Request) void { +fn spawnLsp(core: *pardes.Pardes, io: std.Io, q: *Queue, e: host_io.Lsp.Request) void { const lsp_allocator = q.lsp_allocator; q.lock(); q.lsp_id = e.id; q.discardLsp(); q.unlock(); - if (!q.lsp_workers.start()) { - core.update(.{ .lsp_resp = .{ .id = e.id, .rows = null } }); - return core.reportError(e.pane, "lsp", error.WorkersBusy); + // Its waits are cancelation points: this join is short, and what it + // still delivers carries an id the queue now rejects. + if (q.lsp_task) |*old| { + old.future.cancel(io) catch {}; + q.lsp_task = null; } const job = host_io.Lsp.snapshot(lsp_allocator, core, e) catch |err| { - q.lsp_workers.finish(); core.update(.{ .lsp_resp = .{ .id = e.id, .rows = null } }); return core.reportError(e.pane, "lsp", err); }; - const th = std.Thread.spawn(.{}, lspThread, .{ lsp_allocator, q.lsp_workers, job, q }) catch |err| { - q.lsp_workers.finish(); + const future = io.concurrent(lspThread, .{ io, lsp_allocator, job, q }) catch |err| { job.free(lsp_allocator); core.update(.{ .lsp_resp = .{ .id = e.id, .rows = null } }); return core.reportError(e.pane, "lsp", err); }; - th.detach(); + q.lsp_task = .{ .id = e.id, .future = future }; } -test "GUI LSP worker limit rejects before allocation and recovers after owned workers exit" { +test "GUI LSP query answers, and a newer one cancels it" { const gpa = std.testing.allocator; + const io = std.testing.io; const core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); - const pane = try core.setTestFile("abc"); - pane.body.cur_col = 1; - var workers: LspWorkers = .{}; - var gate: std.Io.Event = .unset; - var threads: [LspWorkers.capacity]?std.Thread = @splat(null); - defer { - gate.set(std.testing.io); - for (threads) |thread| if (thread) |owned| owned.join(); - workers.wait(); - } - for (&threads) |*thread| { - try std.testing.expect(workers.start()); - thread.* = std.Thread.spawn(.{}, struct { - fn run(active: *LspWorkers, ready: *std.Io.Event) void { - defer active.finish(); - ready.waitUncancelable(std.testing.io); - } - }.run, .{ &workers, &gate }) catch |err| { - workers.finish(); - return err; - }; - } - try std.testing.expectEqual(@as(usize, LspWorkers.capacity), workers.active.load(.monotonic)); - try std.testing.expect(!workers.start()); - var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); - var queue: Queue = .{ .gpa = gpa, .lsp_allocator = failing.allocator(), .lsp_workers = &workers, .sdl_wake = false }; + _ = try core.setTestFile("abc"); + var queue: Queue = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .sdl_wake = false }; defer queue.deinit(); - core.lspRequest(core.active, .completion, ""); - const rejected = core.lsp_wait.?.id; - queue.lsp_id = rejected -% 1; - queue.push(.{ .lsp = .{ .id = queue.lsp_id.?, .rows = try gpa.dupe(u8, "obsolete queued result") } }); - spawnLsp(core, &queue, .{ - .id = rejected, - .kind = .completion, - .pane = @intCast(core.active), - .offset = 1, - .arg = "", - }); - try std.testing.expect(core.lsp_wait == null); - try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); - try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "workers busy") != null); - try std.testing.expectEqual(@as(usize, 0), failing.alloc_index); - try std.testing.expect(!failing.has_induced_failure); - try std.testing.expectEqual(rejected, queue.lsp_id.?); - try std.testing.expectEqual(@as(usize, 0), queue.completion_len); - queue.push(.{ .lsp = .{ .id = rejected -% 1, .rows = try gpa.dupe(u8, "obsolete late result") } }); - try std.testing.expectEqual(@as(usize, 0), queue.completion_len); - try std.testing.expectEqual(@as(usize, LspWorkers.capacity), workers.active.load(.monotonic)); - - gate.set(std.testing.io); - workers.wait(); - try std.testing.expectEqual(@as(usize, 0), workers.active.load(.monotonic)); - queue.lsp_allocator = gpa; - core.lspRequest(core.active, .status, ""); - const accepted = core.lsp_wait.?.id; - spawnLsp(core, &queue, .{ - .id = accepted, - .kind = .status, - .pane = @intCast(core.active), - .offset = 0, - .arg = "", - }); - workers.wait(); + for (0..2) |_| { + core.lspRequest(core.active, .status, ""); + spawnLsp(core, io, &queue, .{ .id = core.lsp_wait.?.id, .kind = .status, .pane = @intCast(core.active), .offset = 0, .arg = "" }); + } + const last = core.lsp_wait.?.id; + try queue.lsp_task.?.future.await(io); + queue.lsp_task = null; var batch = queue.take(); defer for (batch.slice()) |msg| msg.deinit(gpa, gpa); try std.testing.expectEqual(@as(usize, 1), batch.len); - try std.testing.expectEqual(accepted, batch.items[0].lsp.id); + try std.testing.expectEqual(last, batch.items[0].lsp.id); try std.testing.expect(batch.items[0].lsp.rows != null); - core.update(.{ .lsp_resp = .{ .id = accepted, .rows = batch.items[0].lsp.rows } }); + core.update(.{ .lsp_resp = .{ .id = last, .rows = batch.items[0].lsp.rows } }); try std.testing.expect(core.lsp_wait == null); - try std.testing.expectEqual(@as(usize, 0), workers.active.load(.monotonic)); - try std.testing.expectEqualStrings("abc", pane.file.?.content); } fn pipeThread(io: std.Io, gpa: std.mem.Allocator, job: *selection_pipe.Job, q: *Queue) anyerror!void { @@ -1748,11 +1638,10 @@ test "GUI worker setup failures finish matching LSP and pipe requests" { var failing = std.testing.FailingAllocator.init(gpa, .{ .fail_index = if (failure == 0) 0 else std.math.maxInt(usize), }); - var workers: LspWorkers = .{}; var queue: Queue = .{ + .io = std.testing.io, .gpa = gpa, .lsp_allocator = failing.allocator(), - .lsp_workers = &workers, .sdl_wake = false, }; defer queue.deinit(); @@ -1768,7 +1657,7 @@ test "GUI worker setup failures finish matching LSP and pipe requests" { if (failure == 0) { queue.lsp_id = req.id -% 1; queue.push(.{ .lsp = .{ .id = queue.lsp_id.?, .rows = try gpa.dupe(u8, "old queued result") } }); - spawnLsp(core, &queue, req); + spawnLsp(core, std.testing.io, &queue, req); try std.testing.expectEqual(req.id, queue.lsp_id.?); try std.testing.expectEqual(@as(usize, 0), queue.completion_len); queue.push(.{ .lsp = .{ .id = req.id -% 1, .rows = try gpa.dupe(u8, "late old result") } }); @@ -1791,7 +1680,7 @@ test "GUI worker setup failures finish matching LSP and pipe requests" { spawnPipe(core, failing_io, failing.allocator(), &queue, &tasks, pipe_id); try std.testing.expect(core.pipe.wait == null); try std.testing.expectEqualStrings("abc", pane.file.?.content); - try std.testing.expectEqual(@as(usize, 0), workers.active.load(.monotonic)); + try std.testing.expect(queue.lsp_task == null); try std.testing.expectEqual(@as(usize, 0), tasks.len); try std.testing.expectEqual(@as(usize, 0), queue.len); } @@ -2071,22 +1960,6 @@ fn fixedCellLayout(g: *const Gui) CellLayout { return .{ .w = @floatFromInt(g.cell_w), .h = @floatFromInt(g.cell_h), .x_off = 0, .y_off = 0 }; } -fn compactTaglineLayout(g: *const Gui, origin_col: f32) CellLayout { - const body_w: f32 = @floatFromInt(g.cell_w); - const tag_w: f32 = @floatFromInt(g.tagline_width); - return .{ - .w = tag_w, - .h = @floatFromInt(g.cell_h), - .x_off = origin_col * (body_w - tag_w), - .y_off = 0, - }; -} - -fn taglineLayoutForCell(g: *const Gui, col: u16) CellLayout { - // Canonical tag cells are physical grips; text is drawn by TagLayer. - return compactTaglineLayout(g, @floatFromInt(col)); -} - const boxContains = pardes.animation.Box.contains; /// What one tier draws, or one track in tiers 2 and 3 (docs/render-pipeline.md @@ -2663,15 +2536,14 @@ fn localSession( var ptys: [pardes.MAX_PANES]?Pty = @splat(null); var gens: [pardes.MAX_PANES]u32 = @splat(0); - var lsp_workers: LspWorkers = .{}; var queue: Queue = .{ + .io = io, .gpa = gpa, .lsp_allocator = allocs.lsp, - .lsp_workers = &lsp_workers, .sdl_wake = true, }; defer { - lsp_workers.wait(); + if (queue.lsp_task) |*task| task.future.cancel(io) catch {}; queue.deinit(); } var pipe_tasks: PipeTasks = .{}; @@ -3035,15 +2907,14 @@ fn runGrid(init: std.process.Init, opts_in: pardes.Options) !void { var ptys: [pardes.MAX_PANES]?Pty = @splat(null); var gens: [pardes.MAX_PANES]u32 = @splat(0); - var lsp_workers: LspWorkers = .{}; var queue: Queue = .{ + .io = io, .gpa = gpa, .lsp_allocator = allocs.lsp, - .lsp_workers = &lsp_workers, .sdl_wake = false, }; defer { - lsp_workers.wait(); + if (queue.lsp_task) |*task| task.future.cancel(io) catch {}; queue.deinit(); } var pipe_tasks: PipeTasks = .{}; @@ -4195,13 +4066,12 @@ const Shell = struct { fn closePty(s: *Shell, pane: u8) void { const pt = if (s.ptys[pane]) |*pt| pt else return; if (pt.fd < 0) return; + // Out of the queue first, which lets go a reader waiting for room + // in it; then its read is canceled (or, at its end, it is joined). s.queue.cancelReader(pane, s.gens[pane]); - if (pt.reader) |thread| { - _ = host_io.writeFd(pt.stop[1], "x"); - thread.join(); + if (pt.reader) |*reader| { + reader.cancel(s.queue.io); // the Io it was started on (spawnReader) pt.reader = null; - for (pt.stop) |fd| _ = libc.close(fd); - pt.stop = .{ -1, -1 }; } _ = libc.close(pt.fd); pt.fd = -1; @@ -4848,11 +4718,10 @@ test "the headless grid host round-trips a yank back as a paste" { var ptys: [pardes.MAX_PANES]?Pty = @splat(null); var gens: [pardes.MAX_PANES]u32 = @splat(0); - var lsp_workers: LspWorkers = .{}; var queue: Queue = .{ + .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, - .lsp_workers = &lsp_workers, .sdl_wake = false, }; defer queue.deinit(); @@ -4933,7 +4802,7 @@ fn openLink(ctx: ?*anyopaque, url: []const u8) void { fn lsp(ctx: ?*anyopaque, req: host_io.Lsp.Request) void { const s = shellOf(ctx); - if (s.threads_ok) return spawnLsp(s.core, s.queue, req); + if (s.threads_ok) return spawnLsp(s.core, s.io, s.queue, req); s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); s.core.reportError(req.pane, "lsp", error.WorkersUnavailable); } @@ -5198,6 +5067,12 @@ const Glide = struct { below: []pardes.Cell = &.{}, nabove: u16 = 0, nbelow: u16 = 0, + /// The core's lines a scroll moved, not yet measured; and what the + /// glide in flight has moved, in lines and in the picture's rows. A + /// wrapped line is several rows, and the thumb counts lines. + pending_lines: f32 = 0, + lines_moved: f32 = 0, + rows_moved: f32 = 0, /// The Motion flavour the last loop step read. motion: pardes.animation.Motion = .{}, @@ -5211,6 +5086,16 @@ const Glide = struct { glide.pending = false; glide.nabove = 0; glide.nbelow = 0; + glide.pending_lines = 0; + glide.lines_moved = 0; + glide.rows_moved = 0; + } + + /// The glide's lag in the core's lines: its rows, scaled by the lines + /// they carried. + fn lagLines(glide: *const Glide) f32 { + if (glide.rows_moved == 0) return glide.offset; + return glide.offset * glide.lines_moved / glide.rows_moved; } fn deinit(glide: *Glide, gpa: std.mem.Allocator) void { @@ -5270,6 +5155,9 @@ const Glide = struct { break :found kk; } else 0; if (shift == 0) return glide.stop(); + glide.rows_moved += @floatFromInt(shift); + glide.lines_moved += glide.pending_lines; + glide.pending_lines = 0; // The rows that left: past the top going down, the bottom going up. if (!glide.ensure(gpa)) return glide.stop(); const keep = if (glide.dir > 0) &glide.above else &glide.below; @@ -5326,6 +5214,8 @@ fn stepGlide(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { glide.offset = 0; glide.nabove = 0; glide.nbelow = 0; + glide.lines_moved = 0; + glide.rows_moved = 0; } } const notch = g.scroll_notch; @@ -5357,6 +5247,8 @@ fn stepGlide(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { } var left = notch; var moved = false; + const first = pane.scroll(); + defer glide.pending_lines += @floatFromInt(@abs(pane.scroll() - first)); while (left != 0) { const down = left > 0; left += if (down) -1 else 1; @@ -9347,7 +9239,7 @@ fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, gr // In pixels, not rows, and with the picture while it glides // or lags behind the core's rows (both in rows of the body). const lag: f32 = if (g.glide.offset != 0 and g.glide.pane == rail.owner) - g.glide.offset + g.glide.lagLines() else if (g.scroll_pane != null and g.scroll_pane.? == rail.owner) g.scroll_lag else 0; const track_px = body_y1 - y0; const size = @min(track_px, @max(layout.h, rail.thumb_span * track_px)); @@ -9983,6 +9875,12 @@ test "the scrollbar thumb moves by the pixel and follows a glide" { g.glide.pane = core.active; g.glide.offset = -1; try std.testing.expectApproxEqAbs(at10, try thumb.top(&g, core), 1e-3); + // A wrapped line: the picture moved two rows for the one line, and the + // thumb lags the line, not two. + g.glide.lines_moved = 1; + g.glide.rows_moved = 2; + g.glide.offset = -2; + try std.testing.expectApproxEqAbs(at10, try thumb.top(&g, core), 1e-3); } test "the rule between stacked panes stays in the tag band's slack, at any tagline size" { @@ -10581,12 +10479,11 @@ fn appendWorkspacePet(g: *Gui, core: ?*const pardes.Pardes, surface: *const pard return; } // Read only the rendered global row. No pane/column tags, status text or - // mouse targets are changed, and editing the workspace parks the pet. + // mouse targets are changed; editing the workspace tag leaves it be. var occupied: usize = 0; for (surface.cells[0..surface.cols], 0..) |*cell, i| { if (cellCodepoint(cell) != ' ') occupied = i + 1; } - const editing = p.header_focus and p.header_column == null; const band_top: f32 = @floatFromInt(taglineBandOffset(0, builder.win_h, g.cell_h, g.tagline_height)); const region = if (occupied >= surface.cols) null else pet.lane( occupied, @@ -10594,7 +10491,6 @@ fn appendWorkspacePet(g: *Gui, core: ?*const pardes.Pardes, surface: *const pard builder.win_w, band_top, @floatFromInt(g.tagline_height), - editing, ); // SDL's regular pump already wakes at least every 16 ms. Quantization in // sample keeps this independent of input, render rate and scene effects, @@ -10602,16 +10498,24 @@ fn appendWorkspacePet(g: *Gui, core: ?*const pardes.Pardes, surface: *const pard const pose = g.pet_state.sample(kind, c.SDL_GetTicks(), region) orelse return; const ink = overlayRgb(p.chromeTheme().tag_fg); const eye = overlayRgb(p.chromeTheme().tag_bg); + // Behind the cursor: the overlay is over the cells, so the pixels a + // cursor covers are left out. + var boxes: [max_cursors]CursorBox = undefined; + const cursors = boxes[0..cursorBoxes(g, surface, fixedCellLayout(g), builder.win_h, &boxes)]; for (0..pet.height) |y| for (0..pet.width) |x| { const color = pet.pixel(kind, pose, x, y); if (color == 0) continue; const x0 = pose.x + @as(f32, @floatFromInt(x)) * pose.scale; const y0 = pose.y + @as(f32, @floatFromInt(y)) * pose.scale; + const covered = for (cursors) |box| { + if (x0 < box.x1 and x0 + pose.scale > box.x0 and y0 < box.y1 and y0 + pose.scale > box.y0) break true; + } else false; + if (covered) continue; builder.addRect(x0, y0, x0 + pose.scale, y0 + pose.scale, if (color == 2) eye else ink); }; } -test "pet overlay stays beyond workspace text and vanishes while its tag is edited" { +test "pet overlay stays beyond workspace text and keeps going while its tag is edited" { std.testing.refAllDecls(pet); const core = try pardes.Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); defer core.deinit(); @@ -10638,10 +10542,13 @@ test "pet overlay stays beyond workspace text and vanishes while its tag is edit try std.testing.expect(x >= 20 * 8 - 0.01); try std.testing.expect(y >= 0 and y < 20); } + const before = g.pet_state; pardes.tagline.enterHeader(core, null); builder.len = 0; appendWorkspacePet(&g, core, &surface, &builder); - try std.testing.expectEqual(@as(usize, 0), builder.len); + try std.testing.expect(builder.len > 0); + try std.testing.expectEqual(before.tick, g.pet_state.tick); + try std.testing.expectEqual(before.x, g.pet_state.x); } fn cursorColor(chrome: *const pardes.Chrome, cell: *const pardes.Cell, role: pardes.FontRole) [3]u8 { diff --git a/src/gui/pet.zig b/src/gui/pet.zig index a249d70f..7a13ca91 100644 --- a/src/gui/pet.zig +++ b/src/gui/pet.zig @@ -13,8 +13,8 @@ const hop_ticks = 8; /// Only the trailing blank part of the global tag is eligible. The caller /// supplies its last occupied cell, including any wide-grapheme continuation. -pub fn lane(occupied: usize, cell_w: f32, screen_w: f32, top: f32, band_h: f32, editing: bool) ?Lane { - if (editing or cell_w <= 0 or band_h < height + 2) return null; +pub fn lane(occupied: usize, cell_w: f32, screen_w: f32, top: f32, band_h: f32) ?Lane { + if (cell_w <= 0 or band_h < height + 2) return null; const scale = @min(3, @floor((band_h - 2) / height)); const left = @as(f32, @floatFromInt(occupied + 2)) * cell_w; const right = screen_w - 2 * cell_w - width * scale; @@ -32,11 +32,10 @@ pub const State = struct { frame: u8 = 0, rng: std.Random.DefaultPrng = undefined, + /// No lane (the tag's text has filled it) hides the pet but keeps + /// where it was and what it was doing. pub fn sample(s: *State, kind: Kind, now_ms: u64, area: ?Lane) ?Pose { - const region = area orelse { - s.* = .{}; - return null; - }; + const region = area orelse return null; if (kind == .off) { s.* = .{}; return null; @@ -142,11 +141,10 @@ pub fn pixel(kind: Kind, pose: Pose, x_in: usize, y: usize) u2 { }; } -test "pet stays in trailing workspace blanks and disappears during editing" { - try std.testing.expect(lane(20, 8, 200, 0, 16, false) == null); - try std.testing.expect(lane(3, 8, 200, 0, 16, true) == null); - try std.testing.expect(lane(3, 8, 200, 0, 10, false) == null); - const region = lane(3, 8, 200, 2, 20, false).?; +test "pet stays in trailing workspace blanks, and a lost lane hides it without a reset" { + try std.testing.expect(lane(20, 8, 200, 0, 16) == null); + try std.testing.expect(lane(3, 8, 200, 0, 10) == null); + const region = lane(3, 8, 200, 2, 20).?; try std.testing.expect(region.left >= 5 * 8); var state: State = .{}; var moved = false; @@ -159,12 +157,15 @@ test "pet stays in trailing workspace blanks and disappears during editing" { reversed = reversed or pose.left; } try std.testing.expect(moved and reversed); + const kept = state; try std.testing.expect(state.sample(.cat, 300000, null) == null); + try std.testing.expectEqual(kept.x, state.x); + try std.testing.expectEqual(kept.tick, state.tick); try std.testing.expect(state.sample(.off, 300100, region) == null); } test "pet clock is fixed rate and sprites bounded in both directions" { - const region = lane(1, 8, 400, 0, 16, false).?; + const region = lane(1, 8, 400, 0, 16).?; var state: State = .{}; const start = state.sample(.frog, 1000, region).?; try std.testing.expectEqualDeep(start, state.sample(.frog, 1099, region).?); @@ -180,7 +181,7 @@ test "pet clock is fixed rate and sprites bounded in both directions" { } test "pet rests at random spots and the frog travels only in the air" { - const region = lane(1, 8, 800, 0, 16, false).?; + const region = lane(1, 8, 800, 0, 16).?; var state: State = .{}; var last = state.sample(.frog, 0, region).?; var rested_midway = false; @@ -195,7 +196,7 @@ test "pet rests at random spots and the frog travels only in the air" { } test "pet initial idle visibly animates without walking or leaving its tile" { - const region = lane(1, 8, 400, 0, 16, false).?; + const region = lane(1, 8, 400, 0, 16).?; for ([_]Kind{ .cat, .frog }) |kind| { var state: State = .{}; const initial = state.sample(kind, 0, region).?; diff --git a/src/host_io.zig b/src/host_io.zig index c593551b..2c736e20 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -203,11 +203,14 @@ pub const Lsp = struct { } others.deinit(gpa); } + var copied: usize = 0; for (core.panes, 0..) |slot, i| { const other = slot orelse continue; if (i == req.pane) continue; const f = other.file orelse continue; if (f.output != null) continue; + if (copied + f.content.len > pardes.memory.limits.lsp_snapshot_bytes) continue; + copied += f.content.len; const local = filesystem.localPath(f.path) orelse continue; const other_path = try gpa.dupe(u8, local); const other_source = gpa.dupeSentinel(u8, f.content, 0) catch |err| { @@ -224,13 +227,19 @@ pub const Lsp = struct { // Null is failure; the receiver frees non-null rows with the job's allocator. pub const Deliver = *const fn (ctx: ?*anyopaque, id: u32, rows: ?[]u8) void; - pub fn work(gpa: std.mem.Allocator, job: *Job, ctx: ?*anyopaque, deliver: Deliver) void { + pub fn work(io: std.Io, gpa: std.mem.Allocator, job: *Job, ctx: ?*anyopaque, deliver: Deliver) void { defer job.free(gpa); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); + // The query's memory is the fixed region memory.zig reserved at + // startup: a hard bound, reused by each query in turn. + const region = pardes.memory.takeLspQuery() orelse { + deliver(ctx, job.id, null); + return; + }; + var arena: std.heap.FixedBufferAllocator = .init(region); + defer pardes.memory.giveLspQuery(arena.end_index); var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); - pardes.lsp.query(gpa, arena.allocator(), .{ + pardes.lsp.query(io, gpa, arena.allocator(), .{ .kind = job.kind, .path = job.path, .source = job.source, @@ -240,6 +249,7 @@ pub const Lsp = struct { .others = job.others, .callstack_depth = job.callstack_depth, .callstack_corners = job.callstack_corners, + .budget = &arena, }, &out.writer) catch { deliver(ctx, job.id, null); return; @@ -367,7 +377,7 @@ pub const Lsp = struct { .offset = 0, .arg = "", }); - work(gpa, job, null, Sink.take); + work(std.testing.io, gpa, job, null, Sink.take); // `status` is the one kind that answers with no file and no cursor, which // is what makes it assertable here without a language server on the box. @@ -416,7 +426,7 @@ pub const Lsp = struct { .arg = "renamed", }); if (fail) failing.fail_index = failing.alloc_index; - work(failing.allocator(), job, &sink, Sink.take); + work(std.testing.io, failing.allocator(), job, &sink, Sink.take); try std.testing.expectEqual(fail, sink.failed); try std.testing.expect(core.lsp_wait == null); if (fail) { @@ -482,7 +492,7 @@ pub const Lsp = struct { defer core.deinit(); const job = try snapshot(gpa, core, .{ .id = 37, .kind = .status, .pane = @intCast(core.active), .offset = 0, .arg = "" }); var sink: Sink = .{}; - work(gpa, job, &sink, Sink.take); + work(std.testing.io, gpa, job, &sink, Sink.take); if (sink.rows) |rows| gpa.free(rows); try std.testing.expect(allocator.failed); try std.testing.expectEqual(@as(usize, 1), sink.calls); @@ -1179,7 +1189,7 @@ pub const Shell = struct { if (builtin.os.tag == .windows) return; var saved_buf: [std.fs.max_path_bytes:0]u8 = @splat(0); const saved: ?[:0]const u8 = if (std.c.getenv("XDG_RUNTIME_DIR")) |v| std.fmt.bufPrintSentinel(&saved_buf, "{s}", .{std.mem.span(v)}, 0) catch null else null; - defer _ = if (saved) |v| setenv("XDG_RUNTIME_DIR", v.ptr, 1) else unsetenv("XDG_RUNTIME_DIR"); + defer _ = if (saved) |v| setenv("XDG_RUNTIME_DIR", v.ptr, 1) else testUnsetenv("XDG_RUNTIME_DIR"); var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -1213,7 +1223,7 @@ pub const Shell = struct { try std.testing.expectEqualStrings(bash_rc, readSmall(c.bashPath().?, &buf) orelse return error.ReadFailed); // No runtime dir: private files, one per owner, gone at teardown. - _ = unsetenv("XDG_RUNTIME_DIR"); + _ = testUnsetenv("XDG_RUNTIME_DIR"); var d = PromptFiles.init(); var e = PromptFiles.init(); defer e.deinit(); @@ -1294,6 +1304,44 @@ pub const ChildEnv = struct { "TERM_PROGRAM=" ++ pardes.config.child_term_program, }; + /// What this editor tells its children of itself (exportPaneEnv, `$winid`), + /// kept here rather than set into this process's environment: std's Io read + /// that block at startup, and setenv/unsetenv rewrite it in place under it + /// (a spawn then scans a null inside it). `build` puts each exported one in + /// place of an inherited variable of its name; a cleared one hides it; one + /// never exported is inherited as it is. + pub const exported_names = [_][]const u8{ "PARDES_PID", "PARDES_9P", "PARDES_PANE", "PARDES_MOUNT", "winid" }; + var exported_state: [exported_names.len]enum { inherited, cleared, set } = @splat(.inherited); + var exported_line: [exported_names.len][pardes.memory.limits.host_path_cap + 64:0]u8 = undefined; + + /// Set (or, null, clear) what children are told for `var_name`. + pub fn exportVar(var_name: []const u8, value: ?[]const u8) void { + const i = exportedIndex(var_name).?; + const v = value orelse { + exported_state[i] = .cleared; + return; + }; + const line = std.fmt.bufPrintSentinel(&exported_line[i], "{s}={s}", .{ var_name, v }, 0) catch { + exported_state[i] = .cleared; + return; + }; + exported_state[i] = .set; + _ = line; + } + + /// What children are told for `var_name`, as `exportVar` left it; null + /// when cleared or never exported. + pub fn exported(var_name: []const u8) ?[]const u8 { + const i = exportedIndex(var_name) orelse return null; + if (exported_state[i] != .set) return null; + return std.mem.span(@as([*:0]const u8, &exported_line[i]))[var_name.len + 1 ..]; + } + + fn exportedIndex(var_name: []const u8) ?usize { + for (exported_names, 0..) |n, i| if (std.mem.eql(u8, n, var_name)) return i; + return null; + } + /// Wide enough for any real environment; `build` answers null rather than /// truncate, because a child missing half its variables is a worse bug /// than one missing TERM, and the caller then execs with `environ` intact. @@ -1318,7 +1366,8 @@ pub const ChildEnv = struct { if (std.mem.eql(u8, inherited, name(mine))) break true; } else false; if (shadowed) continue; - if (n + own.len + 1 > slots.len) return null; + if (exportedIndex(inherited)) |e| if (exported_state[e] != .inherited) continue; + if (n + own.len + exported_names.len + 1 > slots.len) return null; slots[n] = entry; n += 1; } @@ -1336,10 +1385,14 @@ pub const ChildEnv = struct { if (std.mem.eql(u8, name(entry.?), name(default))) break true; } else false; if (set) continue; - if (n + own.len + 4 > slots.len) return null; + if (n + own.len + exported_names.len + 4 > slots.len) return null; slots[n] = default; n += 1; } + for (&exported_line, exported_state) |*line, state| if (state == .set) { + slots[n] = line; + n += 1; + }; for (own) |mine| { slots[n] = mine; n += 1; @@ -1411,14 +1464,14 @@ test "the child environment replaces the launcher's terminal identity exactly on defer if (restore) |t| { _ = Shell.setenv("TERM", t.ptr, 1); } else { - _ = unsetenv("TERM"); + _ = testUnsetenv("TERM"); }; // A launcher TERM must be shadowed rather than duplicated, and the rest of // the environment must arrive untouched. try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("TERM", "dumb", 1)); try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("PARDES_CHILD_ENV_PROBE", "1", 1)); - defer _ = unsetenv("PARDES_CHILD_ENV_PROBE"); + defer _ = testUnsetenv("PARDES_CHILD_ENV_PROBE"); var slots: ChildEnv.Slots = undefined; // Where the user named no pager: a terminal's shell pages into a @@ -1481,6 +1534,16 @@ test "the child environment replaces the launcher's terminal identity exactly on extern "c" fn unsetenv(name: [*:0]const u8) c_int; +/// For tests: unset `name` without compacting the environment block std +/// captured at startup (std.testing.environ and Io's spawns read it later). A +/// new variable first moves glibc's `environ` to a heap copy, which unsetenv +/// then compacts instead. Runtime code never changes this process's +/// environment (ChildEnv.exportVar). +pub fn testUnsetenv(name: [*:0]const u8) c_int { + _ = Shell.setenv("PARDES_TEST_ENVIRON_COPIED", "1", 1); + return unsetenv(name); +} + /// The environment a pane's command is given (exportPaneEnv, `$winid`, /// ChildEnv), as `NAME=value` lines in `arena`, for a command that is not a /// pane's: an Edit's filters, run from pane `serial`. @@ -1497,10 +1560,7 @@ pub fn commandEnv(arena: std.mem.Allocator, serial: u32, adopts: bool) ![]const fn exportWinid(serial: u32) void { var buf: [16]u8 = undefined; - if (serial != 0) if (std.fmt.bufPrintSentinel(&buf, "{d}", .{serial}, 0)) |text| { - if (Shell.setenv("winid", text, 1) == 0) return; - } else |_| {}; - _ = unsetenv("winid"); + ChildEnv.exportVar("winid", if (serial == 0) null else std.fmt.bufPrint(&buf, "{d}", .{serial}) catch null); } /// The longest line a command pane runs (exec.zig refuses a longer one). @@ -1587,17 +1647,18 @@ pub fn forkShell( if (helper) |path| { const c = core.?; const pn = c.panes[pane].?; - const socket = libc.getenv("PARDES_9P") orelse return error.SessionSocketRequired; + const socket = ChildEnv.exported("PARDES_9P") orelse return error.SessionSocketRequired; var command: std.Io.Writer.Allocating = .init(c.gpa); defer command.deinit(); - try @import("linux/v9fs.zig").writeLaunchCommand(&command.writer, path, std.mem.span(socket), &spawn.argv); + try @import("linux/v9fs.zig").writeLaunchCommand(&command.writer, path, socket, &spawn.argv); if (!try pardes.panes.terminal.queuePendingCommand(pn, command.written())) return error.ShellAlreadyStarted; } // Built here and not after the fork: between fork and exec the child may // not call setenv, whose malloc can deadlock against a pty reader thread // that held the heap when the fork took its snapshot. var env_slots: ChildEnv.Slots = undefined; - const paging: ChildEnv.Paging = if (one_line != null) + const pages = if (core) |c| if (c.panes[pane]) |pn| pn.command_pages else false else false; + const paging: ChildEnv.Paging = if (one_line != null and !pages) .command else if (core) |c| (if (c.settings.pager == .off) .terminal_off else .terminal) else .terminal; const envp = ChildEnv.build(&env_slots, paging); @@ -1695,7 +1756,7 @@ test "a forked shell is told which terminal it is talking to" { defer if (restore) |t| { _ = Shell.setenv("TERM", t.ptr, 1); } else { - _ = unsetenv("TERM"); + _ = testUnsetenv("TERM"); }; _ = Shell.setenv("TERM", "dumb", 1); diff --git a/src/hunks.zig b/src/hunks.zig index 73c0654a..24aaf63d 100644 --- a/src/hunks.zig +++ b/src/hunks.zig @@ -368,21 +368,34 @@ const max_line_distance = 0.6; /// rather than aligned at a quadratic cost (delta aligns them all). const max_run = 256; const max_cells = 1 << 16; +/// Pairs one hunk compares (each a table of up to `max_cells`): past it, the +/// rest of its lines are shown unemphasised. And the scratch each pair is +/// aligned in, reused by the next: its table and the ranges it marks. +const max_pairs = 4096; +const pair_scratch_bytes = 8 << 20; /// Pair each removed line with the first added line after the last one /// paired that is near enough to it, in order, and emphasise in both the /// tokens one has and the other has not. fn inferEdits(arena: std.mem.Allocator, minus: []HunkLine, plus: []HunkLine) !void { if (minus.len == 0 or plus.len == 0 or minus.len > max_run or plus.len > max_run) return; + const plus_tokens = try arena.alloc([]const []const u8, plus.len); + for (plus, plus_tokens) |line, *tokens| tokens.* = try tokenize(arena, line.code); + var scratch: std.heap.FixedBufferAllocator = .init(try @import("memory.zig").unfilled(arena, pair_scratch_bytes)); + var pairs: usize = 0; var plus_index: usize = 0; for (minus) |*m| { const m_tokens = try tokenize(arena, m.code); var j = plus_index; while (j < plus.len) : (j += 1) { - const p_tokens = try tokenize(arena, plus[j].code); + const p_tokens = plus_tokens[j]; if ((m_tokens.len + 1) * (p_tokens.len + 1) > max_cells) continue; - var alignment = try Alignment.init(arena, m_tokens, p_tokens); - const marks = try annotate(arena, &alignment, m.code, plus[j].code); + if (pairs == max_pairs) return; + pairs += 1; + scratch.reset(); + const pair = scratch.allocator(); + var alignment = Alignment.init(pair, m_tokens, p_tokens) catch continue; + const marks = annotate(pair, &alignment, m.code, plus[j].code) catch continue; if (marks.distance > max_line_distance) continue; for (marks.minus) |r| for (m.styles[r[0]..r[1]]) |*b| { b.* |= syntax.diff_emph; diff --git a/src/image.zig b/src/image.zig index 8bf9de08..5797ce9e 100644 --- a/src/image.zig +++ b/src/image.zig @@ -768,7 +768,13 @@ pub fn readable(bytes: []const u8) bool { /// decode + downscale to RGBA, gpa-owned. Returns null on any failure — the /// pane then simply shows a blank body. pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) ?struct { rgba: []u8, w: usize, h: usize } { - if (bytes.len == 0) return null; + if (bytes.len == 0 or bytes.len > std.math.maxInt(c_int)) return null; + // Bounded before decoding: a few KB of PNG can name gigapixels. + var iw: c_int = 0; + var ih: c_int = 0; + var ic: c_int = 0; + if (stbi_info_from_memory(bytes.ptr, @intCast(bytes.len), &iw, &ih, &ic) != 1) return null; + if (@as(usize, @intCast(@max(0, iw))) * @as(usize, @intCast(@max(0, ih))) > @import("memory.zig").limits.image_decode_pixels) return null; var img = zstbi.Image.loadFromMemory(bytes, 4) catch return null; // 4 = RGBA defer img.deinit(); var scaled: ?zstbi.Image = null; diff --git a/src/locations.zig b/src/locations.zig index 2828566d..1e4a20cf 100644 --- a/src/locations.zig +++ b/src/locations.zig @@ -217,6 +217,98 @@ pub fn treeContinuation(line: []const u8, buffer: []u8, max_cells: usize) []cons return out.buffered()[0..end]; } +const Resolved = struct { code: []const u8 = "", colors: []const u8 = &.{}, source_row: usize = 0 }; + +/// Each Callstack row's code (its call site's line, or a caller's header) and +/// colors, by input line. A page spans thousands of files, so they are taken +/// a file at a time: grouped by path, each file read, line-indexed and +/// analyzed once, its rows' code and colors copied out, and the file let go +/// before the next. Row by row, the cache compared the whole source each +/// time and past its 64 entries parsed it again, every lookup walked the +/// file from its top, and every source stayed in the arena to the end. +fn resolveCallstack(p: *pardes.Pardes, arena: std.mem.Allocator, dir: []const u8, input: []const u8) ![]Resolved { + const mark = @import("lsp/lsp.zig").callstack_match; + var all: std.ArrayList([]const u8) = .empty; + var by_path: std.StringArrayHashMapUnmanaged(std.ArrayList(u32)) = .empty; + var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, input, "\n"), '\n'); + while (lines.next()) |raw| { + const line = if (std.mem.startsWith(u8, raw, mark)) raw[mark.len..] else raw; + const index: u32 = @intCast(all.items.len); + try all.append(arena, line); + const target = parseRaw(line[treePrefix(line).end..]); + if (target.at.line == 0) continue; + const entry = try by_path.getOrPut(arena, target.path); + if (!entry.found_existing) entry.value_ptr.* = .empty; + try entry.value_ptr.append(arena, index); + } + const resolved = try arena.alloc(Resolved, all.items.len); + @memset(resolved, .{}); + var file_arena: std.heap.ArenaAllocator = .init(p.gpa); + defer file_arena.deinit(); + for (by_path.keys(), by_path.values()) |path, indexes| { + _ = file_arena.reset(.retain_capacity); + const fa = file_arena.allocator(); + const source = sourceText(p, fa, dir, path); + var cached: Cache.Hit = .{ .analysis = .{} }; + defer cached.deinit(p.tree_sitter_gpa); + // Where each line starts, the file's length closing the last. + var starts: std.ArrayList(usize) = .empty; + if (source) |text| { + cached = p.locations_cache.get(p.tree_sitter_gpa, text.path, text.bytes, true, true) catch .{ .analysis = .{} }; + try starts.append(fa, 0); + var at: usize = 0; + while (std.mem.indexOfScalarPos(u8, text.bytes, at, '\n')) |nl| : (at = nl + 1) try starts.append(fa, nl + 1); + } + for (indexes.items) |index| { + const line = all.items[index]; + const prefix = treePrefix(line); + const target = parseRaw(line[prefix.end..]); + var code = line[prefix.end + target.code_start ..]; + var colors: []const u8 = &.{}; + var source_row = target.at.line - 1; + if (source) |text| { + const row = target.at.line - 1; + if (prefix.branch) { + // Choose the innermost header containing the server's name range. + var chosen: ?syntax.ContextDeclaration = null; + for (cached.analysis.declarations) |declaration| { + if (declaration.start_line <= row and row <= declaration.header_end_line) { + if (chosen == null or declaration.end_byte - declaration.start_byte < chosen.?.end_byte - chosen.?.start_byte) + chosen = declaration; + } + } + if (chosen) |header| { + code = text.bytes[header.start_byte..header.header_end_byte]; + source_row = header.start_line; + } else { + const fallback = indexedLine(text.bytes, starts.items, row); + if (fallback.len > 0) code = fallback; + } + } else if (code.len == 0) { + // A call site the language worker sent bare (it reads no + // sources for Callstack): its line, from the source here. + code = indexedLine(text.bytes, starts.items, row); + } + const offset = if (source_row < starts.items.len) starts.items[source_row] else text.bytes.len; + if (offset + code.len <= cached.analysis.colors.len and + std.mem.eql(u8, code, text.bytes[offset..][0..code.len])) + colors = cached.analysis.colors[offset..][0..code.len]; + code = try arena.dupe(u8, code); + colors = try arena.dupe(u8, colors); + } + resolved[index] = .{ .code = code, .colors = colors, .source_row = source_row }; + } + } + return resolved; +} + +/// modal.lineSlice through a line index (`starts`, as resolveCallstack builds it). +fn indexedLine(text: []const u8, starts: []const usize, row: usize) []const u8 { + if (row >= starts.len or starts[row] >= text.len) return ""; + const end = if (row + 1 < starts.len) starts[row + 1] - 1 else text.len; + return text[starts[row]..end]; +} + /// Enrich caller nodes on the UI thread, using the same source/declaration cache /// as LocationsContext. The LSP worker only supplies relationships and addresses. pub fn formatCallstack(p: *pardes.Pardes, dir: []const u8, input: []const u8) !Result { @@ -232,9 +324,10 @@ pub fn formatCallstack(p: *pardes.Pardes, dir: []const u8, input: []const u8) !R rows.deinit(p.gpa); } const stacked = p.settings.callstack_layout == .stacked; - var sources: std.StringHashMap(?Source) = .init(arena); + const resolved = try resolveCallstack(p, arena, dir, input); var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, input, "\n"), '\n'); - while (lines.next()) |raw| { + var index: usize = 0; + while (lines.next()) |raw| : (index += 1) { const mark = @import("lsp/lsp.zig").callstack_match; const focus = std.mem.startsWith(u8, raw, mark); const line = if (focus) raw[mark.len..] else raw; @@ -245,41 +338,9 @@ pub fn formatCallstack(p: *pardes.Pardes, dir: []const u8, input: []const u8) !R try appendMetadata(p.gpa, &rows, .{ .path = "", .at = .{}, .label = "", .code = "", .original = null }, .context, 0, line.len, false); continue; } - const entry = try sources.getOrPut(target.path); - if (!entry.found_existing) entry.value_ptr.* = sourceText(p, arena, dir, target.path); - const source = entry.value_ptr.*; - var cached: Cache.Hit = .{ .analysis = .{} }; - defer cached.deinit(p.tree_sitter_gpa); - if (source) |text| cached = p.locations_cache.get(p.tree_sitter_gpa, text.path, text.bytes, true, true) catch .{ .analysis = .{} }; - var code = line[prefix.end + target.code_start ..]; - var colors: []const u8 = &.{}; - var source_row = target.at.line - 1; - if (source) |text| { - const row = target.at.line - 1; - if (prefix.branch) { - // Choose the innermost header containing the server's name range. - var chosen: ?syntax.ContextDeclaration = null; - for (cached.analysis.declarations) |declaration| { - if (declaration.start_line <= row and row <= declaration.header_end_line) { - if (chosen == null or declaration.end_byte - declaration.start_byte < chosen.?.end_byte - chosen.?.start_byte) - chosen = declaration; - } - } - if (chosen) |header| { - code = text.bytes[header.start_byte..header.header_end_byte]; - source_row = header.start_line; - } else { - const fallback = @import("modal.zig").lineSlice(text.bytes, row); - if (fallback.len > 0) code = fallback; - } - } - { - const offset = @import("modal.zig").lineStartOffset(text.bytes, source_row); - if (offset + code.len <= cached.analysis.colors.len and - std.mem.eql(u8, code, text.bytes[offset..][0..code.len])) - colors = cached.analysis.colors[offset..][0..code.len]; - } - } + const code = resolved[index].code; + const colors = resolved[index].colors; + var source_row = resolved[index].source_row; const recursion = prefix.branch and std.mem.endsWith(u8, line, " ↻ recursion"); const first_line = code[0 .. std.mem.indexOfScalar(u8, code, '\n') orelse code.len]; const source_indent = if (stacked) first_line.len - std.mem.trimStart(u8, first_line, " \t").len else 0; diff --git a/src/look.zig b/src/look.zig index f4fbe52e..02754fff 100644 --- a/src/look.zig +++ b/src/look.zig @@ -587,6 +587,10 @@ fn lookFirstHit(p: *Pardes, id: usize) void { /// Fills the results buffer, and answers how many rows a text or PDF /// search found (0 for Find and Grep, which do not count). With /// `open_empty` false a text search that found nothing opens no buffer. +/// A search of one pane's text (or its PDF) writes at most this many bytes +/// of rows: past it, the rows stop and say where. +pub const search_text_output_bytes = 16 << 20; + pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start: SearchStart, open_empty: bool) !usize { const pane = p.panes[id] orelse return 0; // Blanks at either end are the pattern's (a look of an indented line); @@ -598,7 +602,9 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start // root, and the directory the results buffer is named in. From a // column's or the workspace's tag, the session's. const dir = if (p.exec_header) p.sessionDir() else Pardes.paneDir(pane); - const out = try arena.alloc(u8, filesystem.search_max_output_bytes); + // As much as the search can write and no more: a root's hits for each + // root Grep walks, one for Find, `search_text_output_bytes` in a pane. + var out: []u8 = &.{}; var out_len: usize = 0; var nrows: usize = 0; var anchor: ?usize = null; @@ -631,6 +637,7 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start roots[nroots] = d; nroots += 1; } + out = try @import("memory.zig").unfilled(arena, @max(1, nroots) * filesystem.search_root_output_bytes); // A pane's directory that is not there (a scratch named into one // not made yet, a peer's) has nothing to grep: passed over, not the // search's failure. @@ -641,9 +648,11 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start }; nrows = std.mem.count(u8, out[0..out_len], "\n"); } else if (kind == .find) { + out = try @import("memory.zig").unfilled(arena, filesystem.search_root_output_bytes); out_len = try filesystem.find(arena, dir, pat, out, ¬es); nrows = std.mem.count(u8, out[0..out_len], "\n"); } else if (pane.hasPdf()) { + out = try @import("memory.zig").unfilled(arena, search_text_output_bytes); if (comptime pdf_enabled) { const found = try panes.Pdf.searchRows( &pane.pdf.?, @@ -658,6 +667,7 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start anchor = found.anchor; } } else { + out = try @import("memory.zig").unfilled(arena, search_text_output_bytes); const lines = try edit.paneCursorLines(p, &pane.body); // a real file names itself; a terminal or an output buffer has no path const has_path = if (pane.file) |f| f.output == null else false; @@ -675,7 +685,10 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, kind: Search, start const row = try std.fmt.allocPrint(arena, "{s}:{d}:{d}{c}{d} {s}\n", .{ loc, i + 1, at + 1, config.range_sep, at + pat.len, std.mem.trimEnd(u8, ln, " \t"), }); - if (row.len > out.len - out_len) break; + if (row.len > out.len - out_len) { + notes.rows_cut = nrows; + break; + } if (start == .cursor and (i < cl or (i == cl and at <= cc))) anchor = nrows; @memcpy(out[out_len..][0..row.len], row); out_len += row.len; @@ -1451,6 +1464,7 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text: // 9P is no keyboard input, and searches whatever the key mode. if (pane.image != null or (pane.body.mode == .tty and !p.fs.serving)) return; if (text.len == 0) return; + if (lookCommit(p, id, pane, trimmed)) return; if (p.settings.look_word == .search and pane.file != null) return lookWord(p, id, pane, text); p.word_look = true; defer p.word_look = false; @@ -1471,6 +1485,49 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text: } } +/// A commit hash (7 to 40 hex digits, a letter and a digit among them) +/// looked at inside a git repository: `git show` it, paged into a +Pager, +/// which stacks its hunks in a +Diff (ctl.fillPager); the command pane +/// goes when it succeeds (exec.commandDone). +// ponytail: a hex word that names no commit leaves git's error in a command pane, not a search; check the object first if that bites. +fn lookCommit(p: *Pardes, id: usize, pane: *Pane, word: []const u8) bool { + if (comptime !pardes.hosted) return false; + if (!isCommitHash(word)) return false; + var dir = filesystem.localPath(Pardes.paneDir(pane)) orelse return false; + while (true) { + var buf: [4096]u8 = undefined; + const dot_git = std.fmt.bufPrint(&buf, "{s}/.git", .{dir}) catch return false; + if (exec.kindOf(dot_git) != null) break; + dir = std.fs.path.dirname(dir) orelse return false; + } + var line: [64]u8 = undefined; + const dst = exec.execute(p, id, std.fmt.bufPrint(&line, "git show {s}", .{word}) catch return false) orelse return true; + if (p.panes[dst]) |c| c.command_pages = true; + return true; +} + +fn isCommitHash(word: []const u8) bool { + if (word.len < 7 or word.len > 40) return false; + var digit = false; + var letter = false; + for (word) |c| switch (c) { + '0'...'9' => digit = true, + 'a'...'f' => letter = true, + else => return false, + }; + return digit and letter; +} + +test "a commit hash is 7 to 40 lowercase hex digits with a letter and a digit" { + try std.testing.expect(isCommitHash("9bffa7041c")); + try std.testing.expect(isCommitHash("9bffa7041cd2e8a0b6b1f7c3e4d5a6b7c8d9e0f1")); + try std.testing.expect(!isCommitHash("9bffa7")); + try std.testing.expect(!isCommitHash("defaced")); + try std.testing.expect(!isCommitHash("1234567")); + try std.testing.expect(!isCommitHash("0x9bffa7041c")); + try std.testing.expect(!isCommitHash("9BFFA7041C")); +} + /// Opens (or finds) `path` as Look would, `id`'s own pane when it is empty, /// and selects what `expr` addresses there from its dot. An address that /// does not evaluate moves nothing and says why (acme: no jump). diff --git a/src/lsp/lsp.zig b/src/lsp/lsp.zig index 4a70efe5..1c1b57a2 100644 --- a/src/lsp/lsp.zig +++ b/src/lsp/lsp.zig @@ -26,6 +26,10 @@ pub const Kind = enum { }; pub const callstack_match = "@callstack-match "; +/// The last row of a Callstack page that stopped full: ` `, +/// the entry indices from the top the next page starts at (`3.0.17`), and +/// how many callers this page holds. +pub const callstack_more = "@callstack-more "; pub const CallstackCorners = enum { rounded, square }; pub const callstack_default_depth: u8 = 8; pub const callstack_max_depth: u8 = 64; @@ -46,6 +50,9 @@ pub const Req = struct { /// For `explain`: the query it narrates, read from `arg` (` /// `) by `explaining`; a definition when none was asked before. explains: Kind = .definition, + /// The fixed region `arena` allocates from, when it is one: a walk that + /// can grow (Callstack) reads how much is left and stops in time. + budget: ?*const std.heap.FixedBufferAllocator = null, }; pub const Doc = struct { path: []const u8, source: [:0]const u8 }; @@ -102,18 +109,18 @@ pub fn speaks(path: []const u8) bool { return false; } -pub fn query(gpa: std.mem.Allocator, arena: std.mem.Allocator, req: Req, out: *std.Io.Writer) !void { +pub fn query(io: std.Io, gpa: std.mem.Allocator, arena: std.mem.Allocator, req: Req, out: *std.Io.Writer) !void { if (req.kind == .status) { try out.print("backend: {s}\n", .{backend_name}); - inline for (backends) |b| try b.query(gpa, arena, req, out); + inline for (backends) |b| try b.query(io, gpa, arena, req, out); return; } inline for (backends) |b| { if (b.speaks(req.path) and b.supports.contains(req.kind)) - return b.query(gpa, arena, req, out); + return b.query(io, gpa, arena, req, out); } if (req.kind == .explain and backends.len > 0) - return backends[0].query(gpa, arena, req, out); + return backends[0].query(io, gpa, arena, req, out); // Nothing asked: said why, where an empty answer would read as nothing // found. inline for (backends) |b| if (b.speaks(req.path)) @@ -217,6 +224,6 @@ test "a question no backend answers for a file says why rather than find nothing var buf: [256]u8 = undefined; var out: std.Io.Writer = .fixed(&buf); // A file no server speaks for is answered, not left empty. - try query(std.testing.allocator, arena.allocator(), .{ .kind = .incoming_calls, .path = "/x/notes.txt", .source = "", .offset = 0 }, &out); + try query(std.testing.io, std.testing.allocator, arena.allocator(), .{ .kind = .incoming_calls, .path = "/x/notes.txt", .source = "", .offset = 0 }, &out); try std.testing.expectStringStartsWith(out.buffered(), "@none "); } diff --git a/src/lsp/lsp_client.zig b/src/lsp/lsp_client.zig index b396879b..e356c979 100644 --- a/src/lsp/lsp_client.zig +++ b/src/lsp/lsp_client.zig @@ -8,9 +8,10 @@ //! worker thread, and a language server costs tens of milliseconds to start //! and MINUTES to index a large workspace. So a server is spawned lazily on //! the first query that needs it, kept for the life of the editor, and each -//! spec gets at most one — `conns[i]` guards itself with a pthread mutex -//! because the gui shell detaches its workers and a superseded query can still -//! be inside `run` when the next arrives. +//! spec gets at most one — `conns[i]` guards itself with an `Io.Mutex` +//! because a canceled query can still be inside `run` when the next arrives. +//! Every wait is an `Io` cancelation point: a shell cancels the worker of a +//! query it no longer wants, and the worker stops there. //! //! ONE READER THREAD PER SERVER, and it is not optional. The first design //! pumped the socket only while a query waited, which works for a server that @@ -28,7 +29,8 @@ //! under a thread still polling it. //! //! Nothing here may wedge the editor: -//! - every write and every mailbox wait is bounded by a deadline, +//! - every write is bounded by a deadline, and every mailbox wait by a +//! deadline or, while the server narrates progress, by cancelation, //! - a query the server does not answer in time returns no rows and sends //! `$/cancelRequest`; the server is NOT killed for being busy (an indexing //! server is busy for minutes and the status row says so) — but three @@ -58,20 +60,10 @@ extern "c" fn access(path: [*:0]const u8, mode: c_int) c_int; extern "c" fn getenv(name: [*:0]const u8) ?[*:0]const u8; extern "c" fn usleep(usec: c_uint) c_int; extern "c" fn atexit(f: *const fn () callconv(.c) void) c_int; -extern "c" fn realpath(path: [*:0]const u8, resolved: [*]u8) ?[*:0]u8; // test-only libc (the seam's own tests build a real directory tree) extern "c" fn mkdtemp(template: [*:0]u8) ?[*:0]u8; extern "c" fn mkdir(path: [*:0]const u8, mode: libc.mode_t) c_int; extern "c" fn system(cmd: [*:0]const u8) c_int; -// pthread condattr surface, absent from std.c: what makes the mailbox waits -// tick on CLOCK_MONOTONIC (linux) or a relative timeout (darwin). -const pthread_condattr_t = extern struct { data: [8]u8 align(@alignOf(usize)) = @splat(0) }; -extern "c" fn pthread_condattr_init(attr: *pthread_condattr_t) c_int; -extern "c" fn pthread_condattr_setclock(attr: *pthread_condattr_t, clock: c_int) c_int; -extern "c" fn pthread_condattr_destroy(attr: *pthread_condattr_t) c_int; -extern "c" fn pthread_cond_init(cond: *libc.pthread_cond_t, attr: ?*const pthread_condattr_t) c_int; -extern "c" fn pthread_cond_timedwait_relative_np(cond: *libc.pthread_cond_t, mutex: *libc.pthread_mutex_t, reltime: *const libc.timespec) c_int; -const CLOCK_MONOTONIC: c_int = 1; // linux ABI; the setclock call is linux-only const X_OK: c_int = 1; const POLLIN: i16 = 0x001; @@ -182,21 +174,35 @@ fn specFor(path: []const u8) ?usize { return null; } -// Deadlines. Requests are bounded because tty.zig cancels-and-joins the -// previous worker on a new keypress, so the worst UI stall a wedged wait can -// cause is one req_ms. Timeouts do NOT kill the server — an indexing -// rust-analyzer legitimately sits on a `gd` for longer than anyone will wait, -// and the message row is already narrating why. +// Deadlines. A shell cancels-and-joins the previous worker on a new query, +// and its waits are cancelation points: so a request needs no deadline to +// keep the editor responsive, and waits for its answer. Past req_ms the +// message row says the server is still at it; only a server silent and idle +// (no $/progress) for wedge_ms has failed to answer. Timeouts do NOT kill the +// server — an indexing rust-analyzer legitimately sits on a `gd` for minutes. +// The handshake runs protected from cancelation, so it keeps its deadline. const init_ms = 8_000; // spawn + initialize handshake -const req_ms = 4_000; // one request/response round trip +const req_ms = 4_000; // a request past this is said to be still working +const wedge_ms = 300_000; // silent and idle this long: not answering (rust-analyzer takes ~1 min on `default`'s callers in agave) const diag_ms = 1_200; // wait for a publishDiagnostics push after didChange const reply_ms = 2_000; // our answers to server-to-client requests +const reply_queue_bytes = 64 << 10; // replies waiting for the socket (Conn.replies) +const parse_kept = 1 << 20; // what the reader's parse arena keeps between messages +const max_diag_files = 256; // files a server's pushed diagnostics are kept for +const max_diag_bytes = 32 << 20; // and their bytes const wedged_strikes = 3; // consecutive timeouts before a restart -const max_rows = 2000; +/// Rows one answer may hold, and its writer's bytes: carved from the query's +/// fixed region (memory.limits.arena.lsp_query) with the rest of its memory. +const max_rows = 100_000; +/// What a Callstack walk leaves of its query's region for rendering the +/// tree it found: past this it stops and says so. +const callstack_reserve = 32 << 20; +/// What rendering leaves of the answer's writer for its closing line. +const row_room = 4096; const max_doc_bytes = 8 << 20; -const Err = error{ Dead, Timeout, Protocol, OutOfMemory, NoServer, Backoff, WriteFailed }; +const Err = error{ Dead, Timeout, Protocol, OutOfMemory, NoServer, Backoff, WriteFailed, Canceled }; /// Long-lived state outlives every query arena and cannot borrow the caller's /// gpa (a different one shows up in the harness than in the shell), so @@ -251,8 +257,22 @@ const State = enum(u8) { }; const Conn = struct { - mu: libc.pthread_mutex_t = .{}, - cond: libc.pthread_cond_t = .{}, + mu: std.Io.Mutex = .init, + cond: std.Io.Condition = .init, + /// Frames go out whole: a query's requests and the reader's replies + /// share the socket, and interleaved halves are a parse error that ends + /// the server. + write_mu: std.Io.Mutex = .init, + /// Replies the reader made while a query's write held the socket, sent + /// by that writer once its own message is out (releaseWrite): the reader + /// never waits to write, since a server blocked on its output reads + /// nothing more of ours. + /// Two halves: the reader appends to `replies[filling]`, and the writer + /// flips them and sends the other, with no copy and no wait. + replies: [2][reply_queue_bytes]u8 = undefined, + replies_len: [2]usize = .{ 0, 0 }, + filling: u1 = 0, + replies_mu: std.Io.Mutex = .init, state: State = .off, /// bumped per spawn. A reader thread that sees a different gen than its /// own is reading a corpse and exits; a waiter that sees one stops waiting. @@ -264,9 +284,6 @@ const Conn = struct { /// monotonic ms when the last handshake completed — a crash shortly /// after "ready" counts as a handshake failure for backoff purposes ready_at_ms: i64 = 0, - /// linux: the zeroed condvar defaults to REALTIME; re-initialized with a - /// monotonic condattr before its first wait (under the mutex) - cond_monotonic: bool = false, timeouts: u8 = 0, pid: libc.pid_t = -1, sock: c_int = -1, @@ -278,6 +295,8 @@ const Conn = struct { extra_roots: std.ArrayList([]u8) = .empty, docs: std.ArrayList(Doc) = .empty, diags: std.ArrayList(DiagSet) = .empty, + /// The bytes `diags` holds, kept under max_diag_bytes. + diag_bytes: usize = 0, /// the response mailbox: one request outstanding per connection want_id: u32 = 0, resp: ?[]u8 = null, @@ -285,13 +304,12 @@ const Conn = struct { progress: i32 = 0, title: [48]u8 = @splat(0), title_len: u8 = 0, + /// The server says it is still loading its workspace (rust-analyzer's + /// serverStatus, not quiescent): an empty answer now is not one. + loading: bool = false, + /// its index in `conns`, for what it posts + si: usize = 0, - fn lock(c: *Conn) void { - _ = libc.pthread_mutex_lock(&c.mu); - } - fn unlock(c: *Conn) void { - _ = libc.pthread_mutex_unlock(&c.mu); - } fn alive(c: *const Conn) bool { return c.state == .starting or c.state == .ready; } @@ -406,10 +424,10 @@ const Trace = struct { // ------------------------------------------------------------------- query -pub fn query(gpa: std.mem.Allocator, arena: std.mem.Allocator, asked: lsp.Req, out: *std.Io.Writer) !void { +pub fn query(io: std.Io, gpa: std.mem.Allocator, arena: std.mem.Allocator, asked: lsp.Req, out: *std.Io.Writer) !void { _ = gpa; const req = lsp.explaining(asked); - if (req.kind == .status) return status(req, out); + if (req.kind == .status) return status(io, req, out); var tr: Trace = .{ .on = req.kind == .explain }; const si = specFor(req.path) orelse { @@ -421,13 +439,14 @@ pub fn query(gpa: std.mem.Allocator, arena: std.mem.Allocator, asked: lsp.Req, o }; tr.note("file {s} -> {s} (languageId {s})", .{ std.fs.path.basename(req.path), specs[si].name, specs[si].lang }); - const scratch_buf = try arena.alloc(u8, max_rows * 512); + // Raw: `alloc` fills a safe build's new memory, all 51 MB of it, per query. + const scratch_buf = (arena.rawAlloc(max_rows * 512, .of(u8), @returnAddress()) orelse return error.OutOfMemory)[0 .. max_rows * 512]; var scratch: std.Io.Writer = .fixed(scratch_buf); const t0 = nowUs(); var err_name: []const u8 = ""; var failure: ?anyerror = null; - answer(arena, si, req, &scratch, &tr) catch |e| { + answer(io, arena, si, req, &scratch, &tr) catch |e| { failure = e; err_name = @errorName(e); tr.note("ERROR: {s}", .{err_name}); @@ -443,9 +462,9 @@ pub fn query(gpa: std.mem.Allocator, arena: std.mem.Allocator, asked: lsp.Req, o // again, not that it is not there. if (failure) |err| if (err == error.Backoff) { const c = &conns[si]; - c.lock(); + c.mu.lockUncancelable(io); const left_ms = c.retry_after_ms -| nowMs(); - c.unlock(); + c.mu.unlock(io); return lsp.none(out, "{s} failed recently; retry in {d}s", .{ specs[si].name, @divFloor(left_ms + 999, 1000) }); }; if (failure) |err| return err; @@ -464,17 +483,34 @@ fn traceOut(tr: *const Trace, req: lsp.Req, out: *std.Io.Writer, rows: usize, us try out.print("\n{d} row(s) in {d}us\n", .{ rows, us }); } -fn answer(arena: std.mem.Allocator, si: usize, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) Err!void { +fn answer(io: std.Io, arena: std.mem.Allocator, si: usize, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) Err!void { const c = &conns[si]; - c.lock(); - defer c.unlock(); - const g = try ensure(c, si, arena, req, tr); - run(c, si, arena, req, out, tr) catch |e| { + try c.mu.lock(io); + defer c.mu.unlock(io); + const g = try ensure(c, io, si, arena, req, tr); + const before = out.end; + try attempt(c, io, si, arena, req, out, tr, g); + // A server still loading its workspace answers at once, with nothing + // (rust-analyzer before its index): that is no answer. Wait until it says + // it is loaded, the message row saying so, and ask again. + const answered = out.buffered()[before..]; + if (c.loading and c.gen == g and (answered.len == 0 or std.mem.startsWith(u8, answered, "@none "))) { + tr.note("{s} is still loading: waiting for it, then asking again", .{specs[si].name}); + post(si, .always, "{s} is still loading the workspace; the answer comes when it is done\u{2026}", .{specs[si].name}); + while (c.loading and c.gen == g and c.alive()) _ = try timedWait(c, io, nowMs() + 500); + out.end = before; + try attempt(c, io, si, arena, req, out, tr, g); + } +} + +/// One run of a query, and what its failure says of the server. +fn attempt(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer, tr: *Trace, g: u32) Err!void { + run(c, io, si, arena, req, out, tr) catch |e| { switch (e) { // transport-level: this server is gone; forget it, and the next // query respawns. Gen-checked so a respawn that happened while we // waited is not the one we kill. - error.Dead, error.Protocol => shutdownIf(c, g), + error.Dead, error.Protocol => shutdownIf(c, io, g), error.Timeout => { // Slow is only wedged when the server is IDLE. One with // active `$/progress` work (rust-analyzer running cargo @@ -487,18 +523,19 @@ fn answer(arena: std.mem.Allocator, si: usize, req: lsp.Req, out: *std.Io.Writer c.timeouts +|= 1; if (c.timeouts >= wedged_strikes and c.gen == g) { post(si, .always, "{s} not answering — restarting", .{specs[si].name}); - shutdownIf(c, g); + shutdownIf(c, io, g); } } }, - error.OutOfMemory, error.NoServer, error.Backoff, error.WriteFailed => {}, + // Canceled: the shell asked something newer, not a wedged server. + error.OutOfMemory, error.NoServer, error.Backoff, error.WriteFailed, error.Canceled => {}, } return e; }; c.timeouts = 0; } -fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) Err!void { +fn run(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io.Writer, tr: *Trace) Err!void { // `explain` narrates the last query asked (a definition, `gd`, when // none was) — dispatch below on the effective kind so the trace // follows the code that query really runs. @@ -510,18 +547,18 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io var uri: std.ArrayList(u8) = .empty; try uriOf(&uri, arena, req.path); - try syncDoc(c, si, arena, uri.items, req.source); + try syncDoc(c, io, si, arena, uri.items, req.source); // Every other open file this server answers for, before a query whose // answer reaches them: zls renames only in the documents it has. if (lsp.reachesOtherFiles(kind)) for (req.others) |doc| if (specFor(doc.path) == si and !std.mem.eql(u8, doc.path, req.path)) { var other: std.ArrayList(u8) = .empty; try uriOf(&other, arena, doc.path); - try syncDoc(c, si, arena, other.items, doc.source); + try syncDoc(c, io, si, arena, other.items, doc.source); tr.note("synced {s} first", .{std.fs.path.basename(doc.path)}); }; const pos = posOf(req.source, req.offset, c.caps.enc); - var cx: Cx = .{ .arena = arena, .base = req.root, .cur_path = req.path, .cur_src = req.source, .out = out, .relative_parents = req.kind == .callstack, .callstack_corners = req.callstack_corners }; + var cx: Cx = .{ .arena = arena, .base = req.root, .cur_path = req.path, .cur_src = req.source, .out = out, .fixed_out = true, .relative_parents = req.kind == .callstack, .callstack_corners = req.callstack_corners }; for (req.others) |doc| try cx.files.append(arena, .{ .path = doc.path, .text = doc.source }); tr.note("server {s} (pid {d}), root {s}, {s} columns", .{ @tagName(c.state), c.pid, c.root, @tagName(c.caps.enc), @@ -540,7 +577,7 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io var b = try atPos(arena, uri.items, pos); if (kind == .references) try app(&b, arena, ",\"context\":{\"includeDeclaration\":true}"); tr.note("-> {s} @ {d}:{d}", .{ method, pos.line + 1, pos.ch + 1 }); - const result = (try call(c, arena, method, b.items, deadline)) orelse { + const result = (try call(c, io, arena, method, b.items, deadline)) orelse { tr.note("<- empty (no result, an error response, or null)", .{}); return; }; @@ -549,12 +586,12 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io }, .select_refs => { const b = try atPos(arena, uri.items, pos); - const result = (try call(c, arena, "textDocument/documentHighlight", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/documentHighlight", b.items, deadline)) orelse return; for (items(result)) |h| try emitRange(&cx, c.caps.enc, uri.items, get(h, "range"), ""); }, .hover => { const b = try atPos(arena, uri.items, pos); - const result = (try call(c, arena, "textDocument/hover", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/hover", b.items, deadline)) orelse return; const contents = get(result, "contents") orelse return; const text = str(contents) orelse str(get(contents, "value")) orelse blk: { for (items(contents)) |m| if (str(m) orelse str(get(m, "value"))) |t| break :blk t; @@ -569,26 +606,26 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io try app(&b, arena, "\"textDocument\":{\"uri\":"); try jstr(&b, arena, uri.items); try app(&b, arena, "}"); - const result = (try call(c, arena, "textDocument/documentSymbol", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/documentSymbol", b.items, deadline)) orelse return; try walkSymbols(&cx, c.caps.enc, uri.items, result, 0); }, .workspace_symbols => { var b: std.ArrayList(u8) = .empty; try app(&b, arena, "\"query\":"); try jstr(&b, arena, req.arg); - const result = (try call(c, arena, "workspace/symbol", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "workspace/symbol", b.items, deadline)) orelse return; for (items(result)) |sym| { const loc = get(sym, "location") orelse continue; try emitRange(&cx, c.caps.enc, str(get(loc, "uri")) orelse continue, get(loc, "range"), str(get(sym, "name")) orelse ""); } }, - .diagnostics => try diagnostics(c, arena, &cx, uri.items, deadline), - .workspace_diagnostics => try workspaceDiagnostics(c, arena, &cx, deadline), + .diagnostics => try diagnostics(c, io, arena, &cx, uri.items, deadline), + .workspace_diagnostics => try workspaceDiagnostics(c, io, arena, &cx, deadline), .rename => { var b = try atPos(arena, uri.items, pos); try app(&b, arena, ",\"newName\":"); try jstr(&b, arena, req.arg); - const result = (try call(c, arena, "textDocument/rename", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/rename", b.items, deadline)) orelse return; // Other open files that say the old name, should the server // answer for this file alone (zls renaming at a declaration does, // whatever it was told): applied here, they would no longer build. @@ -603,7 +640,7 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io try app(&b, arena, "\"textDocument\":{\"uri\":"); try jstr(&b, arena, uri.items); try app(&b, arena, "},\"options\":{\"tabSize\":4,\"insertSpaces\":true}"); - const result = (try call(c, arena, "textDocument/formatting", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/formatting", b.items, deadline)) orelse return; try formatEdits(&cx, c.caps.enc, result, req.source); }, .code_action => { @@ -611,7 +648,7 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io try app(&b, arena, "\"textDocument\":{\"uri\":"); try jstr(&b, arena, uri.items); try b.print(arena, "}},\"range\":{{\"start\":{{\"line\":{d},\"character\":{d}}},\"end\":{{\"line\":{d},\"character\":{d}}}}},\"context\":{{\"diagnostics\":[]}}", .{ pos.line, pos.ch, pos.line, pos.ch }); - const result = (try call(c, arena, "textDocument/codeAction", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/codeAction", b.items, deadline)) orelse return; for (items(result)) |ca| { const title = str(get(ca, "title")) orelse continue; try lsp.row(cx.out, lsp.rel(cx.base, cx.cur_path), pos.line, 0, flat(arena, title)); @@ -621,7 +658,7 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io .completion => { var b = try atPos(arena, uri.items, pos); try app(&b, arena, ",\"context\":{\"triggerKind\":1}"); - const result = (try call(c, arena, "textDocument/completion", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/completion", b.items, deadline)) orelse return; const list = if (get(result, "items")) |it| items(it) else items(result); const here = lsp.rel(cx.base, cx.cur_path); var n: usize = 0; @@ -643,11 +680,11 @@ fn run(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, out: *std.Io n += 1; } }, - .callstack => try callstack(c, si, arena, &cx, uri.items, pos, deadline, tr, req.callstack_depth), - .incoming_calls => try hierarchy(c, si, arena, &cx, uri.items, pos, deadline, .incoming, tr), - .outgoing_calls => try hierarchy(c, si, arena, &cx, uri.items, pos, deadline, .outgoing, tr), - .supertypes => try hierarchy(c, si, arena, &cx, uri.items, pos, deadline, .supers, tr), - .subtypes => try hierarchy(c, si, arena, &cx, uri.items, pos, deadline, .subs, tr), + .callstack => try callstack(c, io, si, arena, &cx, uri.items, pos, deadline, tr, req.callstack_depth, req.budget, req.arg), + .incoming_calls => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .incoming, tr), + .outgoing_calls => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .outgoing, tr), + .supertypes => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .supers, tr), + .subtypes => try hierarchy(c, io, si, arena, &cx, uri.items, pos, deadline, .subs, tr), .status, .explain => unreachable, } } @@ -687,13 +724,13 @@ fn walkSymbols(cx: *Cx, enc: Enc, uri: []const u8, node: std.json.Value, depth: /// Pull when the server does (LSP 3.17), the push store otherwise. The store /// path waits briefly for a publish that postdates the didChange we just /// sent, so `]d` right after an edit sees the new truth, not the old one. -fn diagnostics(c: *Conn, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, deadline: i64) Err!void { +fn diagnostics(c: *Conn, io: std.Io, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, deadline: i64) Err!void { if (c.caps.pull) { var b: std.ArrayList(u8) = .empty; try app(&b, arena, "\"textDocument\":{\"uri\":"); try jstr(&b, arena, uri); try app(&b, arena, "}"); - const result = (try call(c, arena, "textDocument/diagnostic", b.items, deadline)) orelse return; + const result = (try call(c, io, arena, "textDocument/diagnostic", b.items, deadline)) orelse return; for (items(get(result, "items"))) |dg| try emitDiag(cx, c.caps.enc, uri, dg, arena); return; } @@ -702,13 +739,13 @@ fn diagnostics(c: *Conn, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, dea stale = d.stale; break; }; - if (stale) waitFresh(c, uri, nowMs() + diag_ms); + if (stale) try waitFresh(c, io, uri, nowMs() + diag_ms); try renderStore(c, arena, cx, uri); } -fn workspaceDiagnostics(c: *Conn, arena: std.mem.Allocator, cx: *Cx, deadline: i64) Err!void { +fn workspaceDiagnostics(c: *Conn, io: std.Io, arena: std.mem.Allocator, cx: *Cx, deadline: i64) Err!void { if (c.caps.pull_workspace) { - const result = (try call(c, arena, "workspace/diagnostic", "\"previousResultIds\":[]", deadline)) orelse return; + const result = (try call(c, io, arena, "workspace/diagnostic", "\"previousResultIds\":[]", deadline)) orelse return; for (items(get(result, "items"))) |per| { const uri = str(get(per, "uri")) orelse continue; for (items(get(per, "items"))) |dg| try emitDiag(cx, c.caps.enc, uri, dg, arena); @@ -741,7 +778,7 @@ fn renderStore(c: *Conn, arena: std.mem.Allocator, cx: *Cx, only_uri: ?[]const u /// Block (mutex released) until the reader marks `uri` fresh or the deadline /// passes. The reader broadcasts on every publishDiagnostics. -fn waitFresh(c: *Conn, uri: []const u8, deadline: i64) void { +fn waitFresh(c: *Conn, io: std.Io, uri: []const u8, deadline: i64) error{Canceled}!void { const g = c.gen; while (c.gen == g and c.alive()) { var fresh = false; @@ -750,7 +787,7 @@ fn waitFresh(c: *Conn, uri: []const u8, deadline: i64) void { break; }; if (fresh) return; - if (!timedWait(c, deadline)) return; + if (!try timedWait(c, io, deadline)) return; } } @@ -873,18 +910,21 @@ fn sortEdits(edits: []PutEdit) void { /// A bounded static hierarchy. Reuse the prepared item verbatim (including /// server data), and retain every call-site range rather than just a declaration. -fn hierarchyResult(c: *Conn, arena: std.mem.Allocator, item: std.json.Value, method: []const u8, deadline: i64) Err!?std.json.Value { +fn hierarchyResult(c: *Conn, io: std.Io, arena: std.mem.Allocator, item: std.json.Value, method: []const u8, deadline: i64) Err!?std.json.Value { if (jsonDepth(item, 0) > 96) return null; var body: std.ArrayList(u8) = .empty; try app(&body, arena, "\"item\":"); try app(&body, arena, std.json.Stringify.valueAlloc(arena, item, .{}) catch return error.OutOfMemory); - return call(c, arena, method, body.items, deadline); + return call(c, io, arena, method, body.items, deadline); } const CallTree = struct { - const Site = struct { range: std.json.Value, focus: bool }; + /// What a node keeps of the server's item: its own copies, so the + /// response it came in is freed once its subtree is walked. + const Call = struct { uri: []const u8, name: []const u8, at: Range }; + const Site = struct { range: Range, focus: bool }; const Node = struct { - item: std.json.Value, + call: Call, ranges: std.ArrayList(Site) = .empty, children: std.ArrayList(usize) = .empty, cycle: bool = false, @@ -893,10 +933,39 @@ const CallTree = struct { roots: std.ArrayList(usize) = .empty, path: [lsp.callstack_max_depth]std.json.Value = undefined, depth_limit: usize = lsp.callstack_default_depth, - visited: usize = 0, limited: bool = false, + out_of_time: bool = false, + out_of_memory: bool = false, + budget: ?*const std.heap.FixedBufferAllocator = null, + si: usize = 0, + collected: usize = 0, + started_ms: i64 = 0, + narrated: bool = false, siblings: [lsp.callstack_max_depth]bool = @splat(false), rendered: usize = 0, + /// Paging. A page starts at `start`, a path of entry indices from the + /// top (empty: the start), skipping what is before it at each level; + /// `rows` and `bytes` count what rendering takes, and the walk stops + /// before their caps at `cut`, which the next page starts at (`more`). + /// The ancestors on the path are shown again on it, as context. + start: [lsp.callstack_max_depth]u32 = undefined, + start_len: usize = 0, + at: [lsp.callstack_max_depth]u32 = undefined, + cut: [lsp.callstack_max_depth]u32 = undefined, + cut_len: usize = 0, + more: bool = false, + rows: usize = 0, + row_cap: usize = max_rows - 16, + /// The bytes those rows take, over-estimated (the uri for the path it + /// becomes), kept under the answer writer's room. + bytes: usize = 0, + byte_cap: usize = std.math.maxInt(usize), + + /// A row of a caller at `depth`: its tree columns, the uri the path is + /// made from, the name, and room for the address. + fn rowBytes(depth: usize, caller: Call) usize { + return 5 * (depth + 2) + caller.uri.len + caller.name.len + 40; + } /// Incoming paths arrive nearest-first. Insert them outermost-first, /// sharing common caller prefixes and retaining all their call sites. @@ -909,11 +978,14 @@ const CallTree = struct { const item = get(entry, "from").?; const children = if (parent) |id| tree.nodes.items[id].children.items else tree.roots.items; const found = for (children) |id| { - if (sameCall(tree.nodes.items[id].item, item)) break id; + if (sameCall(tree.nodes.items[id].call, item)) break id; } else null; + const depth = path.len - 1 - at; const id = found orelse blk: { const id = tree.nodes.items.len; - try tree.nodes.append(arena, .{ .item = item }); + try tree.nodes.append(arena, .{ .call = try callOf(arena, item) }); + tree.rows += 1; + tree.bytes += rowBytes(depth, tree.nodes.items[id].call); if (parent) |pid| { try tree.nodes.items[pid].children.append(arena, id); } else try tree.roots.append(arena, id); @@ -924,23 +996,39 @@ const CallTree = struct { for (items(get(entry, "fromRanges"))) |range| { const parsed = rangeOf(range) orelse continue; for (node.ranges.items) |*other| { - if (std.meta.eql(parsed, rangeOf(other.range).?)) { + if (std.meta.eql(parsed, other.range)) { other.focus = other.focus or at == 0; break; } - } else try node.ranges.append(arena, .{ .range = range, .focus = at == 0 }); + } else { + try node.ranges.append(arena, .{ .range = parsed, .focus = at == 0 }); + tree.rows += 1; + tree.bytes += rowBytes(depth + 1, .{ .uri = node.call.uri, .name = "", .at = parsed }); + } } parent = id; } } }; -fn sameCall(a: std.json.Value, b: std.json.Value) bool { - const au = str(get(a, "uri")) orelse return false; +fn callOf(arena: std.mem.Allocator, item: std.json.Value) Err!CallTree.Call { + return .{ + .uri = try arena.dupe(u8, str(get(item, "uri")).?), + .name = try arena.dupe(u8, str(get(item, "name")) orelse "(unnamed)"), + .at = rangeOf(get(item, "selectionRange") orelse get(item, "range")).?, + }; +} + +fn sameCall(a: CallTree.Call, b: std.json.Value) bool { const bu = str(get(b, "uri")) orelse return false; - const ar = rangeOf(get(a, "selectionRange") orelse get(a, "range")) orelse return false; const br = rangeOf(get(b, "selectionRange") orelse get(b, "range")) orelse return false; - return std.mem.eql(u8, au, bu) and std.meta.eql(ar, br); + return std.mem.eql(u8, a.uri, bu) and std.meta.eql(a.at, br); +} + +fn sameItem(a: std.json.Value, b: std.json.Value) bool { + const au = str(get(a, "uri")) orelse return false; + const ar = rangeOf(get(a, "selectionRange") orelse get(a, "range")) orelse return false; + return sameCall(.{ .uri = au, .name = "", .at = ar }, b); } fn callPrefix(out: *std.Io.Writer, tree: *const CallTree, depth: usize) Err!void { @@ -954,44 +1042,115 @@ fn validCaller(entry: std.json.Value) bool { rangeOf(get(from, "selectionRange") orelse get(from, "range")) != null; } -fn callstack(c: *Conn, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, tr: *Trace, max_depth: u8) Err!void { +fn callstack(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, tr: *Trace, max_depth: u8, budget: ?*const std.heap.FixedBufferAllocator, arg: []const u8) Err!void { if (!c.caps.call_hier) return lsp.none(cx.out, "{s} does not answer call hierarchy (no callHierarchyProvider)", .{specs[si].name}); const b = try atPos(arena, uri, pos); - const prepared = (try call(c, arena, "textDocument/prepareCallHierarchy", b.items, deadline)) orelse return; + const prepared = (try call(c, io, arena, "textDocument/prepareCallHierarchy", b.items, deadline)) orelse return; if (items(prepared).len == 0) return lsp.none(cx.out, "no function at this position", .{}); + // The rows come from the tree alone: the core reads the sources. + cx.no_text = true; + // Each response is parsed into its own part of the region, freed once + // its subtree is walked; only the path being walked is live JSON. + // Raw, as query()'s scratch: `alloc` would fill all ~100 MB of it. + const parse_len = if (budget) |fixed| (fixed.buffer.len - fixed.end_index) / 2 else 0; + var parse_fba: std.heap.FixedBufferAllocator = .init(if (budget != null) + (arena.rawAlloc(parse_len, .of(u8), @returnAddress()) orelse return error.OutOfMemory)[0..parse_len] + else + &.{}); + const parse = if (budget != null) parse_fba.allocator() else arena; for (items(prepared)) |item| { - var tree: CallTree = .{ .depth_limit = std.math.clamp(max_depth, 1, lsp.callstack_max_depth) }; - const incoming = try hierarchyResult(c, arena, item, "callHierarchy/incomingCalls", deadline); - const count = try collectCallers(c, arena, item, incoming, deadline, &tree, 0); - if (count == 0) try cx.out.writeAll("No callers reported\n"); + var tree: CallTree = .{ + .depth_limit = std.math.clamp(max_depth, 1, lsp.callstack_max_depth), + .si = si, + .started_ms = nowMs(), + .budget = budget, + // The page ends while the answer's writer has room for the rest. + .byte_cap = if (cx.fixed_out) (cx.out.buffer.len - cx.out.end) -| (1 << 20) else std.math.maxInt(usize), + }; + var steps = std.mem.tokenizeScalar(u8, std.mem.trim(u8, arg, " \n"), '.'); + while (steps.next()) |step| { + if (tree.start_len == tree.start.len) break; + tree.start[tree.start_len] = std.fmt.parseInt(u32, step, 10) catch break; + tree.start_len += 1; + } + const incoming = try hierarchyResult(c, io, parse, item, "callHierarchy/incomingCalls", deadline); + const count = try collectCallers(c, io, arena, if (budget != null) &parse_fba else null, item, incoming, &tree, 0, tree.start_len > 0); + if (tree.narrated) post(si, .always, "Callstack: {d} callers", .{tree.collected}); + if (count == 0 and tree.start_len == 0) try cx.out.writeAll("No callers reported\n"); try renderCallers(cx, c.caps.enc, &tree, tree.roots.items, 0); - if (tree.limited) try cx.out.writeAll("… continue from a function above with Callstack\n"); + if (tree.more) { + try cx.out.writeAll(lsp.callstack_more); + for (tree.cut[0..tree.cut_len], 0..) |index, level| try cx.out.print("{s}{d}", .{ if (level == 0) "" else ".", index }); + try cx.out.print(" {d}\n", .{tree.collected}); + } else if (tree.out_of_time) { + try cx.out.writeAll("… the language server ran out of time; continue from a function above with Callstack\n"); + } else if (tree.out_of_memory) { + try cx.out.writeAll("… stopped at the query's memory limit; continue from a function above with Callstack\n"); + } else if (tree.limited) try cx.out.writeAll("… continue from a function above with Callstack\n"); tr.note("callstack: {d} callers", .{tree.rendered}); } } -fn collectCallers(c: *Conn, arena: std.mem.Allocator, focus: std.json.Value, incoming: ?std.json.Value, deadline: i64, tree: *CallTree, depth: usize) Err!usize { +/// No caller count and no overall deadline: the walk narrates itself on the +/// message row after a second, and it stops when a request goes unanswered +/// (what was collected is shown), when the page is full (the rest is the +/// next page), or when the shell cancels it for a newer query. +fn collectCallers(c: *Conn, io: std.Io, arena: std.mem.Allocator, parse: ?*std.heap.FixedBufferAllocator, focus: std.json.Value, incoming: ?std.json.Value, tree: *CallTree, depth: usize, on_path: bool) Err!usize { var count: usize = 0; - for (items(incoming)) |entry| { - if (tree.visited >= 64) { - tree.limited = true; - break; + for (items(incoming), 0..) |entry, index| { + // A later page skips what the pages before it walked. + const resuming = on_path and depth < tree.start_len; + if (resuming and index < tree.start[depth]) continue; + tree.at[depth] = @intCast(index); + if (tree.budget) |b| if (b.buffer.len - b.end_index < callstack_reserve) { + tree.out_of_memory = true; + }; + if (!tree.more and (tree.rows >= tree.row_cap or tree.bytes >= tree.byte_cap or tree.out_of_memory)) { + // The page is full: the next goes on here. Never where this + // one began, which would page in place: past that entry. + tree.more = true; + tree.cut_len = depth + 1; + @memcpy(tree.cut[0..tree.cut_len], tree.at[0..tree.cut_len]); + if (tree.cut_len == tree.start_len and std.mem.eql(u32, tree.cut[0..tree.cut_len], tree.start[0..tree.start_len])) + tree.cut[depth] += 1; } + if (tree.out_of_time or tree.more) break; if (!validCaller(entry)) continue; const from = get(entry, "from").?; - const cycle = sameCall(focus, from) or for (tree.path[0..depth]) |ancestor| { - if (sameCall(get(ancestor, "from").?, from)) break true; + const cycle = sameItem(focus, from) or for (tree.path[0..depth]) |ancestor| { + if (sameItem(get(ancestor, "from").?, from)) break true; } else false; tree.path[depth] = entry; - tree.visited += 1; count += 1; + tree.collected += 1; + if (nowMs() - tree.started_ms >= 1000) { + tree.narrated = true; + post(tree.si, .chatty, "Callstack: {d} callers\u{2026}", .{tree.collected}); + } var children: usize = 0; if (!cycle) { - if (depth + 1 == tree.depth_limit or tree.visited >= 64) { + if (depth + 1 == tree.depth_limit) { tree.limited = true; } else { - const ancestors = try hierarchyResult(c, arena, from, "callHierarchy/incomingCalls", deadline); - children = try collectCallers(c, arena, focus, ancestors, deadline, tree, depth + 1); + const mark = if (parse) |fixed| fixed.end_index else 0; + defer if (parse) |fixed| { + fixed.end_index = mark; + }; + const ancestors = hierarchyResult(c, io, if (parse) |fixed| fixed.allocator() else arena, from, "callHierarchy/incomingCalls", nowMs() + req_ms) catch |e| switch (e) { + error.Timeout => blk: { + tree.out_of_time = true; + break :blk null; + }, + // A response bigger than the parse region: this caller + // stops here, the page with it. + error.OutOfMemory => blk: { + tree.out_of_memory = true; + break :blk null; + }, + else => return e, + }; + const deeper = resuming and index == tree.start[depth] and depth + 1 < tree.start_len; + if (!tree.out_of_time and !tree.out_of_memory) children = try collectCallers(c, io, arena, parse, focus, ancestors, tree, depth + 1, deeper); } } if (children == 0) try tree.addPath(arena, tree.path[0 .. depth + 1], cycle); @@ -999,51 +1158,61 @@ fn collectCallers(c: *Conn, arena: std.mem.Allocator, focus: std.json.Value, inc return count; } +/// Test callers sink below the rest; each group keeps the usual order. +// ponytail: substring heuristic, "latest.zig" or "contest" count as tests too +fn testCaller(caller: CallTree.Call) bool { + return std.ascii.findIgnoreCase(caller.name, "test") != null or + std.ascii.findIgnoreCase(std.fs.path.basenamePosix(caller.uri), "test") != null; +} + fn callerLess(tree: *const CallTree, a: usize, b: usize) bool { - const left = tree.nodes.items[a].item; - const right = tree.nodes.items[b].item; - const uri_order = std.mem.order(u8, str(get(left, "uri")).?, str(get(right, "uri")).?); + const left = tree.nodes.items[a].call; + const right = tree.nodes.items[b].call; + if (testCaller(left) != testCaller(right)) return testCaller(right); + const uri_order = std.mem.order(u8, left.uri, right.uri); if (uri_order != .eq) return uri_order == .lt; - return callRangeLess({}, get(left, "selectionRange") orelse get(left, "range").?, get(right, "selectionRange") orelse get(right, "range").?); + return rangeLess(left.at, right.at); } -fn callRangeLess(_: void, a: std.json.Value, b: std.json.Value) bool { - const left = rangeOf(a).?; - const right = rangeOf(b).?; +fn rangeLess(left: Range, right: Range) bool { return left.sl < right.sl or (left.sl == right.sl and left.sc < right.sc); } fn renderCallers(cx: *Cx, enc: Enc, tree: *CallTree, children: []usize, depth: usize) Err!void { std.mem.sort(usize, children, @as(*const CallTree, tree), callerLess); for (children, 0..) |id, index| { - if (tree.rendered >= 64) { + // emitRange's row ceiling and the writer's room, met here before a + // prefix is half written + if (cx.rows >= max_rows or (cx.fixed_out and cx.out.buffer.len - cx.out.end < row_room)) { tree.limited = true; return; } const node = &tree.nodes.items[id]; - const item = node.item; - const uri = str(get(item, "uri")).?; const more = index + 1 < children.len; try callPrefix(cx.out, tree, depth); const has_children = node.children.items.len > 0 or node.ranges.items.len > 0; const rounded = cx.callstack_corners == .rounded; try cx.out.writeAll(if (more) "├" else if (rounded) "╰" else "└"); try cx.out.writeAll(if (has_children) "──┬ " else "─── "); - const name = flat(cx.arena, str(get(item, "name")) orelse "(unnamed)"); + const name = flat(cx.arena, node.call.name); const label = if (node.cycle) try std.fmt.allocPrint(cx.arena, "{s} ↻ recursion", .{name}) else name; - try emitRange(cx, enc, uri, get(item, "selectionRange") orelse get(item, "range"), label); + try emitAt(cx, enc, node.call.uri, node.call.at, label); tree.rendered += 1; tree.siblings[depth] = more; std.mem.sort(CallTree.Site, node.ranges.items, {}, struct { fn less(_: void, a: CallTree.Site, b: CallTree.Site) bool { - return callRangeLess({}, a.range, b.range); + return rangeLess(a.range, b.range); } }.less); for (node.ranges.items, 0..) |site, site_index| { + if (cx.rows >= max_rows or (cx.fixed_out and cx.out.buffer.len - cx.out.end < row_room)) { + tree.limited = true; + return; + } if (site.focus) try cx.out.writeAll(lsp.callstack_match); try callPrefix(cx.out, tree, depth + 1); try cx.out.writeAll(if (node.children.items.len > 0 or site_index + 1 < node.ranges.items.len) "├─ " else if (rounded) "╰─ " else "└─ "); - try emitRange(cx, enc, uri, site.range, ""); + try emitAt(cx, enc, node.call.uri, site.range, ""); } try renderCallers(cx, enc, tree, node.children.items, depth + 1); } @@ -1054,7 +1223,7 @@ const Hier = enum { incoming, outgoing, supers, subs }; /// The two-step hierarchy kinds: prepare at the cursor, then follow every /// item the server returned (usually one). Gated on the server capability so /// an old server costs zero round trips. -fn hierarchy(c: *Conn, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, h: Hier, tr: *Trace) Err!void { +fn hierarchy(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []const u8, pos: Pos, deadline: i64, h: Hier, tr: *Trace) Err!void { const call_side = h == .incoming or h == .outgoing; if (call_side and !c.caps.call_hier) { tr.note("STOP: {s} does not advertise callHierarchyProvider", .{specs[si].name}); @@ -1072,9 +1241,9 @@ fn hierarchy(c: *Conn, si: usize, arena: std.mem.Allocator, cx: *Cx, uri: []cons .subs => "typeHierarchy/subtypes", }; const b = try atPos(arena, uri, pos); - const prepared = (try call(c, arena, prepare, b.items, deadline)) orelse return; + const prepared = (try call(c, io, arena, prepare, b.items, deadline)) orelse return; for (items(prepared)) |item| { - const result = (try hierarchyResult(c, arena, item, follow, deadline)) orelse return; + const result = (try hierarchyResult(c, io, arena, item, follow, deadline)) orelse return; for (items(result)) |entry| switch (h) { .incoming => { // one row per CALL SITE, under the caller's name — that is @@ -1134,6 +1303,10 @@ const Cx = struct { cur_path: []const u8, cur_src: []const u8, out: *std.Io.Writer, + /// `out` is the query's fixed answer buffer, whose room is checked. + fixed_out: bool = false, + /// Rows without their source text (Callstack: the core reads it). + no_text: bool = false, rows: usize = 0, relative_parents: bool = false, callstack_corners: lsp.CallstackCorners = .rounded, @@ -1169,11 +1342,16 @@ const Cx = struct { /// columns, and a single-line range becomes the `path:LINE:COL-ENDCOL` form a /// look SELECTS. `note` overrides the source line as the row's text. fn emitRange(cx: *Cx, enc: Enc, uri: []const u8, range: ?std.json.Value, note: []const u8) Err!void { + return emitAt(cx, enc, uri, rangeOf(range) orelse return, note); +} + +fn emitAt(cx: *Cx, enc: Enc, uri: []const u8, r: Range, note: []const u8) Err!void { if (cx.rows >= max_rows) return; const path = pathOf(cx.arena, uri) orelse return; if (path.len == 0 or path[0] != '/') return; // rows promise absolute-or-rel-from-base - const r = rangeOf(range) orelse return; - const src = cx.text(path); + // Without sources (Callstack) the asking file is still known: its rows' + // columns convert from utf-16 as ever. + const src = if (cx.no_text and !std.mem.eql(u8, path, cx.cur_path)) null else cx.text(path); var bol: usize = 0; var eol: usize = 0; @@ -1323,7 +1501,8 @@ fn transportPair(sv: *[2]libc.fd_t) bool { /// Spawn-or-return, and tell an existing server about a new project root. /// Returns the generation the caller's whole query is bound to. -fn ensure(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trace) Err!u32 { +fn ensure(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trace) Err!u32 { + c.si = si; if (c.state == .disabled) { tr.note("STOP: {s} is disabled for this session (no binary; set {s})", .{ specs[si].name, specs[si].env }); return error.NoServer; @@ -1341,7 +1520,7 @@ fn ensure(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trac try app(&b, arena, "{\"jsonrpc\":\"2.0\",\"method\":\"workspace/didChangeWorkspaceFolders\",\"params\":{\"event\":{\"added\":[{\"name\":\"root\",\"uri\":\""); try uriOf(&b, arena, root); try app(&b, arena, "\"}],\"removed\":[]}}}"); - try frame(c.sock, b.items, nowMs() + reply_ms); + try send(c, io, b.items, nowMs() + wedge_ms); const owned = sa.dupe(u8, root) catch return error.OutOfMemory; c.extra_roots.append(sa, owned) catch sa.free(owned); } @@ -1430,12 +1609,13 @@ fn ensure(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trac if (c.resp) |r| sa.free(r); c.resp = null; c.progress = 0; + c.loading = false; c.timeouts = 0; forgetDocs(c); if (c.root.len > 0) sa.free(c.root); c.root = owned_root; - const th = std.Thread.spawn(.{}, reader, .{ si, g, sv[0] }) catch { + const th = std.Thread.spawn(.{}, reader, .{ io, si, g, sv[0] }) catch { // no reader means nobody would ever close the fd our way; do it here, // before anything else can see the conn _ = libc.close(sv[0]); @@ -1450,8 +1630,14 @@ fn ensure(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trac post(si, .always, "{s} starting — {s}", .{ specs[si].name, root }); tr.note("spawned {s} (pid {d}) at {s}", .{ specs[si].name, pid, root }); - handshake(c, arena, root) catch |e| { - shutdownIf(c, g); + // A start runs to the end however soon the query that began it is + // canceled: killing a half-started server would only make the next + // query start it again. The cancel lands at the next wait instead. + const protection = io.swapCancelProtection(.blocked); + const started = handshake(c, io, arena, root); + _ = io.swapCancelProtection(protection); + started catch |e| { + shutdownIf(c, io, g); // NOT a session disable. A handshake that misses the deadline is // routinely environmental — a rustup shim deciding to download the // project's pinned toolchain before launching the real server was @@ -1477,7 +1663,7 @@ fn ensure(c: *Conn, si: usize, arena: std.mem.Allocator, req: lsp.Req, tr: *Trac return g; } -fn handshake(c: *Conn, arena: std.mem.Allocator, root: []const u8) Err!void { +fn handshake(c: *Conn, io: std.Io, arena: std.mem.Allocator, root: []const u8) Err!void { var b: std.ArrayList(u8) = .empty; try b.print(arena, "\"processId\":{d},\"clientInfo\":{{\"name\":\"pardes\"}},\"rootUri\":\"", .{@as(u32, @bitCast(libc.getpid()))}); try uriOf(&b, arena, root); @@ -1509,7 +1695,7 @@ fn handshake(c: *Conn, arena: std.mem.Allocator, root: []const u8) Err!void { for (b.items) |ch| if (ch != '\n') try body.append(arena, ch); const deadline = nowMs() + init_ms; - const reply = (try call(c, arena, "initialize", body.items, deadline)) orelse return error.Protocol; + const reply = (try call(c, io, arena, "initialize", body.items, deadline)) orelse return error.Protocol; const caps = get(reply, "capabilities"); c.caps.enc = if (std.mem.eql(u8, str(get(caps, "positionEncoding")) orelse "utf-16", "utf-8")) .utf8 else .utf16; @@ -1521,7 +1707,7 @@ fn handshake(c: *Conn, arena: std.mem.Allocator, root: []const u8) Err!void { c.caps.type_hier = provider(get(caps, "typeHierarchyProvider")); c.caps.folders = if (get(get(get(caps, "workspace"), "workspaceFolders"), "supported")) |s| s == .bool and s.bool else false; - try frame(c.sock, "{\"jsonrpc\":\"2.0\",\"method\":\"initialized\",\"params\":{}}", deadline); + try send(c, io, "{\"jsonrpc\":\"2.0\",\"method\":\"initialized\",\"params\":{}}", deadline); } /// A server capability that may be `true`, an options object, or absent. @@ -1536,7 +1722,7 @@ fn provider(v: ?std.json.Value) bool { /// didOpen the first time a file is seen, didChange when its bytes moved, /// nothing when they did not — the common case between two presses of gd. -fn syncDoc(c: *Conn, si: usize, arena: std.mem.Allocator, uri: []const u8, src: []const u8) Err!void { +fn syncDoc(c: *Conn, io: std.Io, si: usize, arena: std.mem.Allocator, uri: []const u8, src: []const u8) Err!void { const hash = std.hash.Wyhash.hash(0, src); var doc: ?*Doc = null; for (c.docs.items) |*d| if (std.mem.eql(u8, d.uri, uri)) { @@ -1568,13 +1754,16 @@ fn syncDoc(c: *Conn, si: usize, arena: std.mem.Allocator, uri: []const u8, src: try jstr(&b, arena, src); try app(&b, arena, "}}}"); } - try frame(c.sock, b.items, nowMs() + req_ms); + // A server busy with what it was sent last reads no more meanwhile + // (clangd parses its compile database at a first open): this waits as + // an answer does, for a cancel or a server that has stopped. + try send(c, io, b.items, nowMs() + wedge_ms); } /// Send a request and wait on the mailbox. Returns the parsed `result`, or /// null for an error response / null result — both are legal "no answer". /// Runs with the conn mutex held; the mutex is released inside the wait. -fn call(c: *Conn, arena: std.mem.Allocator, method: []const u8, params: []const u8, deadline: i64) Err!?std.json.Value { +fn call(c: *Conn, io: std.Io, arena: std.mem.Allocator, method: []const u8, params: []const u8, deadline: i64) Err!?std.json.Value { const g = c.gen; const id = c.next_id; c.next_id +%= 1; @@ -1589,17 +1778,36 @@ fn call(c: *Conn, arena: std.mem.Allocator, method: []const u8, params: []const c.want_id = id; defer c.want_id = 0; - try frame(c.sock, b.items, deadline); + try send(c, io, b.items, if (c.state == .ready) nowMs() + wedge_ms else deadline); + // The handshake (still `.starting`) has its deadline. A ready server is + // waited for until it answers or the shell cancels this query for a + // newer one, so the first query after a start is answered, not lost: + // past `deadline` the message row says it is still working, and only + // silent and idle for wedge_ms is it not answering. + var said = false; + var busy_at = nowMs(); while (c.resp == null and c.gen == g and c.alive()) { - if (!timedWait(c, deadline)) break; + const ready = c.state == .ready; + const waiting = timedWait(c, io, if (ready) nowMs() + 500 else deadline) catch |e| { + cancelRequest(c, io, arena, id); + return e; + }; + if (!ready) { + if (waiting) continue; + break; + } + if (c.progress > 0) busy_at = nowMs(); + if (!said and nowMs() >= deadline) { + said = true; + post(c.si, .always, "{s} is still working on it\u{2026}", .{specs[c.si].name}); + } + if (nowMs() - busy_at >= wedge_ms) break; } + if (said and c.resp != null) post(c.si, .always, "{s} answered", .{specs[c.si].name}); if (c.gen != g or !c.alive()) return error.Dead; const raw = c.resp orelse { - // give the server leave to abandon the work we stopped waiting for - var cb: std.ArrayList(u8) = .empty; - cb.print(arena, "{{\"jsonrpc\":\"2.0\",\"method\":\"$/cancelRequest\",\"params\":{{\"id\":{d}}}}}", .{id}) catch return error.Timeout; - frame(c.sock, cb.items, nowMs() + reply_ms) catch {}; + cancelRequest(c, io, arena, id); return error.Timeout; }; c.resp = null; @@ -1609,49 +1817,23 @@ fn call(c: *Conn, arena: std.mem.Allocator, method: []const u8, params: []const if (result == .null) return null; return result; } -/// One bounded cond wait. False when the deadline has passed. -/// -/// The deadline arithmetic everywhere here is CLOCK_MONOTONIC, so the wait -/// must be too: a REALTIME abstime plus an NTP step backwards would park a -/// worker far past `req_ms`, violating the seam's bounded-wait promise. On -/// linux the condvar is lazily initialized with a monotonic condattr; darwin -/// has no setclock but has a RELATIVE wait, which never consults the wall -/// clock at all. -fn timedWait(c: *Conn, deadline: i64) bool { +/// Give the server leave to abandon the work we stopped waiting for. +fn cancelRequest(c: *Conn, io: std.Io, arena: std.mem.Allocator, id: u32) void { + var cb: std.ArrayList(u8) = .empty; + cb.print(arena, "{{\"jsonrpc\":\"2.0\",\"method\":\"$/cancelRequest\",\"params\":{{\"id\":{d}}}}}", .{id}) catch return; + send(c, io, cb.items, nowMs() + reply_ms) catch {}; +} + +/// One bounded cond wait, and a cancelation point: a worker the shell +/// cancels for a newer query stops here. False when the deadline has passed. +fn timedWait(c: *Conn, io: std.Io, deadline: i64) error{Canceled}!bool { const left = deadline - nowMs(); if (left <= 0) return false; const wait_ms = @min(left, 500); // tick so gen/state changes are noticed - if (comptime builtin.os.tag.isDarwin()) { - const rel: libc.timespec = .{ - .sec = @divTrunc(wait_ms, 1000), - .nsec = @rem(wait_ms, 1000) * 1_000_000, - }; - _ = pthread_cond_timedwait_relative_np(&c.cond, &c.mu, &rel); - return true; - } - if (!c.cond_monotonic) { - // lazily re-initialize the zeroed (REALTIME) condvar with a - // monotonic clock; under the mutex, and only before the first wait, - // so no thread can be parked on the old one - var attr: pthread_condattr_t = undefined; - if (pthread_condattr_init(&attr) == 0) { - _ = pthread_condattr_setclock(&attr, CLOCK_MONOTONIC); - _ = pthread_cond_init(&c.cond, &attr); - _ = pthread_condattr_destroy(&attr); - } - c.cond_monotonic = true; - } - var now: libc.timespec = undefined; - _ = libc.clock_gettime(.MONOTONIC, &now); - var abs: libc.timespec = .{ - .sec = now.sec + @divTrunc(wait_ms, 1000), - .nsec = now.nsec + @rem(wait_ms, 1000) * 1_000_000, + c.cond.waitTimeout(io, &c.mu, .{ .duration = .{ .raw = .fromMilliseconds(wait_ms), .clock = .awake } }) catch |e| switch (e) { + error.Timeout => {}, + error.Canceled => return error.Canceled, }; - if (abs.nsec >= 1_000_000_000) { - abs.sec += 1; - abs.nsec -= 1_000_000_000; - } - _ = libc.pthread_cond_timedwait(&c.cond, &c.mu, &abs); return true; } @@ -1659,7 +1841,7 @@ fn timedWait(c: *Conn, deadline: i64) bool { /// respawn that happened during the caller's wait must not be killed for its /// predecessor's crimes. Mutex held. The reader closes the fd; this only /// shuts the transport down and reaps the child. -fn shutdownIf(c: *Conn, g: u32) void { +fn shutdownIf(c: *Conn, io: std.Io, g: u32) void { if (c.gen != g or c.sock < 0) return; _ = libc.shutdown(c.sock, 2); // SHUT_RDWR: the reader sees EOF and closes reap(c.pid); @@ -1669,7 +1851,7 @@ fn shutdownIf(c: *Conn, g: u32) void { forgetDocs(c); if (c.resp) |r| sa.free(r); c.resp = null; - _ = libc.pthread_cond_broadcast(&c.cond); + c.cond.broadcast(io); } /// TERM, a bounded grace, then KILL, to the server's whole process group @@ -1715,6 +1897,7 @@ fn forgetDocs(c: *Conn) void { sa.free(d.body); } c.diags.clearRetainingCapacity(); + c.diag_bytes = 0; } // ------------------------------------------------------------ reader thread @@ -1722,20 +1905,22 @@ fn forgetDocs(c: *Conn) void { /// Owns the read side of one socket for one generation, and is the only /// closer of that fd. Routes responses to the mailbox, answers server /// requests, feeds the diagnostics store, narrates progress. -fn reader(si: usize, g: u32, sock: c_int) void { +fn reader(io: std.Io, si: usize, g: u32, sock: c_int) void { const c = &conns[si]; var buf = sa.alloc(u8, 256 * 1024) catch { - readerExit(c, si, g, sock); + readerExit(c, io, si, g, sock); return; }; defer sa.free(buf); var len: usize = 0; + var parse_arena: std.heap.ArenaAllocator = .init(sa); + defer parse_arena.deinit(); outer: while (true) { // drain every complete frame already buffered drain: while (true) switch (frameNext(buf[0..len])) { .frame => |m| { - dispatch(c, si, g, sock, buf[m.body_start..m.body_end]); + dispatch(c, io, si, g, sock, buf[m.body_start..m.body_end], &parse_arena); std.mem.copyForwards(u8, buf[0 .. len - m.consumed], buf[m.consumed..len]); len -= m.consumed; }, @@ -1761,9 +1946,9 @@ fn reader(si: usize, g: u32, sock: c_int) void { if (pr == 0) { // tick: a respawn while the server was silent leaves this thread // reading a corpse; notice and go - c.lock(); + c.mu.lockUncancelable(io); const stale = c.gen != g; - c.unlock(); + c.mu.unlock(io); if (stale) break :outer; continue; } @@ -1776,11 +1961,11 @@ fn reader(si: usize, g: u32, sock: c_int) void { if (got == 0) break :outer; // the server exited or shutdownIf spoke len += @intCast(got); } - readerExit(c, si, g, sock); + readerExit(c, io, si, g, sock); } -fn readerExit(c: *Conn, si: usize, g: u32, sock: c_int) void { - c.lock(); +fn readerExit(c: *Conn, io: std.Io, si: usize, g: u32, sock: c_int) void { + c.mu.lockUncancelable(io); if (c.gen == g and c.alive()) { // the server died on its own — shutdownIf never saw it, so the corpse // is ours to reap and the conn's transport fields are ours to clear @@ -1800,10 +1985,14 @@ fn readerExit(c: *Conn, si: usize, g: u32, sock: c_int) void { } else { post(si, .always, "{s} exited — restarts on the next query", .{specs[si].name}); } - _ = libc.pthread_cond_broadcast(&c.cond); + c.cond.broadcast(io); } - c.unlock(); + c.mu.unlock(io); + // A query writes with the mutex let go (send): the fd stays its until + // that write is done, and shutdown(2) has already made it fail fast. + c.write_mu.lockUncancelable(io); _ = libc.close(sock); + c.write_mu.unlock(io); } /// 10s doubling to 2min: the fork-per-keystroke guard's schedule. @@ -1845,32 +2034,33 @@ fn frameNext(data: []const u8) FrameStep { /// One message from the server. Parses into a throwaway arena; touches conn /// state only under the mutex; replies never hold it (bounded writes must not /// stall the mailbox). -fn dispatch(c: *Conn, si: usize, g: u32, sock: c_int, raw: []const u8) void { - var arena_state: std.heap.ArenaAllocator = .init(sa); - defer arena_state.deinit(); +fn dispatch(c: *Conn, io: std.Io, si: usize, g: u32, sock: c_int, raw: []const u8, arena_state: *std.heap.ArenaAllocator) void { + // The reader's one parse arena, reset per message: no mapping per + // `$/progress` report, and no more than parse_kept kept between them. + defer _ = arena_state.reset(.{ .retain_with_limit = parse_kept }); const arena = arena_state.allocator(); const v = std.json.parseFromSliceLeaky(std.json.Value, arena, raw, .{}) catch return; if (v != .object) return; if (str(get(v, "method"))) |method| { - if (get(v, "id")) |id| return serverRequest(arena, sock, method, id, get(v, "params")); - return notification(c, si, g, raw, method, get(v, "params")); + if (get(v, "id")) |id| return serverRequest(c, io, arena, sock, method, id, get(v, "params")); + return notification(c, io, si, g, raw, method, get(v, "params")); } // a response: deliver to the one waiting query, if it is still waiting const id = num(get(v, "id")) orelse return; - c.lock(); - defer c.unlock(); + c.mu.lockUncancelable(io); + defer c.mu.unlock(io); if (c.gen == g and c.want_id != 0 and id == c.want_id and c.resp == null) { c.resp = sa.dupe(u8, raw) catch null; - _ = libc.pthread_cond_broadcast(&c.cond); + c.cond.broadcast(io); } } /// The server asked US something. Everything optional was declined in the /// handshake, so a null-ish answer is always legal — but it must ARRIVE, or /// the server blocks forever on its own question. -fn serverRequest(arena: std.mem.Allocator, sock: c_int, method: []const u8, id: std.json.Value, params: ?std.json.Value) void { +fn serverRequest(c: *Conn, io: std.Io, arena: std.mem.Allocator, sock: c_int, method: []const u8, id: std.json.Value, params: ?std.json.Value) void { var b: std.ArrayList(u8) = .empty; app(&b, arena, "{\"jsonrpc\":\"2.0\",\"id\":") catch return; switch (id) { @@ -1890,17 +2080,17 @@ fn serverRequest(arena: std.mem.Allocator, sock: c_int, method: []const u8, id: } else { app(&b, arena, ",\"result\":null}") catch return; } - frame(sock, b.items, nowMs() + reply_ms) catch {}; + answerServer(c, io, sock, b.items); } -fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8, params: ?std.json.Value) void { +fn notification(c: *Conn, io: std.Io, si: usize, g: u32, raw: []const u8, method: []const u8, params: ?std.json.Value) void { if (std.mem.eql(u8, method, "textDocument/publishDiagnostics")) { const uri = str(get(params, "uri")) orelse return; // keep the raw MESSAGE (params included); re-parsing it per query // beats owning a parsed tree past this arena's life const body = sa.dupe(u8, raw) catch return; - c.lock(); - defer c.unlock(); + c.mu.lockUncancelable(io); + defer c.mu.unlock(io); if (c.gen != g) { sa.free(body); return; @@ -1914,10 +2104,25 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 slot = d; break; }; + // Bounded in files and bytes: a new set that does not fit pushes + // out the oldest files' (the server sends a file's again when it + // changes); one bigger than the whole store is not kept. + if (body.len > max_diag_bytes) { + sa.free(body); + return; + } if (slot) |d| { + c.diag_bytes -= d.body.len; sa.free(d.body); d.body = body; - } else if (c.diags.items.len < 256) { + c.diag_bytes += body.len; + } else { + while (c.diags.items.len > 0 and (c.diags.items.len >= max_diag_files or c.diag_bytes + body.len > max_diag_bytes)) { + const old = c.diags.orderedRemove(0); + c.diag_bytes -= old.body.len; + sa.free(old.uri); + sa.free(old.body); + } const owned = sa.dupe(u8, uri) catch { sa.free(body); return; @@ -1927,17 +2132,18 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 sa.free(body); return; }; - } else sa.free(body); - _ = libc.pthread_cond_broadcast(&c.cond); // waitFresh watches this + c.diag_bytes += body.len; + } + c.cond.broadcast(io); // waitFresh watches this return; } if (std.mem.eql(u8, method, "$/progress")) { const value = get(params, "value") orelse return; const pkind = str(get(value, "kind")) orelse return; const msg = str(get(value, "message")) orelse ""; - c.lock(); + c.mu.lockUncancelable(io); if (c.gen != g) { - c.unlock(); + c.mu.unlock(io); return; } if (std.mem.eql(u8, pkind, "begin")) { @@ -1948,7 +2154,7 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 var tbuf: [48]u8 = undefined; const t = tbuf[0..c.title_len]; @memcpy(t, c.title[0..c.title_len]); - c.unlock(); + c.mu.unlock(io); post(si, .chatty, "{s}: {s}\u{2026} {s}", .{ specs[si].name, t, msg }); return; } @@ -1957,7 +2163,7 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 const t = tbuf[0..c.title_len]; @memcpy(t, c.title[0..c.title_len]); const pct = num(get(value, "percentage")); - c.unlock(); + c.mu.unlock(io); if (pct) |p| post(si, .chatty, "{s}: {s} {d}% {s}", .{ specs[si].name, t, p, msg }) else @@ -1968,7 +2174,7 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 c.progress -= 1; const idle = c.progress <= 0; if (idle) c.progress = 0; - c.unlock(); + c.mu.unlock(io); // the setpoint every burst of progress ends on; `.always` + the // dedupe above means it lands exactly once however the reports raced if (idle) post(si, .always, "{s}: ready", .{specs[si].name}); @@ -1985,6 +2191,12 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 if (std.mem.eql(u8, method, "experimental/serverStatus")) { const health = str(get(params, "health")) orelse "ok"; const quiescent = if (get(params, "quiescent")) |q| q == .bool and q.bool else false; + c.mu.lockUncancelable(io); + if (c.gen == g) { + c.loading = !quiescent; + c.cond.broadcast(io); + } + c.mu.unlock(io); if (!std.mem.eql(u8, health, "ok")) post(si, .always, "{s}: {s} — {s}", .{ specs[si].name, health, str(get(params, "message")) orelse "" }) else if (quiescent) @@ -1995,12 +2207,12 @@ fn notification(c: *Conn, si: usize, g: u32, raw: []const u8, method: []const u8 // ------------------------------------------------------------- introspection -fn status(req: lsp.Req, out: *std.Io.Writer) !void { +fn status(io: std.Io, req: lsp.Req, out: *std.Io.Writer) !void { _ = req; try out.print("\nprotocol servers (lsp-client):\n", .{}); for (&specs, 0..) |*s, i| { const c = &conns[i]; - c.lock(); + c.mu.lockUncancelable(io); const state = c.state; var rootbuf: [256]u8 = undefined; const rootlen = @min(c.root.len, rootbuf.len); @@ -2012,7 +2224,7 @@ fn status(req: lsp.Req, out: *std.Io.Writer) !void { const pull = c.caps.pull; const chier = c.caps.call_hier; const thier = c.caps.type_hier; - c.unlock(); + c.mu.unlock(io); const env_v = if (getenv(s.env)) |v| std.mem.span(v) else null; // Never spawned is not off: the first query of its files starts it. try out.print(" {s:<28} {s}", .{ s.name, if (state == .off) "not started yet (its first query starts it)" else @tagName(state) }); @@ -2069,21 +2281,80 @@ fn atPos(arena: std.mem.Allocator, uri: []const u8, pos: Pos) Err!std.ArrayList( return b; } -fn frame(sock: c_int, body: []const u8, deadline: i64) Err!void { +/// A message to the server from a query, the conn's mutex let go while it is +/// written: the reader goes on taking the server's output meanwhile, which a +/// server may be waiting to write before it reads more of ours. +fn send(c: *Conn, io: std.Io, body: []const u8, deadline: i64) Err!void { + const sock = c.sock; + c.mu.unlock(io); + defer c.mu.lockUncancelable(io); + return frame(c, io, sock, body, deadline); +} + +fn frame(c: *Conn, io: std.Io, sock: c_int, body: []const u8, deadline: i64) Err!void { if (sock < 0) return error.Dead; + c.write_mu.lockUncancelable(io); + defer releaseWrite(c, io, sock); var hdr: [64]u8 = undefined; const h = std.fmt.bufPrint(&hdr, "Content-Length: {d}\r\n\r\n", .{body.len}) catch return error.Protocol; - try sockWrite(sock, h, deadline); - try sockWrite(sock, body, deadline); + var started = false; + try sockWrite(io, sock, h, deadline, &started); + try sockWrite(io, sock, body, deadline, &started); +} + +/// The reader's answer to a server request: written now if the socket is +/// free, else queued for the query writing (bounded; one that does not fit is +/// dropped, and the server's request goes unanswered). +fn answerServer(c: *Conn, io: std.Io, sock: c_int, body: []const u8) void { + var hdr: [64]u8 = undefined; + const h = std.fmt.bufPrint(&hdr, "Content-Length: {d}\r\n\r\n", .{body.len}) catch return; + c.replies_mu.lockUncancelable(io); + const half = &c.replies[c.filling]; + const len = &c.replies_len[c.filling]; + if (len.* + h.len + body.len <= half.len) { + @memcpy(half[len.*..][0..h.len], h); + @memcpy(half[len.* + h.len ..][0..body.len], body); + len.* += h.len + body.len; + } + c.replies_mu.unlock(io); + if (c.write_mu.tryLock()) releaseWrite(c, io, sock); +} + +/// Lets the socket go, first sending what the reader queued meanwhile, and +/// again for what it queues while that goes out. +fn releaseWrite(c: *Conn, io: std.Io, sock: c_int) void { + while (true) { + c.replies_mu.lockUncancelable(io); + const sent = c.filling; + const n = c.replies_len[sent]; + if (n > 0) c.filling ^= 1; + c.replies_mu.unlock(io); + if (n > 0) { + var started = false; + sockWrite(null, sock, c.replies[sent][0..n], nowMs() + reply_ms, &started) catch {}; + c.replies_len[sent] = 0; + } + c.write_mu.unlock(io); + c.replies_mu.lockUncancelable(io); + const more = c.replies_len[c.filling] > 0; + c.replies_mu.unlock(io); + if (!more or !c.write_mu.tryLock()) return; + } } -fn sockWrite(sock: c_int, bytes: []const u8, deadline: i64) Err!void { +/// Writes `bytes`, `started` once any byte of their message is out. Before +/// then, the deadline and a cancel stop it; after, the message is finished +/// however long the server takes to read it (bounded by wedge_ms), since +/// half of one ends the server's reading of every message after it. +fn sockWrite(io: ?std.Io, sock: c_int, bytes: []const u8, deadline: i64, started: *bool) Err!void { var off: usize = 0; while (off < bytes.len) { - const left = deadline - nowMs(); - if (left <= 0) return error.Timeout; + if (!started.*) { + if (deadline - nowMs() <= 0) return error.Timeout; + if (io) |cancel_io| cancel_io.checkCancel() catch return error.Canceled; + } else if (nowMs() - deadline > wedge_ms) return error.Dead; var pfd = [_]libc.pollfd{.{ .fd = sock, .events = POLLOUT, .revents = 0 }}; - const pr = libc.poll(&pfd, 1, @intCast(@min(left, 1000))); + const pr = libc.poll(&pfd, 1, 500); if (pr < 0) { if (libc.errno(pr) == .INTR) continue; return error.Dead; @@ -2096,6 +2367,7 @@ fn sockWrite(sock: c_int, bytes: []const u8, deadline: i64) Err!void { return error.Dead; } if (n == 0) return error.Dead; + started.* = true; off += @intCast(n); } } @@ -2318,7 +2590,7 @@ test "caller trees reverse incoming paths and merge shared callers and sites" { try std.testing.expectEqual(@as(usize, 1), tree.roots.items.len); try std.testing.expectEqual(@as(usize, 4), tree.nodes.items.len); const root = tree.nodes.items[tree.roots.items[0]]; - try std.testing.expectEqualStrings("main", str(get(root.item, "name")).?); + try std.testing.expectEqualStrings("main", root.call.name); try std.testing.expectEqual(@as(usize, 1), root.ranges.items.len); const page = tree.nodes.items[root.children.items[0]]; try std.testing.expectEqual(@as(usize, 2), page.children.items.len); @@ -2355,6 +2627,32 @@ test "caller trees reverse incoming paths and merge shared callers and sites" { try std.testing.expect(recursive.nodes.items[1].cycle); } +test "test callers sort after the rest, each group by place" { + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const fixture = try std.json.parseFromSliceLeaky(std.json.Value, arena, "[{\"name\":\"test b\",\"uri\":\"file:///a.zig\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":1}}},{\"name\":\"z\",\"uri\":\"file:///b.zig\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":1}}},{\"name\":\"x\",\"uri\":\"file:///a_test.zig\",\"selectionRange\":{\"start\":{\"line\":0,\"character\":0},\"end\":{\"line\":0,\"character\":1}}},{\"name\":\"y\",\"uri\":\"file:///a.zig\",\"selectionRange\":{\"start\":{\"line\":5,\"character\":0},\"end\":{\"line\":5,\"character\":1}}}]", .{}); + var tree: CallTree = .{}; + for (items(fixture)) |item| try tree.nodes.append(arena, .{ .call = try callOf(arena, item) }); + var order = [_]usize{ 0, 1, 2, 3 }; + std.mem.sort(usize, &order, @as(*const CallTree, &tree), callerLess); + try std.testing.expectEqualSlices(usize, &.{ 3, 1, 0, 2 }, &order); +} + +test "a mailbox wait is a cancelation point: a canceled worker stops waiting" { + const io = std.testing.io; + var c: Conn = .{}; + const Waiter = struct { + fn run(conn: *Conn, wio: std.Io) error{Canceled}!void { + conn.mu.lockUncancelable(wio); + defer conn.mu.unlock(wio); + while (true) _ = try timedWait(conn, wio, nowMs() + 60_000); + } + }; + var future = try io.concurrent(Waiter.run, .{ &c, io }); + try std.testing.expectError(error.Canceled, future.cancel(io)); +} + test "callstack cross-crate paths remain resolvable without absolute path clutter" { var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena_state.deinit(); @@ -2584,37 +2882,38 @@ test "a language with no server to start says so, not that it did not answer" { defer arena.deinit(); var buf: [256]u8 = undefined; var out: std.Io.Writer = .fixed(&buf); - try query(std.testing.allocator, arena.allocator(), .{ .kind = .hover, .path = "/x/a.py", .source = "", .offset = 0 }, &out); + try query(std.testing.io, std.testing.allocator, arena.allocator(), .{ .kind = .hover, .path = "/x/a.py", .source = "", .offset = 0 }, &out); try std.testing.expectEqualStrings("@none language server for .py not found\n", out.buffered()); } test "Lspinfo before any query says a server is not started yet, not off" { var out: std.Io.Writer.Allocating = .init(std.testing.allocator); defer out.deinit(); - try status(.{ .kind = .status, .path = "", .source = "", .offset = 0 }, &out.writer); + try status(std.testing.io, .{ .kind = .status, .path = "", .source = "", .offset = 0 }, &out.writer); try std.testing.expect(std.mem.indexOf(u8, out.written(), "not started yet (its first query starts it)") != null); } test "a server that failed a moment ago is said to have failed, and when it is tried again, not to be missing" { if (getenv("PARDES_LSP_ZIG") != null) return error.SkipZigTest; + const io = std.testing.io; const si = specFor("/x/a.zig").?; const c = &conns[si]; - c.lock(); + c.mu.lockUncancelable(io); const was = .{ c.state, c.retry_after_ms }; c.state = .dead; c.retry_after_ms = nowMs() + 4500; - c.unlock(); + c.mu.unlock(io); defer { - c.lock(); + c.mu.lockUncancelable(io); c.state = was[0]; c.retry_after_ms = was[1]; - c.unlock(); + c.mu.unlock(io); } var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); defer arena.deinit(); var out: std.Io.Writer.Allocating = .init(std.testing.allocator); defer out.deinit(); - try query(std.testing.allocator, arena.allocator(), .{ .kind = .hover, .path = "/x/a.zig", .source = "", .offset = 0 }, &out.writer); + try query(std.testing.io, std.testing.allocator, arena.allocator(), .{ .kind = .hover, .path = "/x/a.zig", .source = "", .offset = 0 }, &out.writer); try std.testing.expect(std.mem.indexOf(u8, out.written(), "zls failed recently; retry in 5s") != null); } diff --git a/src/macos.zig b/src/macos.zig index 50fa04fa..5d3dfec4 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -44,7 +44,11 @@ fn hostWatchFile(pane: u8, generation: u32, path: ?[*]const u8, path_len: usize) const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); -pub const std_options: std.Options = .{ .logFn = logFn }; +// Every thread's alternate signal stack is a threadlocal that libc zeroes as +// the thread starts, so std's 256 KiB made each 9P connection's thread cost +// that much resident. A stack-overflow segfault on a thread still printed its +// whole symbolized trace from 32 KiB up (16 KiB double-faulted): 64 KiB. +pub const std_options: std.Options = .{ .logFn = logFn, .signal_stack_size = 64 * 1024 }; fn logFn( comptime level: std.log.Level, @@ -2419,7 +2423,7 @@ fn pipeWorker(st: *State, job: *selection_pipe.Job) anyerror!void { } fn lspWorker(st: *State, job: *host_io.Lsp.Job) anyerror!void { - host_io.Lsp.work(st.gpa, job, st, deliverLspRows); + host_io.Lsp.work(st.io, st.gpa, job, st, deliverLspRows); } fn deliverLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void { @@ -2582,12 +2586,11 @@ fn reap(st: *State, pane: u8) void { } fn readPty(st: *State, io: std.Io, pty: std.Io.File, id: u8, gen: u32) anyerror!void { - var read_buf: [0x10000]u8 = undefined; - var reader = pty.readerStreaming(io, &read_buf); + // One buffer, read into directly: a Reader around it only added a second + // (and in a safe build, filled both as `undefined` on every start). + var buf: [0x10000]u8 = undefined; while (true) { - var buf: [0x10000]u8 = undefined; - var vec = [_][]u8{&buf}; - const n = reader.interface.readVec(&vec) catch break; + const n = pty.readStreaming(io, &.{&buf}) catch break; if (n == 0) break; const bytes = st.gpa.dupe(u8, buf[0..n]) catch break; st.inbox.pushOutput(st.gpa, io, .{ .pane = id, .gen = gen, .bytes = bytes }) catch break; diff --git a/src/main.zig b/src/main.zig index 64614daa..ea2db917 100644 --- a/src/main.zig +++ b/src/main.zig @@ -16,7 +16,11 @@ pub const std_options_debug_io: std.Io = if (is_emscripten) else std_options_debug_threaded_io.?.io(); -pub const std_options: std.Options = .{ .logFn = logFn }; +// Every thread's alternate signal stack is a threadlocal that libc zeroes as +// the thread starts, so std's 256 KiB made each 9P connection's thread cost +// that much resident. A stack-overflow segfault on a thread still printed its +// whole symbolized trace from 32 KiB up (16 KiB double-faulted): 64 KiB. +pub const std_options: std.Options = .{ .logFn = logFn, .signal_stack_size = 64 * 1024 }; fn logFn( comptime level: std.log.Level, @@ -328,7 +332,11 @@ fn webMain() !void { // malloc otherwise. Kept on purpose: glibc's malloc was measured at least as // fast as std.heap.smp_allocator on every scenario and faster on MuPDF's // page-sized rasters. macos.zig makes the same choice for itself. -fn nativeMain(init: std.process.Init) !void { +fn nativeMain(std_init: std.process.Init) !void { + var init = std_init; + // Zig 0.17's std.start gives a safe build a SafeAllocator over the page + // allocator, not libc's malloc: hand the shells malloc, as above. + if (builtin.mode != .debug) init.gpa = std.heap.c_allocator; var stderr_probe: [64]u8 = undefined; _ = std.debug.lockStderr(&stderr_probe); std.debug.unlockStderr(); diff --git a/src/memory.zig b/src/memory.zig index 48403c55..853d641a 100644 --- a/src/memory.zig +++ b/src/memory.zig @@ -16,6 +16,10 @@ pub const limits = struct { pub const pending_write_cap: usize = if (board) 0 else 4 * MiB; pub const wrap_rows = if (board) 128 else 256; pub const undo_max = if (board) 16 else 256; + /// The text a file's undo and redo steps hold together, kept by dropping + /// the oldest; the newest step always stays, so the bound per file is + /// this plus one snapshot (at most max_file_bytes). + pub const undo_bytes: usize = if (board) 64 * KiB else 64 * MiB; pub const message_log = if (board) 16 else 128; /// ranges one selection holds; helix has no limit, and a `%s` over a /// file's words wants hundreds @@ -23,6 +27,19 @@ pub const limits = struct { /// /log's ring, which records whether or not anyone reads it. pub const log_bytes: usize = if (board) 4 * KiB else 64 * KiB; pub const max_tag_tail: usize = if (board) 512 else 4096; + /// Pixels one image may decode to (RGBA, 4 bytes each): checked from its + /// header before stb_image allocates them. + pub const image_decode_pixels: usize = if (board) 0 else 64 * 1024 * 1024; + /// What the core's per-step scratch arena and the frame arena keep + /// between steps: a step that needed more (a huge Callstack's sources) + /// gives the rest back instead of holding its high-water mark. + pub const scratch_kept: usize = if (board) 4 * KiB else 16 * MiB; + pub const frame_kept: usize = if (board) 4 * KiB else 16 * MiB; + /// The other open files one language query copies for its server, in + /// bytes: past it the rest are left out (the asked file always goes). + pub const lsp_snapshot_bytes: usize = if (board) 0 else 64 * MiB; + /// One paste, from any shell: past it, the rest is left out and said. + pub const max_paste_bytes: usize = if (board) 16 * KiB else 4 * MiB; pub const host_path_cap: usize = if (board) 0 else 4095; /// -Dembed-sources: the editor serves its own sources under /src. pub const embedded_sources = config.embed_sources; @@ -34,6 +51,10 @@ pub const limits = struct { pub const tree_sitter = if (board) 0 else if (reduced_target) 4 * MiB else 16 * MiB; pub const image = if (board) 0 else if (reduced_target) 64 * KiB else 32 * MiB; pub const pdf = if (board) 0 else if (reduced_target or !config.mupdf) 64 * KiB else 64 * MiB; + /// One language query's working memory (its parsed answers, the rows + /// it writes): a hard bound, nothing spills. Callstack walks until it + /// would leave less than its rendering reserve. + pub const lsp_query = if (board or reduced_target) 0 else 256 * MiB; }; }; @@ -96,6 +117,82 @@ var frame_buffer: [limits.arena.frame]u8 = @splat(0); var tree_sitter_buffer: [limits.arena.tree_sitter]u8 = @splat(0); var image_buffer: [limits.arena.image]u8 = @splat(0); var pdf_buffer: [limits.arena.pdf]u8 = @splat(0); +var lsp_query_buffer: [limits.arena.lsp_query]u8 align(std.heap.page_size_max) = @splat(0); +var lsp_query_busy: std.atomic.Value(bool) = .init(false); +/// What a query may leave resident of the region (giveLspQuery). +const lsp_query_kept = 8 * MiB; + +/// The language query region, for the one query running; null while another +/// holds it (the shells cancel and join a query before starting the next). +pub fn takeLspQuery() ?[]u8 { + if (lsp_query_busy.swap(true, .acquire)) return null; + return &lsp_query_buffer; +} + +/// Gives the region back after a query. A big one's touched pages go back to +/// the system (zeroed again on their next touch, as .bss is), so one huge +/// answer does not stay resident; a small one's stay, for the next query to +/// reuse without faulting them in again. +pub fn giveLspQuery(used: usize) void { + if (comptime builtin.os.tag == .linux) if (used > lsp_query_kept) { + const page = std.heap.pageSize(); + const len = std.mem.alignForward(usize, @min(used, lsp_query_buffer.len), page); + std.posix.madvise(@as([*]align(std.heap.page_size_min) u8, @ptrCast(&lsp_query_buffer)), len, std.posix.MADV.DONTNEED) catch {}; + }; + lsp_query_busy.store(false, .release); +} + +/// `n` bytes as they come: `Allocator.alloc` fills a safe build's new memory +/// as `undefined` (0xAA), which writes, and makes resident, all of a buffer +/// sized for the worst case: every language query wrote its 51 MB answer +/// room, every search its 16 MiB. For buffers written before they are read. +pub fn unfilled(allocator: Allocator, n: usize) Allocator.Error![]u8 { + if (n == 0) return allocator.alloc(u8, 0); + const ptr = allocator.rawAlloc(n, .of(u8), @returnAddress()) orelse return error.OutOfMemory; + return ptr[0..n]; +} + +/// `bytes` copied into memory `unfilled` takes: a text-sized copy (an undo +/// snapshot) is written once, not filled first. +pub fn dupeUnfilled(allocator: Allocator, bytes: []const u8) Allocator.Error![]u8 { + const out = try unfilled(allocator, bytes.len); + @memcpy(out, bytes); + return out; +} + +/// Frees without the safe-build overwrite `free` does, for text-sized buffers +/// freed on every edit. +pub fn freeUnfilled(allocator: Allocator, bytes: []const u8) void { + if (bytes.len > 0) allocator.rawFree(@constCast(bytes), .of(u8), @returnAddress()); +} + +/// Gives libc's free memory back to the system, inside its heap too: after a +/// big result is formatted or a big pane torn down, glibc keeps what was freed +/// (a V8 Callstack page left 21 MiB free in the heap; this returned 20). +/// Walks the heap, so for rare, large events only. +pub fn trim() void { + if (comptime builtin.os.tag != .linux or builtin.abi.isMusl() or !builtin.link_libc) return; + const glibc = struct { + extern "c" fn malloc_trim(pad: usize) c_int; + }; + _ = glibc.malloc_trim(0); +} + +/// Marks a big region that is touched sparsely as not for huge pages. With +/// transparent huge pages on `always` (a common default), touching one byte +/// of a 2 MiB-aligned stretch makes all 2 MiB resident: the 9P runner's +/// slots and these arenas' first pages held 45 MiB of an idle session's +/// 71 MiB that way. Only the region given, never the whole process (a prctl +/// would reach every shell and server pardes starts). +pub fn sparse(region: []u8) void { + if (comptime builtin.os.tag != .linux) return; + const page = std.heap.pageSize(); + const start = std.mem.alignForward(usize, @intFromPtr(region.ptr), page); + const end = std.mem.alignBackward(usize, @intFromPtr(region.ptr) + region.len, page); + if (end <= start) return; + std.posix.madvise(@ptrFromInt(start), end - start, std.posix.MADV.NOHUGEPAGE) catch {}; +} + var pardes_fallback: SharedStackFallback = .{ .buffer = &pardes_buffer }; var frame_fallback: SharedStackFallback = .{ .buffer = &frame_buffer }; var tree_sitter_fallback: SharedStackFallback = .{ .buffer = &tree_sitter_buffer }; @@ -118,6 +215,7 @@ pub fn init(fallback: Allocator) Allocators { // a Debug build `fallback` is std.process.Init's gpa, a DebugAllocator // already, and a second one checked every block twice. const backing = if (debug_enabled) std.heap.page_allocator else fallback; + inline for (.{ &pardes_buffer, &frame_buffer, &tree_sitter_buffer, &image_buffer, &pdf_buffer, &lsp_query_buffer }) |buffer| sparse(buffer); pardes_fallback.fallback_allocator = backing; frame_fallback.fallback_allocator = backing; tree_sitter_fallback.fallback_allocator = backing; diff --git a/src/mini.zig b/src/mini.zig index ce291c99..8d8ea0b2 100644 --- a/src/mini.zig +++ b/src/mini.zig @@ -313,7 +313,21 @@ test "Mini publishes only complete snapshots and content replacement drops metad const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; var path_buf: [4096]u8 = undefined; const path = try std.fmt.bufPrint(&path_buf, "{s}/mini.txt", .{dir}); - try std.testing.checkAllAllocationFailures(std.testing.allocator, Case.run, .{path}); + // Growth that never resizes in place: whether a resize fits where it is + // depends on the heap's layout, and with it how many allocations a run + // makes, which checkAllAllocationFailures needs to be the same each run. + const NoResize = struct { + fn resize(_: *anyopaque, _: []u8, _: std.mem.Alignment, _: usize, _: usize) bool { + return false; + } + fn remap(_: *anyopaque, _: []u8, _: std.mem.Alignment, _: usize, _: usize) ?[*]u8 { + return null; + } + }; + const testing_vtable = std.testing.allocator.vtable; + const no_resize_vtable: std.mem.Allocator.VTable = .{ .alloc = testing_vtable.alloc, .resize = NoResize.resize, .remap = NoResize.remap, .free = testing_vtable.free }; + const backing: std.mem.Allocator = .{ .ptr = std.testing.allocator.ptr, .vtable = &no_resize_vtable }; + try std.testing.checkAllAllocationFailures(backing, Case.run, .{path}); } test "Mini refuses a file that is no UTF-8, before its decoding could panic" { diff --git a/src/modal.zig b/src/modal.zig index 82f1a3a0..ad06833f 100644 --- a/src/modal.zig +++ b/src/modal.zig @@ -989,13 +989,77 @@ pub fn lineCount(content: []const u8) usize { // byte offset of the start of line `row` (0-based). row may == lineCount() // (== content.len, the end). pub fn lineStartOffset(content: []const u8, row: usize) usize { + // Newlines counted 32 bytes at a time, the last block byte by byte: one + // indexOfScalarPos per line was a call per line, 7000 of them to find + // line 7000 of a source, for every cursor move, selection and language + // request there. + const block = 32; + const Block = @Vector(block, u8); var off: usize = 0; - var r: usize = 0; - while (r < row) : (r += 1) { - const nl = std.mem.indexOfScalarPos(u8, content, off, '\n') orelse return content.len; - off = nl + 1; + var left = row; + if (left == 0) return 0; + while (off + block <= content.len) : (off += block) { + const chunk: Block = content[off..][0..block].*; + const found: usize = @popCount(@as(u32, @bitCast(chunk == @as(Block, @splat('\n'))))); + if (found >= left) break; + left -= found; + } + while (off < content.len) : (off += 1) if (content[off] == '\n') { + left -= 1; + if (left == 0) return off + 1; + }; + return content.len; +} + +test "lineStartOffset by blocks and offsetAt agree with a line at a time" { + var prng: std.Random.DefaultPrng = .init(0x9e3779b9); + const random = prng.random(); + var buf: [300]u8 = undefined; + for (0..2000) |_| { + const len = random.uintLessThan(usize, buf.len); + for (buf[0..len]) |*b| b.* = if (random.uintLessThan(u8, 4) == 0) '\n' else 'a'; + const text = buf[0..len]; + for (0..len + 3) |row| { + var off: usize = 0; + var r: usize = 0; + const want = while (r < row) : (r += 1) { + off = (std.mem.indexOfScalarPos(u8, text, off, '\n') orelse break text.len) + 1; + } else off; + try std.testing.expectEqual(want, lineStartOffset(text, row)); + const cursor: Cursor = .{ .row = row, .col = random.uintLessThan(usize, 6) }; + const clamped = lineStartOffset(text, @min(row, cursorLineCount(text) - 1)); + const end = std.mem.indexOfScalarPos(u8, text, clamped, '\n') orelse text.len; + try std.testing.expectEqual(clamped + graphemeStart(text[clamped..end], @min(cursor.col, end - clamped)), offsetAt(text, cursor)); + // lineSpan, as it was: a line at a time, null past the last. + const span: ?LineSpan = span: { + if (text.len == 0) break :span null; + var start: usize = 0; + for (0..row) |_| start = (std.mem.indexOfScalarPos(u8, text, start, '\n') orelse break :span null) + 1; + if (start == text.len and !(row == 0 or text[text.len - 1] == '\n')) break :span null; + break :span .{ .start = start, .end = std.mem.indexOfScalarPos(u8, text, start, '\n') orelse text.len }; + }; + try std.testing.expectEqual(span, lineSpan(text, row)); + // rangeBytes, as it was: each line looked for from the top, twice. + const other: Cursor = .{ .row = random.uintLessThan(usize, len + 3), .col = random.uintLessThan(usize, 6) }; + var lo = cursor; + var hi = other; + if (hi.row < lo.row or (hi.row == lo.row and hi.col < lo.col)) std.mem.swap(Cursor, &lo, &hi); + const lo_line = lineSlice(text, lo.row); + const hi_line = lineSlice(text, hi.row); + const s0 = lineStartOffset(text, lo.row) + graphemeStart(lo_line, @min(lo.col, lo_line.len)); + var e0 = lineStartOffset(text, hi.row) + graphemeStart(hi_line, @min(hi.col, hi_line.len)); + if (e0 < text.len) e0 = nextGrapheme(text, e0); + const got = rangeBytes(text, cursor, other); + try std.testing.expectEqual(s0, got.s); + try std.testing.expectEqual(@max(s0, e0), got.e); + } } - return off; +} + +/// The line that starts at `start` (lineSlice's, once its start is known). +fn lineFrom(content: []const u8, start: usize) []const u8 { + if (start >= content.len) return ""; + return content[start .. std.mem.indexOfScalarPos(u8, content, start, '\n') orelse content.len]; } // the text of line `row` (no terminator), a slice into `content`. @@ -1011,23 +1075,29 @@ pub fn lineSlice(content: []const u8, row: usize) []const u8 { /// A bounded scan of one line; null if the row does not exist. pub const LineSpan = struct { start: usize, end: usize }; +/// Just past the `row`-th newline; null if the text has fewer. +pub fn lineStartExact(content: []const u8, row: usize) ?usize { + const at = lineStartOffset(content, row); + // At the end: either the row-th newline was the last byte, or there were fewer. + if (at == content.len and std.mem.count(u8, content, "\n") < row) return null; + return at; +} + pub fn lineSpan(content: []const u8, row: usize) ?LineSpan { // Match lineCount: empty content has no lines; a trailing newline adds one. if (content.len == 0) return null; - var start: usize = 0; - var r: usize = 0; - while (r < row) : (r += 1) { - const nl = std.mem.indexOfScalarPos(u8, content, start, '\n') orelse return null; - start = nl + 1; - } - if (start > content.len) return null; + const start = lineStartExact(content, row) orelse return null; if (start == content.len and !(row == 0 or content.len == 0 or content[content.len - 1] == '\n')) return null; const end = std.mem.indexOfScalarPos(u8, content, start, '\n') orelse content.len; return .{ .start = start, .end = end }; } -fn spliceAlloc(alloc: std.mem.Allocator, content: []const u8, start: usize, end: usize, replacement: []const u8) ![]u8 { - const out = try alloc.alloc(u8, content.len - (end - start) + replacement.len); +pub fn spliceAlloc(alloc: std.mem.Allocator, content: []const u8, start: usize, end: usize, replacement: []const u8) ![]u8 { + // Raw: every byte is written below, where `alloc` fills a safe build's + // new memory first, a whole file's worth per keystroke. + const len = content.len - (end - start) + replacement.len; + if (len == 0) return alloc.alloc(u8, 0); + const out = (alloc.rawAlloc(len, .of(u8), @returnAddress()) orelse return error.OutOfMemory)[0..len]; @memcpy(out[0..start], content[0..start]); @memcpy(out[start..][0..replacement.len], replacement); @memcpy(out[start + replacement.len ..], content[end..]); @@ -1036,13 +1106,18 @@ fn spliceAlloc(alloc: std.mem.Allocator, content: []const u8, start: usize, end: /// insert `text` at (row, col). col is clamped to the line length. pub fn insertAt(alloc: std.mem.Allocator, content: []const u8, c: Cursor, text: []const u8) ![]u8 { + const off = insertOffset(content, c); + return spliceAlloc(alloc, content, off, off, text); +} + +/// Where insertAt puts its text: col clamped to the line, no further. +pub fn insertOffset(content: []const u8, c: Cursor) usize { // Only an out-of-range row requires counting the whole document. const span = lineSpan(content, c.row) orelse blk: { const last = lineCount(content) -| 1; break :blk lineSpan(content, last) orelse LineSpan{ .start = content.len, .end = content.len }; }; - const off = span.start + @min(c.col, span.end - span.start); - return spliceAlloc(alloc, content, off, off, text); + return span.start + @min(c.col, span.end - span.start); } // delete the character at (row, col). no-op if col is past the line end. @@ -1105,12 +1180,15 @@ fn rangeBytes(content: []const u8, a: Cursor, b: Cursor) struct { s: usize, e: u lo = b; hi = a; } - const lo_line = lineSlice(content, lo.row); - const hi_line = lineSlice(content, hi.row); + // Each line found once, the second from the first. + const lo_start = lineStartOffset(content, lo.row); + const hi_start = if (hi.row == lo.row) lo_start else lo_start + lineStartOffset(content[lo_start..], hi.row - lo.row); + const lo_line = lineFrom(content, lo_start); + const hi_line = lineFrom(content, hi_start); const lo_col = graphemeStart(lo_line, @min(lo.col, lo_line.len)); const hi_col = graphemeStart(hi_line, @min(hi.col, hi_line.len)); - const s = lineStartOffset(content, lo.row) + lo_col; - var e = lineStartOffset(content, hi.row) + hi_col; + const s = lo_start + lo_col; + var e = hi_start + hi_col; if (e < content.len) e = nextGrapheme(content, e); // include the grapheme under the head return .{ .s = s, .e = @max(s, e) }; } @@ -1138,12 +1216,12 @@ pub fn clearLine(alloc: std.mem.Allocator, content: []const u8, row: usize) ![]u // paste `text` as a new line BELOW `row`. Multiline `text` becomes several lines. pub fn pasteLineBelow(alloc: std.mem.Allocator, content: []const u8, row: usize, text: []const u8) ![]u8 { - const n = lineCount(content); - const off = if (row + 1 < n) lineStartOffset(content, row + 1) else content.len; + // The next line's start, or the end: no whole-text line count to know which. + const off = lineStartExact(content, row + 1) orelse content.len; const suffix_newline = off < content.len or (content.len > 0 and content[content.len - 1] == '\n'); const prefix_newline = !suffix_newline and off > 0; const extra: usize = @intFromBool(suffix_newline or prefix_newline); - const out = try alloc.alloc(u8, content.len + text.len + extra); + const out = try @import("memory.zig").unfilled(alloc, content.len + text.len + extra); var write: usize = 0; @memcpy(out[write..][0..off], content[0..off]); write += off; @@ -1393,8 +1471,10 @@ pub fn positionAt(text: []const u8, off: usize) Cursor { /// (row, col) -> clamped gap offset; col == line length lands ON the '\n' pub fn offsetAt(text: []const u8, c: Cursor) usize { - const row = @min(c.row, cursorLineCount(text) - 1); - const s = lineStartOffset(text, row); + // A row past the last is the last: found back from the end, where + // counting every line of the text to clamp it cost a pass over all of it. + var s = lineStartOffset(text, c.row); + if (s == text.len) s = if (std.mem.lastIndexOfScalar(u8, text, '\n')) |nl| nl + 1 else 0; // lineEndOffset(text, row) inlined: it starts by walking to `row` again, // and we are already standing there const e = std.mem.indexOfScalarPos(u8, text, s, '\n') orelse text.len; @@ -1783,15 +1863,6 @@ test "selection textobjects distinguish words and paragraph boundaries" { try std.testing.expectEqual(@as(usize, 7), r.head); } -/// leading-whitespace visual width (tab -> next multiple of INDENT_W) -pub fn indentWidth(line: []const u8) usize { - var w: usize = 0; - for (line) |ch| { - if (ch == ' ') w += 1 else if (ch == '\t') w = (w / INDENT_W + 1) * INDENT_W else break; - } - return w; -} - /// A line's indent as it is, tabs and spaces both, as acme's autoindent /// copies it: what o/O/insert-newline give the new line. pub fn indentText(line: []const u8) []const u8 { diff --git a/src/mouse.zig b/src/mouse.zig index 76c65a16..eeb987b2 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -1114,7 +1114,9 @@ fn mirrorTtySelection(p: *Pardes, pane: *Pane) void { /// second selects what edit.doubleClickRange says, from the caret the click /// left. A plain click still puts the caret on its cell. fn doubleClick(p: *Pardes, id: usize, t: *panes.Text, on_tag: bool, row: i32, col: i32) void { - const now = clockMs(); + // The host's clock, which every host keeps (a libc clock is no clock on + // the web or the board) and a test's virtual one replaces. + const now: i64 = @intCast(p.now_ns / std.time.ns_per_ms); const prev = p.last_click; p.last_click = .{ .id = id, .on_tag = on_tag, .row = row, .col = col, .ms = now }; const c = prev orelse return; @@ -1160,13 +1162,6 @@ fn sweepPoint(p: *Pardes, pane: *panes.Pane, r: i32, c: i32) ?modal.Cursor { return .{ .row = @intCast(w.line), .col = @intCast(@max(0, col)) }; } -fn clockMs() i64 { - if (comptime !pardes.hosted) return 0; - var ts: std.c.timespec = undefined; - if (std.c.clock_gettime(.MONOTONIC, &ts) != 0) return 0; - return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000); -} - fn dragRelease(p: *Pardes, button: Mouse.Button) void { // A different button's release belongs to a chord or another host // stream; only the button which began this gesture may end it. diff --git a/src/ninep/addr.zig b/src/ninep/addr.zig index 86d2d49e..7753c94d 100644 --- a/src/ninep/addr.zig +++ b/src/ninep/addr.zig @@ -239,21 +239,15 @@ pub const Addr = struct { k = @intFromBool(a.text[p] == '\n'); p += 1; } - while (k < n) { - if (p >= nc) { + if (k < n) { + p = nthLineAfter(a.text, p, n - k) orelse { a.err = e_range; return null; - } - if (a.text[p] == '\n') k += 1; - p += 1; + }; } p1 = p; } - while (p < nc) { - const ch = a.text[p]; - p += 1; - if (ch == '\n') break; - } + p = if (std.mem.indexOfScalarPos(u8, a.text, p, '\n')) |nl| nl + 1 else nc; return .{ .q0 = clip(p1), .q1 = clip(p) }; } @@ -678,3 +672,31 @@ test "a line just past the last newline is an empty one there, as sam's lineaddr try testing.expectEqual(Status.ok, th.wr(p, Node.of(th.serialOf(p), .ctl), "Edit 1i/header/\n").reply.status); try testing.expectEqualStrings("header", p.panes[0].?.file.?.content); } + +/// Just past the `count`-th newline at or after `from`; null if the text has +/// fewer. Counted a block at a time (modal.lineStartOffset), where a byte at +/// a time made `echo 7000 > addr` walk every byte above line 7000. +fn nthLineAfter(text: []const u8, from: usize, count: usize) ?usize { + return from + (modal.lineStartExact(text[from..], count) orelse return null); +} + +test "nthLineAfter finds what a byte at a time finds" { + var prng: std.Random.DefaultPrng = .init(0x51ab); + const random = prng.random(); + var buf: [200]u8 = undefined; + for (0..3000) |_| { + const len = random.uintLessThan(usize, buf.len); + for (buf[0..len]) |*b| b.* = if (random.uintLessThan(u8, 3) == 0) '\n' else 'x'; + const text = buf[0..len]; + const from = random.uintLessThan(usize, len + 1); + const count = 1 + random.uintLessThan(usize, 40); + var p = from; + var k: usize = 0; + const want: ?usize = while (k < count) { + if (p >= text.len) break null; + if (text[p] == '\n') k += 1; + p += 1; + } else p; + try std.testing.expectEqual(want, nthLineAfter(text, from, count)); + } +} diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 733d9c8e..480c1dc7 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -4684,6 +4684,10 @@ test "what a /pager open writes after its directory is the text: plain in the bo // An edit drops the colours (pager.zig's ponytail). try testing.expectEqual(Status.ok, call(p, .{ .tag = 6, .op = .write, .node = Node.of(pn.serial, .body), .data = "more\n" }).reply.status); try testing.expectEqual(@as(usize, 0), f.pager_spans.len); + // Undone back to the paged text: its colours come back with it. + panes.File.undo(p, pn); + try testing.expectEqualStrings("red /a\nNext\n", f.content); + try testing.expectEqual(@as(usize, 2), f.pager_spans.len); // PagerColor off, and an open closed with no read: the same text, plain, // in at the editor's next step (a close through a mount never waits). diff --git a/src/panes.zig b/src/panes.zig index 7ce85419..b535993e 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -133,6 +133,9 @@ pub const Pane = struct { /// Its pty is still open: a job the command left in the background may /// be printing to it, and a reuse would hang it up. command_pty: bool = false, + /// Its child pages as a terminal's does (`pardes -`, a +Pager), not + /// through cat: Look's `git show` of a commit (look.lookCommit). + command_pages: bool = false, /// The shell a terminal runs when it is not the configured one (`Tty /// fish`), owned. shell: ?[]u8 = null, diff --git a/src/pardes.zig b/src/pardes.zig index aaa9d177..c2a3ba21 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -478,6 +478,7 @@ pub const Loc = struct { }; test { + _ = @import("modal.zig"); _ = @import("tagline.zig"); _ = @import("hunks.zig"); _ = @import("builtins_json.zig"); @@ -4645,6 +4646,10 @@ pub const Pardes = struct { /// The last query asked (Lspwhy explains it): its kind, argument, and /// the pane and place it was asked at. lsp_last: ?struct { kind: lsp.Kind, arg: Effect.Buf(128), serial: u32, offset: u32 } = null, + /// The Callstack page `+Callstack` shows stopped short: its file's pane, + /// the place it was asked at, and the direct caller the next page starts + /// at. Callstack run in `+Callstack` asks for it. + callstack_more: ?struct { serial: u32, offset: u32, next: Effect.Buf(128) } = null, lsp_wait: ?struct { id: u32, kind: lsp.Kind, @@ -5168,10 +5173,13 @@ pub const Pardes = struct { } fn reapPanes(p: *Pardes) void { + var reaped = false; for (&p.retired_panes.previous) |*slot| if (slot.*) |pane| { p.teardownPane(pane); slot.* = null; + reaped = true; }; + if (reaped) memory.trim(); p.retired_panes.previous = p.retired_panes.current; p.retired_panes.current = @splat(null); } @@ -5544,7 +5552,7 @@ pub const Pardes = struct { p.invalidate(); look.invalidateLookHover(p, id); const applied = p.applyWatchedFileChanged(id, bytes); - _ = p.scratch.reset(.retain_capacity); + _ = p.scratch.reset(.{ .retain_with_limit = memory.limits.scratch_kept }); p.sync(); return applied; } @@ -6000,7 +6008,7 @@ pub const Pardes = struct { // A pty streaming into an unwatched session spent most of its time // drawing what nobody looked at. if (v.watched) |f| if (!f(h.ctx)) return; - _ = p.frame_arena.reset(.retain_capacity); + _ = p.frame_arena.reset(.{ .retain_with_limit = memory.limits.frame_kept }); const surface = try p.render(p.frame_arena.allocator()); if (v.present) |f| f(h.ctx, surface); // Settled before post_present: a shell ticks there, and what that @@ -6202,7 +6210,7 @@ pub const Pardes = struct { look.advanceLookHover(p); }, } - _ = p.scratch.reset(.retain_capacity); + _ = p.scratch.reset(.{ .retain_with_limit = memory.limits.scratch_kept }); p.sync(); p.fsReport(); ctlfs.events.announce(p); @@ -6777,6 +6785,19 @@ pub const Pardes = struct { pub const SavePath = Effect.Buf(effect_path_cap); pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8) void { + p.lspRequestAt(asked, kind, arg_in, null); + } + + /// The next page of the Callstack `+Callstack` shows, asked where the + /// first was. + pub fn callstackMore(p: *Pardes, from: usize) void { + const more = p.callstack_more orelse return p.reportFailure(from, "Callstack: this is the last page; run it in a file to start again"); + const id = p.paneBySerial(more.serial) orelse return p.reportFailure(from, "Callstack: the file it was asked in is closed"); + p.lspRequestAt(id, .callstack, more.next.slice(), more.offset); + } + + /// `lspRequest` at byte `at` of the pane's file rather than its cursor. + fn lspRequestAt(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8, at_byte: ?u32) void { var arg = arg_in; if (!normal.multiOnce(p)) return; // one question per keystroke, from the primary // Lspwhy narrates the last query where it was asked -- that pane's @@ -6800,7 +6821,7 @@ pub const Pardes = struct { (!zig_buf and std.mem.indexOfAny(u8, arg, " \t\r\n\"\\") != null)) return p.reportFailure(id, std.fmt.bufPrint(&said, "Rename: {s} is no name", .{arg}) catch "Rename: no name"); } - var off = if (pane.file) |f| modal.offsetAt(f.content, .{ + var off = if (at_byte) |at| @min(at, if (pane.file) |f| f.content.len else 0) else if (pane.file) |f| modal.offsetAt(f.content, .{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)), }) else 0; @@ -7089,13 +7110,24 @@ pub const Pardes = struct { } const dir = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice(); - const content = p.gpa.dupe(u8, rows) catch return; + // A Callstack page that stops short ends in its marker: said as a + // row naming the word that shows the next page, and kept. + if (w.kind == .callstack) p.callstack_more = null; + const marker = if (w.kind == .callstack) std.mem.lastIndexOf(u8, rows, lsp.callstack_more) else null; + const content = if (marker) |at| more: { + var fields = std.mem.tokenizeAny(u8, rows[at + lsp.callstack_more.len ..], " \n"); + const next = fields.next() orelse ""; + const shown = fields.next() orelse "?"; + if (p.lsp_last) |last| p.callstack_more = .{ .serial = w.serial, .offset = last.offset, .next = .from(next) }; + break :more std.fmt.allocPrint(p.gpa, "{s}… {s} callers on this page, more after them: Callstack here shows the next page\n", .{ rows[0..at], shown }) catch return; + } else p.gpa.dupe(u8, rows) catch return; const serial_before = p.next_serial; p.fs.refilled = null; panes.Output.fillResults(p, w.pane, dir, from, w.arg.slice(), content, null) catch |err| { p.reportError(w.pane, "language response", err); return; }; + if (rows.len >= 1 << 20) memory.trim(); // What a 9P write that asked it answers: the pane the rows are in // (a multi-file Rename's preview, Lspinfo's +Lsp), made or filled // again, not the pane it was asked from. diff --git a/src/regexp.zig b/src/regexp.zig index 4cbca57e..6d281859 100644 --- a/src/regexp.zig +++ b/src/regexp.zig @@ -283,7 +283,10 @@ pub const Regex = struct { /// its top level and every branch starts with `^`; null when it is not /// one, or no branch does. fn anchoredAlternation(pat: []const u8, out: *[5 * max_ops + 2]u8) error{ Bad, Mixed }!?[]const u8 { - var bars: [16]usize = undefined; + // No rewrite is longer than `out`, so neither is any pattern it + // takes, nor its count of bars. + if (pat.len > out.len) return error.Bad; + var bars: [5 * max_ops + 2]u16 = undefined; var n: usize = 0; var depth: usize = 0; var in_class = false; @@ -301,8 +304,7 @@ pub const Regex = struct { } else if (c == ')') { depth -|= 1; } else if (c == '|' and depth == 0) { - if (n == bars.len) return error.Bad; - bars[n] = i; + bars[n] = @intCast(i); n += 1; } } @@ -518,6 +520,9 @@ test "a ^ after | anchors that branch: ^def|^ finds a line that starts either w try std.testing.expectError(error.Mixed, Regex.compile("^def|x")); var plain = try Regex.compile("a|b"); try std.testing.expectEqual(@as(usize, 7), (try plain.find(text, 0, text.len, text.len)).?.start); + // Seventeen branches and more are a pattern like any other. + var many = try Regex.compile("q|r|s|t|u|v|w|x|y|z|k|l|m|n|o|p|j|b"); + try std.testing.expectEqual(@as(usize, 0), (try many.find(text, 0, text.len, text.len)).?.start); } test "a quoted backslash before n is no newline, and a class ends where mvzr ends it" { diff --git a/src/sam_edit.zig b/src/sam_edit.zig index f6253c89..94b76816 100644 --- a/src/sam_edit.zig +++ b/src/sam_edit.zig @@ -259,6 +259,10 @@ fn fail(why: *Why, comptime fmt: []const u8, args: anytype) Failure { // ---- parsing: edit.c ---- +/// Commands one Edit may nest, loops (`x`, `y`, `g`, `v`, `X`, `Y`) and +/// braces together: each level is a stack frame holding a compiled regex. +pub const max_nest = 32; + const Parser = struct { arena: std.mem.Allocator, src: []const u8, @@ -271,6 +275,9 @@ const Parser = struct { open_text: bool = false, /// The address being read had a `,` after a `"re"`. file_comma: bool = false, + /// Commands open around the one being read, braces and loops alike: + /// each is a frame of `parse` and later of `execIn`, so it is bounded. + depth: u8 = 0, why: *Why, fn getch(ps: *Parser) ?u8 { @@ -460,6 +467,9 @@ const Parser = struct { /// edit.c:467, parsecmd. fn parse(ps: *Parser, nest: u32) Failure!?*Cmd { + if (ps.depth >= max_nest) return fail(ps.why, "commands nested more than {d} deep", .{max_nest}); + ps.depth += 1; + defer ps.depth -= 1; var file_re: ?[]const u8 = null; ps.file_comma = false; const a = try ps.address(&file_re); @@ -1163,6 +1173,11 @@ test "an Edit that fails halfway changes nothing, and says why in acme's words" .{ "e /tmp/x", "can't open /tmp/x: no files here" }, .{ "\"zz\" p", "no file matches \"zz\"" }, .{ ",s/(a)/\\1/", "no \\1: mvzr keeps no submatches" }, + .{ comptime deep: { + var loops: []const u8 = ""; + for (0..40) |_| loops = loops ++ ",x/a/"; + break :deep loops ++ "d"; + }, "commands nested more than 32 deep" }, .{ "1 m 1,2", "move overlaps itself" }, .{ ",x/(^|\\n)foo/d", "bad regular expression: in a pattern with \\n, ^ can only come first and $ only just before a \\n" }, }) |c| { diff --git a/src/selection_pipe.zig b/src/selection_pipe.zig index c3e5e3a6..229b3d67 100644 --- a/src/selection_pipe.zig +++ b/src/selection_pipe.zig @@ -401,7 +401,7 @@ pub fn runIn( }, }; child.stdin = null; // writer_context owns and closes this endpoint - var writer: ?std.Thread = std.Thread.spawn(.{}, writeInput, .{writer_context}) catch { + var writer: ?std.Io.Future(void) = io.concurrent(writeInput, .{writer_context}) catch { writer_context.file.close(io); gpa.free(writer_context.input); gpa.destroy(writer_context); @@ -410,8 +410,9 @@ pub fn runIn( }; // On every early return (a timeout, a ceiling) the answer goes at once: // the group is killed and the shell left to be reaped elsewhere - // (abandon), and the writer, which owns its input, let go. - defer if (writer) |thread| thread.detach(); + // (abandon), and the writer's write canceled (it closes and frees what + // it owns as it ends). + defer if (writer) |*w| w.cancel(io); defer if (child.id != null) abandonNow(io, &child, pid); defer if (token != 0) Running.remove(pid); if (token != 0 and !Running.add(token, pid)) return fail.k(.signal); @@ -443,7 +444,9 @@ pub fn runIn( multi_reader.checkAnyError() catch return fail.k(.io); if (token != 0) Running.remove(pid); const term = child.wait(io) catch return fail.k(.io); - writer.?.join(); + // A cancel of this job reaches the write too: a grandchild that keeps + // stdin open and never reads holds no worker. + writer.?.await(io); writer = null; const stdout = multi_reader.toOwnedSlice(0) catch return fail.k(.io); diff --git a/src/surface.zig b/src/surface.zig index e67cf21c..d6ec016d 100644 --- a/src/surface.zig +++ b/src/surface.zig @@ -533,11 +533,6 @@ pub const Surface = struct { return s.cell_diffs[@as(usize, y) * s.cols + x].changed(); } - pub fn panelCellDiff(s: *const Surface, x: u16, y: u16) PanelCellDiff { - if (!s.hasPanelDiff() or x >= s.cols or y >= s.rows) return .unchanged; - return s.cell_diffs[@as(usize, y) * s.cols + x]; - } - pub fn at(s: *Surface, x: u16, y: u16) *Cell { std.debug.assert(x < s.cols and y < s.rows); return &s.cells[@as(usize, y) * s.cols + x]; diff --git a/src/terminal.zig b/src/terminal.zig index 33ad22e6..05054521 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -1,4 +1,4 @@ -//! A terminal pane: its VT emulator and replay, prompt rows, the edit overlay +//! A terminal pane: its VT emulator, prompt rows, the edit overlay //! typed over shell rows, and the Filter that recolours output to the theme. const panes = @import("panes.zig"); const std = @import("std"); @@ -141,16 +141,9 @@ pub const MarkedHandler = if (enabled) struct { } } else void; -pub const Replay = struct { - bytes: [1024 * 1024]u8 = undefined, - head: usize = 0, - len: usize = 0, -}; - pub const State = struct { vt: VtSlot, stream: StreamSlot, - replay: Replay, reply: [256]u8 = undefined, reply_len: u16 = 0, /// The grid cell the program last heard the mouse at, so motion is @@ -613,8 +606,6 @@ pub fn create(gpa: std.mem.Allocator, cols: u16, rows: u16) !*Pane { .kitty_image_storage_limit = if (images_enabled) TerminalImages.storage_limit else 0, }); state.stream = .init(.{ .handler = .{ .inner = state.vt.vtHandler() }, .allocator = gpa }); - state.replay.head = 0; - state.replay.len = 0; state.reply_len = 0; state.mouse_cell = null; state.images = if (images_enabled) .{} else {}; @@ -678,43 +669,12 @@ pub fn restore(p: *Pardes, src: dump.Pane, live: bool) !*Pane { return pane; } -/// Feed the emulator and retain the bounded suffix a dump can replay. Live -/// output and restoration share this byte path, then apply different views. +/// Feed the emulator. Live output and restoration share this byte path, +/// then apply different views. fn ingest(pane: *Pane, bytes: []const u8) void { - const state = pane.terminal.?; - const replay = &state.replay; - if (bytes.len >= replay.bytes.len) { - const kept = bytes[bytes.len - replay.bytes.len ..]; - @memcpy(&replay.bytes, kept); - replay.head = 0; - replay.len = replay.bytes.len; - } else { - const overflow = bytes.len -| (replay.bytes.len - replay.len); - replay.head = (replay.head + overflow) % replay.bytes.len; - replay.len -= overflow; - const tail = (replay.head + replay.len) % replay.bytes.len; - const first = @min(bytes.len, replay.bytes.len - tail); - @memcpy(replay.bytes[tail..][0..first], bytes[0..first]); - @memcpy(replay.bytes[0 .. bytes.len - first], bytes[first..]); - replay.len += bytes.len; - } - state.stream.nextSlice(bytes); + pane.terminal.?.stream.nextSlice(bytes); } -/// Return the replay ring in chronological order. Wrapped records are copied -/// into `allocator`; contiguous records remain a borrowed slice of the pane. -fn replayBytes(pane: *const Pane, allocator: std.mem.Allocator) ![]const u8 { - const state = pane.terminal orelse return &.{}; - const replay = &state.replay; - if (replay.len == 0) return &.{}; - if (replay.head + replay.len <= replay.bytes.len) - return replay.bytes[replay.head..][0..replay.len]; - const out = try allocator.alloc(u8, replay.len); - const first = replay.bytes.len - replay.head; - @memcpy(out[0..first], replay.bytes[replay.head..]); - @memcpy(out[first..], replay.bytes[0 .. replay.len - first]); - return out; -} test "replay ownership is terminal-only and construction rolls back on allocation failure" { const Case = struct { @@ -753,7 +713,6 @@ test "document construction allocates only the pane and has inert terminal defau try std.testing.expectEqual(GridCursor{}, gridCursor(pane)); try std.testing.expectEqual(Scrollbar{}, scrollbar(pane)); try std.testing.expectEqualStrings("", try screenTextAlloc(pane, allocator)); - try std.testing.expectEqualStrings("", try replayBytes(pane, allocator)); try std.testing.expect(!failing.has_induced_failure); } @@ -779,46 +738,18 @@ test "terminal state keeps parser fragments and sends emulator replies through i } try std.testing.expectEqual(@as(usize, 1), replies); try std.testing.expectEqual(@as(u16, 0), state.reply_len); - try std.testing.expectEqualStrings("\x1b[6n", try replayBytes(pane, std.testing.allocator)); } -test "replay keeps a bounded chronological suffix across large writes and wrapping" { - if (comptime !enabled) return error.SkipZigTest; - const gpa = std.testing.allocator; - const pane = try create(gpa, 40, 12); - defer gpa.destroy(pane); - defer deinitEmulator(pane, gpa); - try std.testing.expectEqualStrings("", try replayBytes(pane, gpa)); - ingest(pane, "hello"); - const small = try replayBytes(pane, gpa); - try std.testing.expectEqualStrings("hello", small); - try std.testing.expectEqual(@intFromPtr(&pane.terminal.?.replay.bytes), @intFromPtr(small.ptr)); - - const capacity = pane.terminal.?.replay.bytes.len; - const input = try gpa.alloc(u8, capacity + 7); - defer gpa.free(input); - @memset(input, 0); - const ending = "\x1b[31mred\x1b[0m\r\n"; - @memcpy(input[input.len - ending.len ..], ending); - ingest(pane, input); - try std.testing.expectEqualSlices(u8, input[7..], try replayBytes(pane, gpa)); - ingest(pane, "next\r\n"); - const wrapped = try replayBytes(pane, gpa); - defer gpa.free(wrapped); - try std.testing.expectEqual(capacity, wrapped.len); - try std.testing.expectEqualSlices(u8, input[7 + "next\r\n".len ..], wrapped[0 .. capacity - "next\r\n".len]); - try std.testing.expectEqualStrings("next\r\n", wrapped[capacity - "next\r\n".len ..]); -} - -test "replay restores terminal cells from the retained stream" { +test "a terminal stream restores the cells it drew" { if (comptime !enabled) return error.SkipZigTest; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = p.panes[0].?; - feedOutput(p, pane, "\x1b[31mred\x1b[0m\r\ncafé\r\n"); - const encoded = try dump.encodeBytes(gpa, try replayBytes(pane, gpa)); + const drawn = "\x1b[31mred\x1b[0m\r\ncafé\r\n"; + feedOutput(p, pane, drawn); + const encoded = try dump.encodeBytes(gpa, drawn); defer gpa.free(encoded); const restored = try restore(p, .{ .kind = .terminal, @@ -835,7 +766,6 @@ test "replay restores terminal cells from the retained stream" { const after = try screenTextAlloc(restored, gpa); defer gpa.free(after); try std.testing.expectEqualStrings(before, after); - try std.testing.expectEqualSlices(u8, try replayBytes(pane, gpa), try replayBytes(restored, gpa)); } test "a restored command pane comes back finished, its command not run again" { diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 4cd1bc9a..afc0dbf0 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -34,6 +34,8 @@ var kitty_shm = std.atomic.Value(bool).init(false); var kitty_shm_probing = std.atomic.Value(bool).init(false); const kitty_shm_probe_id = 0x7fff_fff1; var kitty_shm_serial: u32 = 0; +/// Transmissions an unread shm segment outlives before it is removed. +const kitty_shm_window = 64; fn kittyShmName(buf: []u8, n: u32) ![:0]const u8 { return std.fmt.bufPrintSentinel(buf, "/pardes-{d}-{d}", .{ libc.getpid(), n }, 0); @@ -1787,6 +1789,13 @@ const Shell = struct { if (!s.kitty.contains(key) and vx.caps.kitty_graphics and kitty_shm.load(.acquire)) shm: { var buf: [64]u8 = undefined; kitty_shm_serial +%= 1; + // Bounded: a segment this many transmissions old was never + // read (a terminal reads one as its command arrives), and a + // tmpfs holds it in memory until it goes. + if (kitty_shm_serial > kitty_shm_window) { + var old_buf: [64]u8 = undefined; + if (kittyShmName(&old_buf, kitty_shm_serial - kitty_shm_window)) |old| _ = libc.shm_unlink(old) else |_| {} + } const name = kittyShmName(&buf, kitty_shm_serial) catch break :shm; if (!kittyShmWrite(name, place.rgba)) break :shm; if (vx.transmitLocalImagePath(s.gpa, s.tty.writer(), name, @intCast(place.iw), @intCast(place.ih), .shared_mem, .rgba) catch null) |handle| @@ -2010,7 +2019,7 @@ const Shell = struct { old.future.cancel(s.io) catch {}; s.lsp_task = null; } - const future = s.io.concurrent(lspWorker, .{ s.lsp_gpa, job, s.loop }) catch |err| { + const future = s.io.concurrent(lspWorker, .{ s.io, s.lsp_gpa, job, s.loop }) catch |err| { job.free(s.lsp_gpa); s.core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } }); return s.core.reportError(req.pane, "lsp", err); @@ -2144,9 +2153,9 @@ fn requestClipboard(vx: *vaxis.Vaxis, tty: *vaxis.Tty) void { vx.requestSystemClipboard(tty.writer()) catch {}; } -fn lspWorker(allocator: std.mem.Allocator, job: *host_io.Lsp.Job, loop: *Loop) anyerror!void { +fn lspWorker(io: std.Io, allocator: std.mem.Allocator, job: *host_io.Lsp.Job, loop: *Loop) anyerror!void { var sink: LspRowSink = .{ .allocator = allocator, .loop = loop }; - host_io.Lsp.work(allocator, job, &sink, LspRowSink.take); + host_io.Lsp.work(io, allocator, job, &sink, LspRowSink.take); } const LspRowSink = struct { @@ -2185,23 +2194,30 @@ fn watchFiles(io: std.Io, fd: c_int, loop: *Loop) anyerror!void { return; } const file: std.Io.File = .{ .handle = fd, .flags = .{ .nonblocking = false } }; - var read_buf: [4096]u8 = undefined; - var reader = file.readerStreaming(io, &read_buf); + // One buffer, read into directly: a Reader around it only added a second + // (and in a safe build, filled both as `undefined` on every start). + var buf: [4096]u8 = undefined; while (true) { - var buf: [4096]u8 = undefined; - var vec = [_][]u8{&buf}; - const n = reader.interface.readVec(&vec) catch break; + const n = file.readStreaming(io, &.{&buf}) catch break; if (n == 0) break; loop.postEvent(.files_changed) catch break; } } fn winchWatch(loop: *Loop, vx: *vaxis.Vaxis, tty: *vaxis.Tty) void { + winchWatchUntil(loop, vx, tty, null); +} + +/// A SIGWINCH watcher that ends: `stop` set, then a SIGWINCH sent to its +/// thread, wakes its sigwait and it returns, so whoever owns `loop` can join +/// it before the loop goes (attachSession's loop is on its stack). +fn winchWatchUntil(loop: *Loop, vx: *vaxis.Vaxis, tty: *vaxis.Tty, stop: ?*const std.atomic.Value(bool)) void { var set = posix.sigemptyset(); posix.sigaddset(&set, posix.SIG.WINCH); while (true) { var sig: c_int = 0; if (libc.sigwait(&set, &sig) != 0) continue; + if (stop) |flag| if (flag.load(.acquire)) return; if (vx.state.in_band_resize) continue; // terminal reports via CSI 48 const ws = tty.getWinsize() catch continue; loop.postEvent(.{ .winsize = ws }) catch {}; @@ -2285,12 +2301,11 @@ fn wakeFs(ctx: ?*anyopaque) void { } fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: u32, loop: *Loop) anyerror!void { - var read_buf: [0x10000]u8 = undefined; - var reader = pty.readerStreaming(io, &read_buf); + // One buffer, read into directly: a Reader around it only added a second + // (and in a safe build, filled both as `undefined` on every start). + var buf: [0x10000]u8 = undefined; while (true) { - var buf: [0x10000]u8 = undefined; - var vec = [_][]u8{&buf}; - const n = reader.interface.readVec(&vec) catch break; + const n = pty.readStreaming(io, &.{&buf}) catch break; if (n == 0) break; const bytes = try gpa.dupe(u8, buf[0..n]); loop.postEvent(.{ .pty_read = .{ .id = id, .gen = gen, .bytes = bytes } }) catch { @@ -2301,7 +2316,7 @@ fn readPty(io: std.Io, gpa: std.mem.Allocator, pty: std.Io.File, id: usize, gen: _ = loop.tryPostEvent(.{ .pty_eof = .{ .id = id, .gen = gen } }) catch {}; } -const max_paste_bytes: usize = 4 << 20; +const max_paste_bytes: usize = pardes.memory.limits.max_paste_bytes; fn pasteBytes(key: vaxis.Key) []const u8 { const text = key.text orelse ""; @@ -3023,7 +3038,13 @@ fn attachSession(init: std.process.Init, name: []const u8, tty: *vaxis.Tty, vx: startInput(&loop, &input_cache) catch |err| return .{ .lost = err }; defer stopInput(&loop); - (std.Thread.spawn(.{}, winchWatch, .{ &loop, vx, tty }) catch |err| return .{ .lost = err }).detach(); + var winch_stop: std.atomic.Value(bool) = .init(false); + const winch = std.Thread.spawn(.{}, winchWatchUntil, .{ &loop, vx, tty, &winch_stop }) catch |err| return .{ .lost = err }; + defer { + winch_stop.store(true, .release); + _ = libc.pthread_kill(winch.getHandle(), posix.SIG.WINCH); + winch.join(); + } vx.queryTerminalSend(tty.writer()) catch {}; return attachLoop(&a); diff --git a/test/lspbench.zig b/test/lspbench.zig index d0e25aee..08df9f4c 100644 --- a/test/lspbench.zig +++ b/test/lspbench.zig @@ -110,8 +110,13 @@ test "lspbench options reject unknown flags and multiple roots before probing" { try std.testing.expectError(error.MultipleRoots, Options.parse(&.{ "first", "--check", "second" })); } +/// The process's Io, for the queries: their waits are woken by the client's +/// reader threads, which a single-threaded Io cannot be. +var query_io: std.Io = undefined; + pub fn main(init: std.process.Init) !void { const gpa = std.heap.page_allocator; + query_io = init.io; const args = try init.minimal.args.toSlice(init.arena.allocator()); if (args.len > 1 and std.mem.eql(u8, args[1], "probe")) return probeCommand(init); @@ -171,13 +176,19 @@ fn checkResults(results: []const Result, required: usize) !void { for (results) |r| if (r.empty or !r.correct) return error.IncorrectProbe; } -fn runOnce(gpa: std.mem.Allocator, req: lsp.Req, expected: []const u8, r: *Result) !u64 { - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); +fn runOnce(gpa: std.mem.Allocator, req_in: lsp.Req, expected: []const u8, r: *Result) !u64 { + // The editor's own path (host_io.Lsp.work): the query in the fixed + // region reserved at startup, not a heap arena that maps its memory anew. + const memory = @import("pardes").memory; + const region = memory.takeLspQuery() orelse return error.QueryRegionBusy; + var arena: std.heap.FixedBufferAllocator = .init(region); + defer memory.giveLspQuery(arena.end_index); + var req = req_in; + req.budget = &arena; var out: std.Io.Writer.Allocating = .init(gpa); defer out.deinit(); const t0 = nowNs(); - try lsp.query(gpa, arena.allocator(), req, &out.writer); + try lsp.query(query_io, gpa, arena.allocator(), req, &out.writer); const ns = nowNs() -| t0; r.accept(out.written(), expected); return ns / 1000; @@ -341,6 +352,7 @@ extern "c" fn usleep(usec: c_uint) c_int; /// [--reps N] [--warm S]`, rows on stdout, the timing on stderr. fn probeCommand(init: std.process.Init) !void { const gpa = std.heap.page_allocator; + query_io = init.io; const arena = init.arena.allocator(); const io = std.Io.Threaded.global_single_threaded.io(); @@ -431,7 +443,7 @@ fn probeCommand(init: std.process.Init) !void { var scratch: std.heap.ArenaAllocator = .init(gpa); defer scratch.deinit(); const t0 = nowUs(); - try lsp.query(gpa, scratch.allocator(), .{ + try lsp.query(query_io, gpa, scratch.allocator(), .{ .kind = kind, .path = path, .source = source, diff --git a/test/panes.zig b/test/panes.zig index e98e3a54..1460b355 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -1913,9 +1913,6 @@ test "terminal output keeps following new rows after scrollback eviction" { try std.testing.expectEqualStrings("f", effect.write.bytes.slice()); try std.testing.expect(p.nextEffect() == null); } - const replay = &pane.terminal.?.replay; - try std.testing.expectEqual(replay.bytes.len, replay.len); - try std.testing.expect(replay.head > 0); } test "terminal edit stays on its surviving row when old scrollback is evicted" { diff --git a/test/perf-baseline-gui-debug.json b/test/perf-baseline-gui-debug.json index ffcd678f..a41c92b2 100644 --- a/test/perf-baseline-gui-debug.json +++ b/test/perf-baseline-gui-debug.json @@ -1 +1 @@ -{"harness":"15bee9f100e5ef64","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1744,"med_us":1832,"p90_us":2468,"max_us":2524},{"op":"render","fixture":"medium","min_us":88,"med_us":97,"p90_us":114,"max_us":115},{"op":"key-down","fixture":"medium","min_us":95,"med_us":98,"p90_us":104,"max_us":105},{"op":"key-right","fixture":"medium","min_us":92,"med_us":96,"p90_us":98,"max_us":105},{"op":"page-down","fixture":"medium","min_us":91,"med_us":95,"p90_us":97,"max_us":105},{"op":"wheel","fixture":"medium","min_us":87,"med_us":93,"p90_us":99,"max_us":100},{"op":"edit-char","fixture":"medium","min_us":1241,"med_us":1459,"p90_us":1691,"max_us":1724},{"op":"edit-twin","fixture":"medium","min_us":2592,"med_us":3003,"p90_us":3481,"max_us":3503},{"op":"body-2m","fixture":"medium","min_us":4576,"med_us":8262,"p90_us":15424,"max_us":17259},{"op":"body-appends","fixture":"medium","min_us":152003,"med_us":227268,"p90_us":272872,"max_us":326510},{"op":"deep-sel","fixture":"medium","min_us":82,"med_us":83,"p90_us":90,"max_us":93}]} +{"harness":"442f274a5da9136c","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2253,"med_us":2626,"p90_us":3065,"max_us":3090},{"op":"render","fixture":"medium","min_us":100,"med_us":103,"p90_us":103,"max_us":110},{"op":"key-down","fixture":"medium","min_us":102,"med_us":103,"p90_us":105,"max_us":113},{"op":"key-right","fixture":"medium","min_us":98,"med_us":104,"p90_us":108,"max_us":113},{"op":"page-down","fixture":"medium","min_us":103,"med_us":104,"p90_us":111,"max_us":114},{"op":"wheel","fixture":"medium","min_us":98,"med_us":100,"p90_us":102,"max_us":108},{"op":"edit-char","fixture":"medium","min_us":1251,"med_us":1940,"p90_us":2652,"max_us":3041},{"op":"edit-twin","fixture":"medium","min_us":2779,"med_us":3177,"p90_us":3366,"max_us":3657},{"op":"body-2m","fixture":"medium","min_us":5812,"med_us":11423,"p90_us":13681,"max_us":13758},{"op":"body-appends","fixture":"medium","min_us":153898,"med_us":241075,"p90_us":284518,"max_us":305761},{"op":"deep-sel","fixture":"medium","min_us":86,"med_us":91,"p90_us":94,"max_us":122}]} diff --git a/test/perf-baseline-tty-debug.json b/test/perf-baseline-tty-debug.json index b8e534c4..dc37e033 100644 --- a/test/perf-baseline-tty-debug.json +++ b/test/perf-baseline-tty-debug.json @@ -1 +1 @@ -{"harness":"15bee9f100e5ef64","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1747,"med_us":1912,"p90_us":2150,"max_us":2247},{"op":"render","fixture":"medium","min_us":89,"med_us":95,"p90_us":102,"max_us":104},{"op":"key-down","fixture":"medium","min_us":97,"med_us":101,"p90_us":107,"max_us":133},{"op":"key-right","fixture":"medium","min_us":93,"med_us":104,"p90_us":109,"max_us":112},{"op":"page-down","fixture":"medium","min_us":92,"med_us":96,"p90_us":106,"max_us":108},{"op":"wheel","fixture":"medium","min_us":90,"med_us":92,"p90_us":96,"max_us":96},{"op":"edit-char","fixture":"medium","min_us":1167,"med_us":1345,"p90_us":1483,"max_us":1627},{"op":"edit-twin","fixture":"medium","min_us":2319,"med_us":2921,"p90_us":3425,"max_us":3539},{"op":"body-2m","fixture":"medium","min_us":4333,"med_us":7752,"p90_us":15941,"max_us":17192},{"op":"body-appends","fixture":"medium","min_us":149149,"med_us":234177,"p90_us":285302,"max_us":295516},{"op":"deep-sel","fixture":"medium","min_us":83,"med_us":88,"p90_us":99,"max_us":119}]} +{"harness":"442f274a5da9136c","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2181,"med_us":2495,"p90_us":2621,"max_us":2660},{"op":"render","fixture":"medium","min_us":96,"med_us":98,"p90_us":102,"max_us":112},{"op":"key-down","fixture":"medium","min_us":101,"med_us":103,"p90_us":107,"max_us":108},{"op":"key-right","fixture":"medium","min_us":100,"med_us":112,"p90_us":118,"max_us":119},{"op":"page-down","fixture":"medium","min_us":97,"med_us":101,"p90_us":105,"max_us":107},{"op":"wheel","fixture":"medium","min_us":98,"med_us":100,"p90_us":108,"max_us":110},{"op":"edit-char","fixture":"medium","min_us":1377,"med_us":1842,"p90_us":2336,"max_us":2418},{"op":"edit-twin","fixture":"medium","min_us":2655,"med_us":3200,"p90_us":3321,"max_us":3660},{"op":"body-2m","fixture":"medium","min_us":5420,"med_us":10753,"p90_us":12826,"max_us":15385},{"op":"body-appends","fixture":"medium","min_us":153569,"med_us":232519,"p90_us":281625,"max_us":309036},{"op":"deep-sel","fixture":"medium","min_us":91,"med_us":98,"p90_us":111,"max_us":111}]} diff --git a/test/perf-baseline-tty-fast.json b/test/perf-baseline-tty-fast.json index 46125349..bd8f32dc 100644 --- a/test/perf-baseline-tty-fast.json +++ b/test/perf-baseline-tty-fast.json @@ -1 +1 @@ -{"harness":"15bee9f100e5ef64","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"fast","c_optimize":"fast","terminal_optimize":"fast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":1904,"med_us":2040,"p90_us":2290,"max_us":2600},{"op":"render","fixture":"medium","min_us":80,"med_us":83,"p90_us":88,"max_us":93},{"op":"key-down","fixture":"medium","min_us":81,"med_us":87,"p90_us":93,"max_us":109},{"op":"key-right","fixture":"medium","min_us":79,"med_us":82,"p90_us":86,"max_us":96},{"op":"page-down","fixture":"medium","min_us":79,"med_us":83,"p90_us":89,"max_us":93},{"op":"wheel","fixture":"medium","min_us":77,"med_us":79,"p90_us":82,"max_us":83},{"op":"edit-char","fixture":"medium","min_us":1139,"med_us":1338,"p90_us":1453,"max_us":1578},{"op":"edit-twin","fixture":"medium","min_us":2515,"med_us":2776,"p90_us":2879,"max_us":2907},{"op":"body-2m","fixture":"medium","min_us":4832,"med_us":7650,"p90_us":15076,"max_us":15371},{"op":"body-appends","fixture":"medium","min_us":165796,"med_us":240881,"p90_us":284919,"max_us":292573},{"op":"deep-sel","fixture":"medium","min_us":73,"med_us":75,"p90_us":83,"max_us":93}]} +{"harness":"442f274a5da9136c","build":{"compiler":"0.17.0","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"fast","c_optimize":"fast","terminal_optimize":"fast","platform":"tty","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"quic":false,"theme_animation":true,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400},{"name":"esp32p4","lines":12,"cols":240,"bytes":2892}],"cells":[{"op":"open","fixture":"medium","min_us":2283,"med_us":2611,"p90_us":2812,"max_us":2917},{"op":"render","fixture":"medium","min_us":89,"med_us":97,"p90_us":105,"max_us":119},{"op":"key-down","fixture":"medium","min_us":88,"med_us":95,"p90_us":100,"max_us":116},{"op":"key-right","fixture":"medium","min_us":90,"med_us":99,"p90_us":103,"max_us":106},{"op":"page-down","fixture":"medium","min_us":86,"med_us":90,"p90_us":96,"max_us":97},{"op":"wheel","fixture":"medium","min_us":85,"med_us":91,"p90_us":94,"max_us":101},{"op":"edit-char","fixture":"medium","min_us":1229,"med_us":1823,"p90_us":1874,"max_us":2101},{"op":"edit-twin","fixture":"medium","min_us":2196,"med_us":2745,"p90_us":2928,"max_us":2972},{"op":"body-2m","fixture":"medium","min_us":5606,"med_us":10369,"p90_us":14063,"max_us":14406},{"op":"body-appends","fixture":"medium","min_us":155867,"med_us":237195,"p90_us":289128,"max_us":306283},{"op":"deep-sel","fixture":"medium","min_us":82,"med_us":84,"p90_us":86,"max_us":91}]} diff --git a/test/perf.zig b/test/perf.zig index 7662d028..ab284739 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -665,8 +665,6 @@ fn measureTerm(op: TermOp, fx: TermFixture, reps: usize) !Cell { .row = pane.body.cur_row, .col = pane.body.cur_col, .edit_len = if (pane.ovl) |overlay| overlay.text.len else 0, - .replay_head = state.replay.head, - .replay_len = state.replay.len, .cols = pane.cols, .rows = pane.rows, }; @@ -689,22 +687,11 @@ fn measureTerm(op: TermOp, fx: TermFixture, reps: usize) !Cell { _ = try frame(core); const dt = nowNs() -| t0; switch (op) { - .render => if (pane.body.cur_row != before.row or pane.body.cur_col != before.col or - state.replay.head != before.replay_head or state.replay.len != before.replay_len) + .render => if (pane.body.cur_row != before.row or pane.body.cur_col != before.col) return error.RenderChangedTerminal, - .output => { - const capacity = state.replay.bytes.len; - if (term_chunk.len == 0 or term_chunk.len >= capacity) return error.InvalidOutputFixture; - const overflow = term_chunk.len -| (capacity - before.replay_len); - if (state.replay.len != @min(capacity, before.replay_len + term_chunk.len) or - state.replay.head != (before.replay_head + overflow) % capacity) - return error.OutputWasNotRecorded; - const start = (state.replay.head + state.replay.len - term_chunk.len) % capacity; - const first = @min(term_chunk.len, capacity - start); - if (!std.mem.eql(u8, term_chunk[0..first], state.replay.bytes[start..][0..first]) or - !std.mem.eql(u8, term_chunk[first..], state.replay.bytes[0 .. term_chunk.len - first])) - return error.WrongTerminalOutput; - }, + // What the output did to the screen is the snapshot suite's to + // check; here it is timed. + .output => if (term_chunk.len == 0) return error.InvalidOutputFixture, .resize_rows => if (pane.rows == before.rows or pane.cols != before.cols or state.vt.screens.active.pages.rows != pane.rows) return error.TerminalDidNotResize, .resize_cols => if (pane.cols == before.cols or pane.rows != before.rows or -- cgit v1.3 From a53a1aafb9804e943bdcd720c2bb688ecb90a888 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 23 Oct 2026 11:12:56 -0300 Subject: Audit (colours, drawing): one Surface.tint, shared colour maths, the helix copies of hand-ported themes removed The 22 _helix themes that duplicate a hand-written port are gone; monokai, ayu_dark and nord stay, since others inherit from them. Co-Authored-By: Claude Opus 5.5 --- docs/typ/themes.typ | 5 +- src/File.zig | 23 +--- src/Messages.zig | 10 -- src/Presentation.zig | 72 +++++------ src/animation.zig | 16 +-- src/body_layer.zig | 64 +++------- src/colors.zig | 123 +++++-------------- src/draw.zig | 25 +--- src/gui/gui.zig | 38 ++---- src/surface.zig | 193 ++++++++++++------------------ test/snapshots/themesel.golden | 28 ++--- tools/gen_themes.zig | 14 ++- vendor/themes/ayu_dark.toml | 92 -------------- vendor/themes/ayu_dark_helix.toml | 92 ++++++++++++++ vendor/themes/ayu_evolve.toml | 2 +- vendor/themes/ayu_light.toml | 94 --------------- vendor/themes/ayu_mirage.toml | 92 -------------- vendor/themes/catppuccin_frappe.toml | 35 ------ vendor/themes/catppuccin_latte.toml | 35 ------ vendor/themes/catppuccin_macchiato.toml | 35 ------ vendor/themes/catppuccin_mocha.toml | 168 -------------------------- vendor/themes/dark_plus.toml | 138 --------------------- vendor/themes/doom-one.LICENSE | 23 ---- vendor/themes/doom-one.toml | 127 -------------------- vendor/themes/dracula.toml | 159 ------------------------ vendor/themes/molokai.toml | 2 +- vendor/themes/monokai.toml | 121 ------------------- vendor/themes/monokai_aqua.toml | 2 +- vendor/themes/monokai_helix.toml | 121 +++++++++++++++++++ vendor/themes/monokai_pro.toml | 134 --------------------- vendor/themes/monokai_pro_machine.toml | 131 -------------------- vendor/themes/monokai_pro_octagon.toml | 134 --------------------- vendor/themes/monokai_pro_ristretto.toml | 131 -------------------- vendor/themes/monokai_pro_spectrum.toml | 131 -------------------- vendor/themes/nord-night.toml | 2 +- vendor/themes/nord.toml | 199 ------------------------------- vendor/themes/nord_helix.toml | 199 +++++++++++++++++++++++++++++++ vendor/themes/rose_pine.toml | 197 ------------------------------ vendor/themes/rose_pine_dawn.toml | 30 ----- vendor/themes/rose_pine_moon.toml | 30 ----- vendor/themes/solarized_dark.toml | 135 --------------------- vendor/themes/solarized_light.toml | 155 ------------------------ vendor/themes/tokyonight_day.toml | 41 ------- vendor/themes/tokyonight_moon.toml | 41 ------- vendor/themes/tokyonight_storm.toml | 12 -- 45 files changed, 614 insertions(+), 3037 deletions(-) delete mode 100644 vendor/themes/ayu_dark.toml create mode 100644 vendor/themes/ayu_dark_helix.toml delete mode 100644 vendor/themes/ayu_light.toml delete mode 100644 vendor/themes/ayu_mirage.toml delete mode 100644 vendor/themes/catppuccin_frappe.toml delete mode 100644 vendor/themes/catppuccin_latte.toml delete mode 100644 vendor/themes/catppuccin_macchiato.toml delete mode 100644 vendor/themes/catppuccin_mocha.toml delete mode 100644 vendor/themes/dark_plus.toml delete mode 100644 vendor/themes/doom-one.LICENSE delete mode 100644 vendor/themes/doom-one.toml delete mode 100644 vendor/themes/dracula.toml delete mode 100644 vendor/themes/monokai.toml create mode 100644 vendor/themes/monokai_helix.toml delete mode 100644 vendor/themes/monokai_pro.toml delete mode 100644 vendor/themes/monokai_pro_machine.toml delete mode 100644 vendor/themes/monokai_pro_octagon.toml delete mode 100644 vendor/themes/monokai_pro_ristretto.toml delete mode 100644 vendor/themes/monokai_pro_spectrum.toml delete mode 100644 vendor/themes/nord.toml create mode 100644 vendor/themes/nord_helix.toml delete mode 100644 vendor/themes/rose_pine.toml delete mode 100644 vendor/themes/rose_pine_dawn.toml delete mode 100644 vendor/themes/rose_pine_moon.toml delete mode 100644 vendor/themes/solarized_dark.toml delete mode 100644 vendor/themes/solarized_light.toml delete mode 100644 vendor/themes/tokyonight_day.toml delete mode 100644 vendor/themes/tokyonight_moon.toml delete mode 100644 vendor/themes/tokyonight_storm.toml (limited to 'src/File.zig') diff --git a/docs/typ/themes.typ b/docs/typ/themes.typ index da4354e2..edfaa7ad 100644 --- a/docs/typ/themes.typ +++ b/docs/typ/themes.typ @@ -67,8 +67,9 @@ tab. Where a chrome colour misses one of pardes's floors (rules 1.5:1 off the page, the focused tag 1.5:1 off the unfocused one on a dark page and 1.25:1 on a light one, tag text 4.5:1), only that colour moves, just far enough, and the file's header says so; text, syntax and ANSI never move. -An imported theme whose name a port now holds is kept with `_helix` added -(`dracula_helix`). +helix's own copy of a theme ported here is not imported, except the +three other helix themes build on: `monokai_helix`, `ayu_dark_helix` and +`nord_helix`. #pairs( [Visual Studio Code], [`dark_plus`], diff --git a/src/File.zig b/src/File.zig index 7e05ac9f..e92efaba 100644 --- a/src/File.zig +++ b/src/File.zig @@ -1929,16 +1929,6 @@ pub const DiffTints = struct { } }; -/// A diff row's tint: its ground from `x` to the pane's edge. -fn tintRow(s: *Surface, x: u16, y: u16, end: u16, bg: [3]u8) void { - var col = x; - while (col < end) : (col += 1) { - const cell = s.at(col, y); - cell.default = false; - cell.style.bg = .{ .rgb = bg }; - } -} - fn synStyle(p: *Pardes, sy: syntax.Syn) ?SynStyle { return switch (sy) { .none => null, @@ -2010,7 +2000,7 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. if (tint) |t| if (prefix_width < tw) { // A +Diff line added or removed whole: faintly (hunks.zig). const whole = highlights[base - highlight_start] & syntax.diff_whole != 0; - if (row_tint or whole) tintRow(s, tx + @as(u16, @intCast(prefix_width)), body_y + vr, tx + tw, if (row_tint) t.bg else t.line_bg); + if (row_tint or whole) s.tint(tx + @as(u16, @intCast(prefix_width)), body_y + vr, tw -| @as(u16, @intCast(prefix_width)), if (row_tint) t.bg else t.line_bg, null); }; // A +Pager's own colours (pager.zig) on every row but one the diff // look tints: an added or removed line is drawn as pardes draws a @@ -2228,7 +2218,7 @@ pub fn recolorDiffOutput(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, t const view = maybe orelse continue; const base = @intFromPtr(rows[view.row].ptr) - flat_start - lo; const tint = if (base < styles.len) tints.forStyle(styles[base]) else null; - if (tint) |t| tintRow(s, tx, body_y + @as(u16, @intCast(vr)), tx + tw, t.bg); + if (tint) |t| s.tint(tx, body_y + @as(u16, @intCast(vr)), tw, t.bg, null); var c: usize = 0; var screen_c: usize = 0; while (c < line.len and screen_c < tw) { @@ -2310,12 +2300,9 @@ pub fn paintWordSelection( if (hi <= lo) continue; const c0 = @as(i32, prefix_width) + here.pad + displayOffset(pane, row, here.at, lo); const c1 = @as(i32, prefix_width) + here.pad + displayEndOffset(pane, row, here.at, hi - 1); - var col = @max(@as(i32, prefix_width), c0); - while (col <= c1 and col < @as(i32, tw)) : (col += 1) { - const cell = s.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(vr))); - cell.default = false; - cell.style.bg = .{ .rgb = bg }; - } + const col = @max(@as(i32, prefix_width), c0); + const end = @min(c1 + 1, @as(i32, tw)); + if (col < end) s.tint(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(vr)), @intCast(end - col), bg, null); } } diff --git a/src/Messages.zig b/src/Messages.zig index 6d064c93..6785bd8a 100644 --- a/src/Messages.zig +++ b/src/Messages.zig @@ -398,16 +398,6 @@ pub fn noticeLife(pane: *const Pane, i: usize) ?Pane.MessageLife { }; } -pub fn blendRgb(from: [3]u8, to: [3]u8, amount: f32) [3]u8 { - var out: [3]u8 = undefined; - for (&out, from, to) |*o, a, b| { - const af: f32 = @floatFromInt(a); - const bf: f32 = @floatFromInt(b); - o.* = @intFromFloat(@round(bf + (af - bf) * std.math.clamp(amount, 0, 1))); - } - return out; -} - fn logMessage(p: *Pardes, id: usize, text: []const u8) void { if (text.len == 0) return; const serial: u32 = if (p.fs.session_write) 0 else if (id < MAX_PANES) if (p.panes[id]) |pane| pane.serial else 0 else 0; diff --git a/src/Presentation.zig b/src/Presentation.zig index 2a75b66d..3fc9be44 100644 --- a/src/Presentation.zig +++ b/src/Presentation.zig @@ -347,52 +347,36 @@ pub fn acknowledge(self: *Presentation, p: *Pardes, tracks: []const Track) void pub fn capturePrevious(self: *Presentation, gpa: std.mem.Allocator, surface: *const pardes.Surface) void { self.diff_state = .none; const cells = surface.cells; - if (cells.len == 0) { - self.previous_valid = false; - self.previous_layout = @splat(null); - return; - } - if (self.previous_cells.len != cells.len) { - const next = gpa.alloc(pardes.Cell, cells.len) catch { - self.previous_valid = false; - self.previous_layout = @splat(null); - return; - }; - if (self.previous_cells.len > 0) gpa.free(self.previous_cells); - self.previous_cells = next; - } - for (&self.previous_body_layers, surface.bodyLayers()) |*old, *current| { - const count = if (current.rows > 0) current.cells.len else 0; - const storage = if (old.cells.len == count) old.cells else gpa.realloc(old.cells, count) catch { - self.previous_valid = false; - self.previous_layout = @splat(null); - return; - }; - if (count > 0) @memcpy(storage, current.cells); - old.* = current.*; - old.cells = storage; - } - for (&self.previous_tag_layers, surface.tagLayers()) |*old, *current| { - const count = if (current.rows > 0) current.cells.len else 0; - const storage = if (old.cells.len == count) old.cells else gpa.realloc(old.cells, count) catch { - self.previous_valid = false; - self.previous_layout = @splat(null); - return; + copy: { + if (cells.len == 0) break :copy; + if (self.previous_cells.len != cells.len) { + const next = gpa.alloc(pardes.Cell, cells.len) catch break :copy; + if (self.previous_cells.len > 0) gpa.free(self.previous_cells); + self.previous_cells = next; + } + const olds = [_][]pardes.Layer{ &self.previous_body_layers, &self.previous_tag_layers }; + const currents = [_][]const pardes.Layer{ surface.bodyLayers(), surface.tagLayers() }; + for (olds, currents) |old_layers, current_layers| for (old_layers, current_layers) |*old, *current| { + const count = if (current.rows > 0) current.cells.len else 0; + const storage = if (old.cells.len == count) old.cells else gpa.realloc(old.cells, count) catch break :copy; + if (count > 0) @memcpy(storage, current.cells); + old.* = current.*; + old.cells = storage; }; - if (count > 0) @memcpy(storage, current.cells); - old.* = current.*; - old.cells = storage; + @memcpy(self.previous_cells, cells); + @memcpy(self.previous_regions[0..surface.nregions], surface.regionList()); + self.previous_nregions = surface.nregions; + self.previous_cols = surface.cols; + self.previous_rows = surface.rows; + self.previous_valid = true; + self.previous_layout = if (self.submitted_ready) + self.submitted + else + @splat(null); + return; } - @memcpy(self.previous_cells, cells); - @memcpy(self.previous_regions[0..surface.nregions], surface.regionList()); - self.previous_nregions = surface.nregions; - self.previous_cols = surface.cols; - self.previous_rows = surface.rows; - self.previous_valid = true; - self.previous_layout = if (self.submitted_ready) - self.submitted - else - @splat(null); + self.previous_valid = false; + self.previous_layout = @splat(null); } pub fn cellDiff(self: *const Presentation, cols: u16, rows: u16, col: u16, row: u16) pardes.PanelCellDiff { diff --git a/src/animation.zig b/src/animation.zig index 547b9201..a4887148 100644 --- a/src/animation.zig +++ b/src/animation.zig @@ -1226,22 +1226,14 @@ pub fn Immediate(comptime Value: type) type { }; } -pub fn interpolateRgb(from: [3]u8, to: [3]u8, step: u16, steps: u16) [3]u8 { - if (step == 0) return from; - if (step >= steps) return to; - var out: [3]u8 = undefined; - for (&out, from, to) |*dst, a, b| { - const numerator = @as(u32, a) * (steps - step) + @as(u32, b) * step; - dst.* = @intCast((numerator + steps / 2) / steps); - } - return out; -} - +/// A Fade's value for its tests: a colour stepped channel by channel. const TestColor = struct { rgb: [3]u8, pub fn interpolate(from: TestColor, to: TestColor, step: u16, steps: u16) TestColor { - return .{ .rgb = interpolateRgb(from.rgb, to.rgb, step, steps) }; + var out = from; + for (&out.rgb, to.rgb) |*c, b| c.* = @intCast((@as(u32, c.*) * (steps - step) + @as(u32, b) * step + steps / 2) / steps); + return out; } }; diff --git a/src/body_layer.zig b/src/body_layer.zig index 2aa8e5f8..0ddda41d 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -6,7 +6,6 @@ const pardes = @import("pardes.zig"); const normal = @import("normal.zig"); const edit = @import("edit.zig"); const config = @import("config.zig"); -const limits = @import("memory.zig").limits; const layout = @import("layout.zig"); const modal = @import("modal.zig"); const tracy = @import("tracy.zig"); @@ -23,19 +22,7 @@ const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; const Rect = layout.Rect; const Pardes = pardes.Pardes; const tagline = @import("tagline.zig"); -const Messages = @import("Messages.zig"); const Text = panes.Text; -const MAX_PANES = pardes.MAX_PANES; -const TagKind = @import("Layer.zig").Kind; -const MAX_TAG_ROWS = pardes.MAX_TAG_ROWS; -const NOTICE_LAYER_BASE = pardes.NOTICE_LAYER_BASE; -const TAG_LINE_LAYER_BASE = pardes.TAG_LINE_LAYER_BASE; -const HEADER_LINE_LAYER_BASE = pardes.HEADER_LINE_LAYER_BASE; -const MAX_COLS = pardes.MAX_COLS; -const TOPBAR_H = pardes.TOPBAR_H; -const COLBAR_H = pardes.COLBAR_H; -const TAG_GAP = pardes.TAG_GAP; -const wordBoundsAtCol = pardes.wordBoundsAtCol; const Layer = @import("Layer.zig"); @@ -71,14 +58,9 @@ fn paintTerminalSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: [ lo = modal.graphemeStart(line, @min(lo, line.len)); hi = @min(hi, line.len); if (lo >= hi) continue; - var col = panes.File.rawDisplayCol(line, lo); - const end = if (row.to_edge and hi == line.len) width else panes.File.rawDisplayCol(line, hi); - while (col < end and col < width) : (col += 1) { - const cell = s.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(visible))); - cell.default = false; - cell.style.bg = .{ .rgb = bg }; - if (fg) |ink| cell.style.fg = .{ .rgb = ink }; - } + const col = panes.File.rawDisplayCol(line, lo); + const end = @min(width, if (row.to_edge and hi == line.len) width else panes.File.rawDisplayCol(line, hi)); + if (col < end) s.tint(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(visible)), @intCast(end - col), bg, fg); } } } @@ -113,14 +95,9 @@ fn paintSourceSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: []c const lo = @max(start, row.lo); const hi = @min(end, row.hi); if (lo >= hi) continue; - var col = prefix + source.pad + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], lo - start))); - const last = if (row.to_edge and hi == end) @as(i32, width) else prefix + source.pad + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], hi - start))); - while (col < last and col < width) : (col += 1) { - const cell = s.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(visible))); - cell.default = false; - cell.style.bg = .{ .rgb = bg }; - if (fg) |ink| cell.style.fg = .{ .rgb = ink }; - } + const col = prefix + source.pad + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], lo - start))); + const last = @min(width, if (row.to_edge and hi == end) @as(i32, width) else prefix + source.pad + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], hi - start)))); + if (col < last) s.tint(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(visible)), @intCast(last - col), bg, fg); } } } @@ -151,15 +128,11 @@ pub fn paintPointerSelection( // File line numbers occupy a gutter only in the body. The tag is // row zero in Sel space and starts at its real first text cell. const scroll: i32 = if (row < pane.tag_rows) pane.tag_scroll else 0; - var col: i32 = if (pane.file != null and row >= pane.tag_rows) @max(c0, @as(i32, panes.File.gutterWidth(pane))) else @max(0, c0 - scroll); + const col: i32 = if (pane.file != null and row >= pane.tag_rows) @max(c0, @as(i32, panes.File.gutterWidth(pane))) else @max(0, c0 - scroll); const row_x = if (row < pane.tag_rows) r.x + @min(TAG_TEXT_INSET, r.w) else tx; const row_width = if (row < pane.tag_rows) r.w -| TAG_TEXT_INSET else tw; - while (col <= c1 - scroll and col < row_width) : (col += 1) { - const cell = s.at(row_x + @as(u16, @intCast(col)), sy); - cell.default = false; - cell.style.bg = .{ .rgb = bg }; - if (fg) |ink| cell.style.fg = .{ .rgb = ink }; - } + const end = @min(c1 - scroll + 1, row_width); + if (col < end) s.tint(row_x + @as(u16, @intCast(col)), sy, @intCast(end - col), bg, fg); } } @@ -345,13 +318,8 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane while (row < body_bottom) : (row += 1) { const ar = pane.wrapAt(@as(i32, row) - @as(i32, pane.tag_rows)).line; if (ar < lo or ar > hi) continue; - var col: u16 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; - while (col < tw) : (col += 1) { - const cell = s.at(tx + col, body_y + row - pane.tag_rows); - cell.default = false; - cell.style.bg = .{ .rgb = modal_bg }; - if (!hover_only) cell.style.fg = .{ .rgb = th.sel_fg }; - } + const col: u16 = if (pane.file != null) panes.File.gutterWidth(pane) else 0; + if (col < tw) s.tint(tx + col, body_y + row - pane.tag_rows, tw - col, modal_bg, if (hover_only) null else th.sel_fg); } } const preview = normal.selRegexArmed(pane) != null; @@ -409,13 +377,9 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane panes.File.lineDisplayEndOffset(visible_line, @intCast(@max(0, w.at)), @intCast(@max(0, bnd.hi_col)))) + vpfx + w.pad else @as(i32, tw) - 1; - var col: i32 = @max(cstart, vpfx); - while (col <= cend and col < tw) : (col += 1) { - const cell = s.at(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(vr))); - cell.default = false; - cell.style.bg = .{ .rgb = bg }; - if (!hover_only) cell.style.fg = .{ .rgb = th.sel_fg }; - } + const col: i32 = @max(cstart, vpfx); + const end = @min(cend + 1, tw); + if (col < end) s.tint(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(vr)), @intCast(end - col), bg, if (hover_only) null else th.sel_fg); } if (primary and !preview and !hover_only) continue; // the hardware cursor IS the primary's if (hover_only) continue; // quiet preview preserves the source ink diff --git a/src/colors.zig b/src/colors.zig index 28136975..c016434b 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -4,12 +4,10 @@ const pardes = @import("pardes.zig"); const tagline = @import("tagline.zig"); const panes = @import("panes.zig"); const std = @import("std"); -const layout = @import("layout.zig"); const animation = @import("animation.zig"); const Color = @import("surface.zig").Color; const FontRole = @import("surface.zig").FontRole; const config = @import("config.zig"); -const limits = @import("memory.zig").limits; const pdf_enabled = panes.Pdf.enabled; const platform = pardes.platform; const theme_animation = @import("pardes_config").theme_animation; @@ -34,7 +32,7 @@ pub fn contrast(a: [3]u8, b: [3]u8) f32 { return (@max(x, y) + 0.05) / (@min(x, y) + 0.05); } -fn lerp(a: [3]u8, b: [3]u8, t: f32) [3]u8 { +pub fn lerp(a: [3]u8, b: [3]u8, t: f32) [3]u8 { var out: [3]u8 = undefined; for (&out, a, b) |*o, x, y| o.* = @intFromFloat(std.math.clamp(@round(@as(f32, @floatFromInt(x)) + (@as(f32, @floatFromInt(y)) - @as(f32, @floatFromInt(x))) * t), 0, 255)); return out; @@ -498,22 +496,7 @@ fn fold(comptime C: type) [@typeInfo(C).@"struct".decl_names.len]Theme { } } -/// The imported themes (tools/gen_themes.zig), less any name one of ours -/// takes: a faithful port (`dracula`) keeps the plain name, and helix's -/// looser copy of it is still there as `dracula_helix` (the zed ones already -/// carry `_zed`). -fn foldImports(comptime ours: anytype, comptime C: type) [@typeInfo(C).@"struct".decl_names.len]Theme { - comptime { - @setEvalBranchQuota(400000); - var out = fold(C); - for (&out) |*g| for (ours) |c| if (std.mem.eql(u8, c.name, g.name)) { - g.name = g.name ++ "_helix"; - }; - return out; - } -} - -pub const themes = fold(curated) ++ foldImports(fold(curated), @import("generated_themes")); +pub const themes = fold(curated) ++ fold(@import("generated_themes")); /// The first `native_count` of `themes` are pardes's own; the rest imported. pub const native_count = @typeInfo(curated).@"struct".decl_names.len; @@ -589,18 +572,6 @@ test "lapis_plain is lapis on flat grounds, framed and shadowed as lapis" { /// Original and classic-inspired Pardes palettes precede retained imports. pub const native_theme_count = 15; -fn themeContrast(a: [3]u8, b: [3]u8) f64 { - var luminance: [2]f64 = .{ 0, 0 }; - for ([2][3]u8{ a, b }, 0..) |rgb, i| { - for (rgb, [3]f64{ 0.2126, 0.7152, 0.0722 }) |channel, weight| { - const srgb = @as(f64, @floatFromInt(channel)) / 255; - const linear = if (srgb <= 0.04045) srgb / 12.92 else std.math.pow(f64, (srgb + 0.055) / 1.055, 2.4); - luminance[i] += weight * linear; - } - } - return (@max(luminance[0], luminance[1]) + 0.05) / (@min(luminance[0], luminance[1]) + 0.05); -} - comptime { if (themes.len > std.math.maxInt(u16) + 1) @compileError("runtime config theme index no longer fits u16"); @@ -714,21 +685,11 @@ pub fn requestThemeFile(p: *Pardes, id: usize, argument: []const u8) void { var joined: [4095]u8 = undefined; const resolved = if (absolute) input else path: { const dir = p.opts.config_dir.?; - const separator = std.Io.Dir.path.sep; - const needs_separator = dir.len > 0 and dir[dir.len - 1] != separator; - const len = dir.len + @intFromBool(needs_separator) + input.len; - if (len > joined.len) { + const separator = if (dir.len > 0 and dir[dir.len - 1] != std.Io.Dir.path.sep) std.Io.Dir.path.sep_str else ""; + break :path std.fmt.bufPrint(&joined, "{s}{s}{s}", .{ dir, separator, input }) catch { p.reportError(id, "theme file", error.PathTooLong); return; - } - @memcpy(joined[0..dir.len], dir); - var at = dir.len; - if (needs_separator) { - joined[at] = separator; - at += 1; - } - @memcpy(joined[at..][0..input.len], input); - break :path joined[0..len]; + }; }; if (!p.theme_file_path.set(resolved)) { p.reportError(id, "theme file", error.PathTooLong); @@ -787,9 +748,7 @@ fn themeFileFailure(p: *Pardes, request: ThemeFileRequest, why: []const u8) void fn revertThemeFile(p: *Pardes) void { const loaded = p.theme_file_loaded.get(); if (std.mem.eql(u8, loaded, p.theme_file_path.get())) return; - var keep: [limits.host_path_cap]u8 = undefined; - @memcpy(keep[0..loaded.len], loaded); - if (loaded.len == 0) p.theme_file_path.clear() else _ = p.theme_file_path.set(keep[0..loaded.len]); + if (loaded.len == 0) p.theme_file_path.clear() else _ = p.theme_file_path.set(loaded); const generation = nextThemeFileGeneration(p); p.emit(.{ .theme_file = .{ .generation = generation, .on = loaded.len > 0 } }); } @@ -836,9 +795,7 @@ pub fn loadThemeFile(p: *Pardes, generation: u32, bytes: []const u8, animate: bo const old = p.custom_theme; p.custom_theme = parsed; if (old) |theme_value| p.gpa.free(theme_value.name); - var settled: [limits.host_path_cap]u8 = undefined; - @memcpy(settled[0..request.path.len], request.path); - _ = p.theme_file_loaded.set(settled[0..request.path.len]); + _ = p.theme_file_loaded.set(request.path); invalidateThemeDependentRasters(p); _ = p.scratch.reset(.{ .retain_with_limit = pardes.memory.limits.scratch_kept }); p.sync(); @@ -1115,58 +1072,38 @@ test "native themes keep text and UI roles readable on their own surfaces" { for (themes[0..names.len], names) |th, name| { try std.testing.expectEqualStrings(name, th.name); const chrome = ChromeTheme.fromTheme(&th); - const minimum: f64 = if (std.mem.eql(u8, name, "ink") or std.mem.eql(u8, name, "daybreak")) 7 else 4.5; + const minimum: f32 = if (std.mem.eql(u8, name, "ink") or std.mem.eql(u8, name, "daybreak")) 7 else 4.5; const text_colors = [_][3]u8{ th.fg.?, th.kw, th.str, th.num, th.comment, chrome.diagnostic_error, chrome.diagnostic_warning, chrome.diagnostic_info, chrome.diagnostic_hint, }; - for (text_colors) |fg| try std.testing.expect(themeContrast(fg, th.bg.?) >= minimum); + for (text_colors) |fg| try std.testing.expect(contrast(fg, th.bg.?) >= minimum); // Gutters are orientation aids, not source text: stay visible without // competing with comments or pulling attention away from the body. - try std.testing.expect(themeContrast(th.lineno, th.bg.?) >= 2.5); - try std.testing.expect(themeContrast(th.lineno, th.bg.?) <= 4); - try std.testing.expect(themeContrast(th.lineno_active.?, th.bg.?) >= themeContrast(th.lineno, th.bg.?)); - try std.testing.expect(themeContrast(th.lineno_active.?, th.bg.?) <= 4.5); - try std.testing.expect(themeContrast(th.comment, th.bg.?) >= 5); - try std.testing.expect(themeContrast(th.comment, th.bg.?) >= themeContrast(th.lineno, th.bg.?) + 2); - try std.testing.expect(themeContrast(th.tag_fg, th.tag_bg) >= minimum); - try std.testing.expect(themeContrast(chrome.tag_active_fg, chrome.tag_active_bg) >= minimum); + try std.testing.expect(contrast(th.lineno, th.bg.?) >= 2.5); + try std.testing.expect(contrast(th.lineno, th.bg.?) <= 4); + try std.testing.expect(contrast(th.lineno_active.?, th.bg.?) >= contrast(th.lineno, th.bg.?)); + try std.testing.expect(contrast(th.lineno_active.?, th.bg.?) <= 4.5); + try std.testing.expect(contrast(th.comment, th.bg.?) >= 5); + try std.testing.expect(contrast(th.comment, th.bg.?) >= contrast(th.lineno, th.bg.?) + 2); + try std.testing.expect(contrast(th.tag_fg, th.tag_bg) >= minimum); + try std.testing.expect(contrast(chrome.tag_active_fg, chrome.tag_active_bg) >= minimum); try std.testing.expect(th.tag_name_fg != null); - try std.testing.expect(themeContrast(chrome.tag_name_fg, th.tag_bg) >= minimum); - try std.testing.expect(themeContrast(chrome.tag_active_name_fg, chrome.tag_active_bg) >= minimum); + try std.testing.expect(contrast(chrome.tag_name_fg, th.tag_bg) >= minimum); + try std.testing.expect(contrast(chrome.tag_active_name_fg, chrome.tag_active_bg) >= minimum); // Focus stays on the same tonal surface, rather than inverting a // whole command strip. Text remains readable in both states. - try std.testing.expect(themeContrast(chrome.tag_active_bg, th.tag_bg) <= 1.6); - try std.testing.expect(themeContrast(chrome.tag_active_fg, th.tag_fg) <= 1.6); - try std.testing.expect(themeContrast(th.sel_fg, th.sel_bg) >= minimum); - try std.testing.expect(themeContrast(chrome.search_fg, chrome.search_bg) >= minimum); + try std.testing.expect(contrast(chrome.tag_active_bg, th.tag_bg) <= 1.6); + try std.testing.expect(contrast(chrome.tag_active_fg, th.tag_fg) <= 1.6); + try std.testing.expect(contrast(th.sel_fg, th.sel_bg) >= minimum); + try std.testing.expect(contrast(chrome.search_fg, chrome.search_bg) >= minimum); // ANSI black can intentionally match the page (for backgrounds). All // other ANSI foregrounds, including bright black, remain legible. - for (th.palette.?[1..]) |fg| try std.testing.expect(themeContrast(fg, th.bg.?) >= minimum); + for (th.palette.?[1..]) |fg| try std.testing.expect(contrast(fg, th.bg.?) >= minimum); } } test "native filename tints change hue without changing perceived lightness" { - const Perceptual = struct { - fn lab(rgb: [3]u8) [3]f64 { - var linear: [3]f64 = undefined; - for (rgb, 0..) |channel, i| { - const value = @as(f64, @floatFromInt(channel)) / 255; - linear[i] = if (value <= 0.04045) value / 12.92 else std.math.pow(f64, (value + 0.055) / 1.055, 2.4); - } - const r = linear[0]; - const g = linear[1]; - const b = linear[2]; - const l = std.math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b); - const m = std.math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b); - const n = std.math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b); - return .{ - 0.2104542553 * l + 0.7936177850 * m - 0.0040720468 * n, - 1.9779984951 * l - 2.4285922050 * m + 0.4505937099 * n, - 0.0259040371 * l + 0.7827717662 * m - 0.8086757660 * n, - }; - } - }; for (themes[0..native_theme_count]) |th| { try std.testing.expect(th.tag_name_fg != null and th.tag_active_name_fg != null); const chrome = ChromeTheme.fromTheme(&th); @@ -1175,8 +1112,8 @@ test "native filename tints change hue without changing perceived lightness" { .{ chrome.tag_active_fg, chrome.tag_active_name_fg }, }; for (pairs) |pair| { - const base = Perceptual.lab(pair[0]); - const name = Perceptual.lab(pair[1]); + const base = toOklab(pair[0]); + const name = toOklab(pair[1]); // Half a lightness point allows 8-bit quantization without a // basename becoming visibly brighter or darker than its tag. try std.testing.expectApproxEqAbs(base[0], name[0], 0.005); @@ -1193,15 +1130,15 @@ test "native filename tints change hue without changing perceived lightness" { test "native dark palettes choose near-black or deliberately soft contrast" { for (themes[0..native_theme_count]) |th| { - if (themeContrast(th.bg.?, .{ 0, 0, 0 }) > 10) continue; // light paper + if (contrast(th.bg.?, .{ 0, 0, 0 }) > 10) continue; // light paper const soft = std.mem.eql(u8, th.name, "dusk") or std.mem.eql(u8, th.name, "lagoon") or std.mem.eql(u8, th.name, "solarium") or std.mem.eql(u8, th.name, "forge_soft"); if (soft) { - try std.testing.expect(themeContrast(th.fg.?, th.bg.?) >= 4.5); - try std.testing.expect(themeContrast(th.fg.?, th.bg.?) <= 7); + try std.testing.expect(contrast(th.fg.?, th.bg.?) >= 4.5); + try std.testing.expect(contrast(th.fg.?, th.bg.?) <= 7); } else { for (th.bg.?) |channel| try std.testing.expect(channel <= 0x14); - try std.testing.expect(themeContrast(th.fg.?, th.bg.?) >= 14); + try std.testing.expect(contrast(th.fg.?, th.bg.?) >= 14); } } const forge = curated.forge.theme; diff --git a/src/draw.zig b/src/draw.zig index 3d0d4d3c..93a78090 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -35,8 +35,6 @@ const wordBoundsAtCol = pardes.wordBoundsAtCol; const BOX_H = pardes.BOX_H; const TAG_GAP = pardes.TAG_GAP; const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; -const TOPBAR_H = pardes.TOPBAR_H; -const COLBAR_H = pardes.COLBAR_H; const MAX_PANES = pardes.MAX_PANES; const MAX_COLS = pardes.MAX_COLS; const MAX_TAG_ROWS = pardes.MAX_TAG_ROWS; @@ -1213,12 +1211,7 @@ fn joinPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r // Window mode (layout.windowKey): the outlined pane's tag in the // selection's colours. if (p.window_pick == id) { - const th = p.theme(); - for (storage) |*cell| { - cell.style.bg = .{ .rgb = th.sel_bg }; - cell.style.fg = .{ .rgb = th.sel_fg }; - cell.default = false; - } + for (0..rows) |row| temporary.tint(0, @intCast(row), temporary.cols, p.theme().sel_bg, p.theme().sel_fg); } const tag_fg: Color = .{ .rgb = if (active and p.settings.focus_tint) chrome.tag_active_fg else chrome.tag_fg }; // One layer, a row to each line the tag shows. @@ -1268,11 +1261,11 @@ fn joinNotice(p: *Pardes, s: *Surface, arena: std.mem.Allocator, region: Region) // cannot move it by less than a row, a pixel shell slides it too. const motion: Messages.MessageMotion = if (Messages.noticeLife(pane, i)) |life| Messages.messageMotion(p, life) else .{}; const page = th.bg orelse chrome.tag_bg; - const bg = Messages.blendRgb(chrome.tag_bg, page, motion.alpha); + const bg = colors.lerp(page, chrome.tag_bg, motion.alpha); // Where an exec was sent to a REPL reads in the tag's name tint, set // apart from what the editor says. const ink = if (kind == .message and pane.msg_sent) chrome.tag_name_fg else chrome.tag_fg; - const fg = Messages.blendRgb(ink, page, motion.alpha); + const fg = colors.lerp(page, ink, motion.alpha); // Nothing to say, or too narrow for a layer: a blank chip on the grid. if (text.len == 0 or r.w <= TAG_TEXT_INSET) { s.fill(region.rect.x, region.rect.y, chip, 1, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); @@ -1428,15 +1421,9 @@ pub fn paintPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pa const line = lines[row - top]; const from = if (row == first.row) first.col else 0; const to = @min(line.len, if (row == last.row) last.col else line.len); - var col = panes.File.rawDisplayCol(line, from) -| pane.tag_scroll; - const end = panes.File.rawDisplayCol(line, to); - const y = tag_y + @as(u16, @intCast(row - top)); - while (col + pane.tag_scroll < end and col < tw) : (col += 1) { - const cell = s.at(tx + @as(u16, @intCast(col)), y); - cell.default = false; - cell.style.bg = .{ .rgb = th.tag_sel_bg orelse th.sel_bg }; - cell.style.fg = .{ .rgb = th.sel_fg }; - } + const col = panes.File.rawDisplayCol(line, from) -| pane.tag_scroll; + const end = @min(panes.File.rawDisplayCol(line, to) -| pane.tag_scroll, tw); + if (col < end) s.tint(tx + @as(u16, @intCast(col)), tag_y + @as(u16, @intCast(row - top)), @intCast(end - col), th.tag_sel_bg orelse th.sel_bg, th.sel_fg); } } } diff --git a/src/gui/gui.zig b/src/gui/gui.zig index d3734fac..2d01db33 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -8794,37 +8794,25 @@ fn clipToBodies(g: *Gui, gpa: std.mem.Allocator, first: usize, bodies: []const [ /// the decor pipeline blends a colour that is not black): the largest `a` /// that keeps text and page apart by min(their contrast, 4.5). fn lightenCeiling(fg: [3]u8, bg: [3]u8, rgb: [3]u8) f32 { - const contrast = struct { - fn of(a: [3]u8, b: [3]u8) f32 { - const la = luminance(a); - const lb = luminance(b); - return (@max(la, lb) + 0.05) / (@min(la, lb) + 0.05); - } - fn blend(under: [3]u8, over: [3]u8, a: f32) [3]u8 { + const contrast = pardes.colors.contrast; + const blend = struct { + fn of(under: [3]u8, over: [3]u8, a: f32) [3]u8 { var out: [3]u8 = undefined; for (&out, under, over) |*o, x, y| o.* = @intFromFloat(@round(@as(f32, @floatFromInt(x)) * (1 - a) + @as(f32, @floatFromInt(y)) * a)); return out; } - }; - const target = @min(contrast.of(fg, bg), 4.5); + }.of; + const target = @min(contrast(fg, bg), 4.5); var lo: f32 = 0; var hi: f32 = 1; for (0..24) |_| { const mid = (lo + hi) / 2; - if (contrast.of(contrast.blend(fg, rgb, mid), contrast.blend(bg, rgb, mid)) >= target - 1e-3) lo = mid else hi = mid; + if (contrast(blend(fg, rgb, mid), blend(bg, rgb, mid)) >= target - 1e-3) lo = mid else hi = mid; } return lo; } -/// sRGB's relative luminance (WCAG). -fn luminance(rgb: [3]u8) f32 { - var sum: f32 = 0; - for (rgb, [3]f32{ 0.2126, 0.7152, 0.0722 }) |channel, weight| { - const v = @as(f32, @floatFromInt(channel)) / 255; - sum += weight * (if (v <= 0.04045) v / 12.92 else std.math.pow(f32, (v + 0.055) / 1.055, 2.4)); - } - return sum; -} +const luminance = pardes.colors.relativeLuminance; /// How dark a shadow may make the page and its text, both together, before /// the pair drops below its own contrast or 4.5, whichever is lower (§8.2): @@ -8853,11 +8841,7 @@ test "a rim never lightens a native theme's text below its contrast or 4.5" { return out; } }.of; - const ratio = struct { - fn of(x: [3]u8, y: [3]u8) f32 { - return (@max(luminance(x), luminance(y)) + 0.05) / (@min(luminance(x), luminance(y)) + 0.05); - } - }.of; + const ratio = pardes.colors.contrast; try std.testing.expect(ratio(blend(fg, light, a), blend(bg, light, a)) >= @min(ratio(fg, bg), 4.5) - 2e-3); } } @@ -9206,11 +9190,7 @@ fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, gr } /// Halfway between two colours. -fn mixRgb(a: [3]u8, b: [3]u8) [3]u8 { - var out: [3]u8 = undefined; - for (&out, a, b) |*o, x, y| o.* = @intCast((@as(u16, x) + y) / 2); - return out; -} +const mixRgb = pardes.colors.mix; /// A rule's width: the theme's own, or one pixel. fn rulePx(chrome: *const pardes.Chrome) f32 { diff --git a/src/surface.zig b/src/surface.zig index d6ec016d..839e8f33 100644 --- a/src/surface.zig +++ b/src/surface.zig @@ -221,10 +221,6 @@ pub const ImageCacheKey = if (pdf_enabled) struct { } }; -const PdfFitMode = panes.Pdf.FitMode; - -const PdfTintMode = panes.Pdf.TintMode; - /// Dynamic placement exists only for native PDF pages. Static image panes need /// only their pane identity, so feature-off builds carry a zero-bit payload. pub const NativePlacement = if (pdf_enabled) struct { @@ -562,67 +558,73 @@ pub const Surface = struct { continue; } } - if (col >= end) break; - // n == 0: not a start byte at all. A short tail or a bad - // continuation decodes to null the same way — one U+FFFD, one byte. - const n = std.unicode.utf8ByteSequenceLength(text[i]) catch 0; - const decoded: ?u21 = if (n > 0 and i + n <= text.len) - (std.unicode.utf8Decode(text[i .. i + n]) catch null) - else - null; - var cp_slice: []const u8 = "\u{FFFD}"; - var consumed: usize = 1; - if (decoded != null) { - var git = uucode.grapheme.utf8Iterator(text[i..]); - if (git.nextGrapheme()) |g| { - const candidate = text[i .. i + g.end]; - if (std.unicode.utf8ValidateSlice(candidate)) { - cp_slice = candidate; - consumed = candidate.len; - } else { - cp_slice = text[i .. i + n]; - consumed = n; - } - } - } - i += consumed; - var cp = decoded orelse 0xFFFD; - if (cp == '\r') continue; - if (cp == '\t') { - const spaces = @min(config.tab_now, end - col); - s.fill(col, y, spaces, 1, style); - col += spaces; - continue; - } - // No other C0/C1 control or DEL reaches a font fallback either. - if (cp < ' ' or cp == 0x7f or (cp >= 0x80 and cp <= 0x9f)) { - cp = 0xFFFD; - cp_slice = "\u{FFFD}"; - } - const width: u16 = if (decoded == null or (cp < 0x80 and cp_slice.len == 1)) - 1 - else - @max(1, vaxis.gwidth.gwidth(cp_slice, .unicode)); - if (width == 2 and col + 1 >= end) break; - var shown = cp_slice; - if (shown.len > @typeInfo(@FieldType(Cell, "text")).array.len) { - const cap = @typeInfo(@FieldType(Cell, "text")).array.len; - var prefix: usize = 0; - while (prefix < shown.len) { - const cp_len = std.unicode.utf8ByteSequenceLength(shown[prefix]) catch break; - if (prefix + cp_len > cap) break; - prefix += cp_len; + col = s.printGeneral(col, end, y, text, &i, style) orelse break; + } + return col; + } + + /// `print`'s general arm: the grapheme at `i.*`, painted at `col`. + /// Advances `i.*` past it and returns the column after it, or null + /// when a wide glyph does not fit before `end`. + fn printGeneral(s: *Surface, col: u16, end: u16, y: u16, text: []const u8, i: *usize, style: CellStyle) ?u16 { + const start = i.*; + // n == 0: not a start byte at all. A short tail or a bad + // continuation decodes to null the same way — one U+FFFD, one byte. + const n = std.unicode.utf8ByteSequenceLength(text[start]) catch 0; + const decoded: ?u21 = if (n > 0 and start + n <= text.len) + (std.unicode.utf8Decode(text[start .. start + n]) catch null) + else + null; + var cp_slice: []const u8 = "\u{FFFD}"; + var consumed: usize = 1; + if (decoded != null) { + var git = uucode.grapheme.utf8Iterator(text[start..]); + if (git.nextGrapheme()) |g| { + const candidate = text[start .. start + g.end]; + if (std.unicode.utf8ValidateSlice(candidate)) { + cp_slice = candidate; + consumed = candidate.len; + } else { + cp_slice = text[start .. start + n]; + consumed = n; } - shown = if (prefix > 0) shown[0..prefix] else "\u{FFFD}"; } - s.set(col, y, shown, style); - if (width == 2 and col + 1 < end) { - // spacer: empty cell under the wide glyph's tail - s.set(col + 1, y, "", style); + } + i.* += consumed; + var cp = decoded orelse 0xFFFD; + if (cp == '\r') return col; + if (cp == '\t') { + const spaces = @min(config.tab_now, end - col); + s.fill(col, y, spaces, 1, style); + return col + spaces; + } + // No other C0/C1 control or DEL reaches a font fallback either. + if (cp < ' ' or cp == 0x7f or (cp >= 0x80 and cp <= 0x9f)) { + cp = 0xFFFD; + cp_slice = "\u{FFFD}"; + } + const width: u16 = if (decoded == null or (cp < 0x80 and cp_slice.len == 1)) + 1 + else + @max(1, vaxis.gwidth.gwidth(cp_slice, .unicode)); + if (width == 2 and col + 1 >= end) return null; + var shown = cp_slice; + if (shown.len > @typeInfo(@FieldType(Cell, "text")).array.len) { + const cap = @typeInfo(@FieldType(Cell, "text")).array.len; + var prefix: usize = 0; + while (prefix < shown.len) { + const cp_len = std.unicode.utf8ByteSequenceLength(shown[prefix]) catch break; + if (prefix + cp_len > cap) break; + prefix += cp_len; } - col += width; + shown = if (prefix > 0) shown[0..prefix] else "\u{FFFD}"; } - return col; + s.set(col, y, shown, style); + if (width == 2 and col + 1 < end) { + // spacer: empty cell under the wide glyph's tail + s.set(col + 1, y, "", style); + } + return col + width; } pub fn fill(s: *Surface, x: u16, y: u16, w: u16, h: u16, style: CellStyle) void { @@ -633,6 +635,17 @@ pub const Surface = struct { } } + /// Recolour `n` cells from (x, y), keeping their glyphs: a selection's + /// ground, and its ink when `fg` is given. + pub fn tint(s: *Surface, x: u16, y: u16, n: u16, bg: [3]u8, fg: ?[3]u8) void { + for (x..x + n) |col| { + const cell = s.at(@intCast(col), y); + cell.default = false; + cell.style.bg = .{ .rgb = bg }; + if (fg) |ink| cell.style.fg = .{ .rgb = ink }; + } + } + pub fn clearRect(s: *Surface, x: u16, y: u16, w: u16, h: u16) void { var yy = y; while (yy < y + h) : (yy += 1) { @@ -683,66 +696,12 @@ test "surface print keeps combining and wide graphemes in their display cells" { } test "the ASCII fast path in surface print paints what the general arm paints" { + // The general arm alone, every grapheme through it. const ref = struct { fn print(s: *Surface, x: u16, y: u16, w: u16, text: []const u8, style: CellStyle) u16 { var col = x; - const end = x + w; var i: usize = 0; - while (i < text.len) { - if (col >= end) break; - const n = std.unicode.utf8ByteSequenceLength(text[i]) catch 0; - const decoded: ?u21 = if (n > 0 and i + n <= text.len) - (std.unicode.utf8Decode(text[i .. i + n]) catch null) - else - null; - var cp_slice: []const u8 = "\u{FFFD}"; - var consumed: usize = 1; - if (decoded != null) { - var git = uucode.grapheme.utf8Iterator(text[i..]); - if (git.nextGrapheme()) |g| { - const candidate = text[i .. i + g.end]; - if (std.unicode.utf8ValidateSlice(candidate)) { - cp_slice = candidate; - consumed = candidate.len; - } else { - cp_slice = text[i .. i + n]; - consumed = n; - } - } - } - i += consumed; - var cp = decoded orelse 0xFFFD; - if (cp == '\r') continue; - if (cp == '\t') { - const spaces = @min(config.tab_now, end - col); - s.fill(col, y, spaces, 1, style); - col += spaces; - continue; - } - if (cp < ' ' or cp == 0x7f or (cp >= 0x80 and cp <= 0x9f)) { - cp = 0xFFFD; - cp_slice = "\u{FFFD}"; - } - const width: u16 = if (decoded == null or (cp < 0x80 and cp_slice.len == 1)) - 1 - else - @max(1, vaxis.gwidth.gwidth(cp_slice, .unicode)); - if (width == 2 and col + 1 >= end) break; - var shown = cp_slice; - if (shown.len > @typeInfo(@FieldType(Cell, "text")).array.len) { - const cap = @typeInfo(@FieldType(Cell, "text")).array.len; - var prefix: usize = 0; - while (prefix < shown.len) { - const cp_len = std.unicode.utf8ByteSequenceLength(shown[prefix]) catch break; - if (prefix + cp_len > cap) break; - prefix += cp_len; - } - shown = if (prefix > 0) shown[0..prefix] else "\u{FFFD}"; - } - s.set(col, y, shown, style); - if (width == 2 and col + 1 < end) s.set(col + 1, y, "", style); - col += width; - } + while (i < text.len and col < x + w) col = s.printGeneral(col, x + w, y, text, &i, style) orelse break; return col; } }.print; diff --git a/test/snapshots/themesel.golden b/test/snapshots/themesel.golden index b8e6bb61..346bb898 100644 --- a/test/snapshots/themesel.golden +++ b/test/snapshots/themesel.golden @@ -756,20 +756,20 @@ |29: 0-3 d,#1e1e1e, 4-99 #858585,#1e1e1e, |30: 0-3 d,#1e1e1e, 4-6 #858585,#1e1e1e, 7-99 #d4d4d4,#1e1e1e, == snap tail grid=100x31 cursor=7,29 -|17: 327 Theme wolf_alabaster_dark -|18: 328 Theme wolf_alabaster_dark_bg -|19: 329 Theme wolf_alabaster_dark_mono -|20: 330 Theme wolf_alabaster_light -|21: 331 Theme wolf_alabaster_light_bg -|22: 332 Theme wolf_alabaster_light_mono -|23: 333 Theme yellowed -|24: 334 Theme yo -|25: 335 Theme yo_berry -|26: 336 Theme yo_light -|27: 337 Theme zed_onedark -|28: 338 Theme zed_onelight -|29: 339 Theme zenburn -|30: 340 +|17: 305 Theme wolf_alabaster_dark +|18: 306 Theme wolf_alabaster_dark_bg +|19: 307 Theme wolf_alabaster_dark_mono +|20: 308 Theme wolf_alabaster_light +|21: 309 Theme wolf_alabaster_light_bg +|22: 310 Theme wolf_alabaster_light_mono +|23: 311 Theme yellowed +|24: 312 Theme yo +|25: 313 Theme yo_berry +|26: 314 Theme yo_light +|27: 315 Theme zed_onedark +|28: 316 Theme zed_onelight +|29: 317 Theme zenburn +|30: 318 == snap picked grid=100x31 cursor=7,3 |16: 14 line 14 |17: 15 line 15 diff --git a/tools/gen_themes.zig b/tools/gen_themes.zig index be5fde2f..30808dfe 100644 --- a/tools/gen_themes.zig +++ b/tools/gen_themes.zig @@ -11,9 +11,10 @@ //! //! Why vendored and not read out of ~/05-genizah: `zig build` must work on a //! fresh clone with no network and no helix checkout. It is the WHOLE of what -//! both projects ship — helix's 214 runtime themes and zed's three families, -//! 1.5MB of text — because "which ones are worth having" is not a question a -//! build tool gets to answer on the user's behalf. +//! both projects ship — helix's runtime themes and zed's three families — +//! because "which ones are worth having" is not a question a build tool gets +//! to answer on the user's behalf. The one exception is helix's copy of a +//! theme pardes ports by hand (src/themes/: dracula, nord, ...): not vendored. //! //! NAMES. A helix theme is its file stem; a zed variant is its `name` slugged //! with `_zed` on the end. Both projects ship gruvbox, ayu and one, so the @@ -21,7 +22,10 @@ //! variant is one rule instead of eight exceptions — it also keeps a name from //! moving when the other source gains or loses a file. helix's own `acme.toml` //! is vendored as `acme_helix.toml` for the same reason, since pardes ships an -//! acme of its own; the file is otherwise untouched. Two themes answering to +//! acme of its own; the file is otherwise untouched. So are `monokai`, +//! `ayu_dark` and `nord` as `_helix.toml`, kept (unlike helix's other +//! copies of themes ported here) because helix themes inherit them; those +//! `inherits` lines name the renamed file. Two themes answering to //! one name is a bug (`Theme ` would silently pick one), so src/colors.zig //! asserts the ring's names are distinct at comptime. //! @@ -29,7 +33,7 @@ //! helix-editor/helix runtime/themes, each file keeping its author's header); //! *.json are zed's (zed-industries/zed assets/themes). The licences sit beside //! them as `.LICENSE` — `helix.LICENSE` covering the runtime set, one per -//! zed family, plus the twenty-two helix keeps in `runtime/themes/licenses/` +//! zed family, plus the twenty-one helix keeps in `runtime/themes/licenses/` //! for the themes it took from somewhere else (their names group by SOURCE, not //! by file: `everforest.LICENSE` covers both everforest themes). build.zig's //! directory read skips anything that is not a .toml or a .json, which is what diff --git a/vendor/themes/ayu_dark.toml b/vendor/themes/ayu_dark.toml deleted file mode 100644 index a2fbc316..00000000 --- a/vendor/themes/ayu_dark.toml +++ /dev/null @@ -1,92 +0,0 @@ -# Author: André Sá -# Based on the AYU theme colors from https://github.com/dempfi/ayu - -# Syntax highlighting -"type" = "blue" -"type.builtin" = "blue" -"constructor" = "green" -"constant" = "magenta" -"string" = "green" -"string.regexp" = "orange" -"string.special" = "yellow" -"comment" = { fg = "gray", modifiers = ["italic"] } -"variable" = "foreground" -"label" = "orange" -"punctuation" = "foreground" -"keyword" = "orange" -"keyword.control" = "yellow" -"keyword.directive" = "yellow" -"operator" = "orange" -"function" = "yellow" -"tag" = "blue" -"namespace" = "blue" -"markup.heading" = "orange" -"markup.list" = "yellow" -"markup.bold" = { fg = "orange", modifiers = ["bold"] } -"markup.italic" = { fg = "orange", modifiers = ["italic"] } -"markup.strikethrough" = { modifiers = ["crossed_out"] } -"markup.raw.block" = "orange" -"markup.link.url" = "blue" -"markup.link.text" = "yellow" -"markup.link.label" = "green" -"markup.quote" = "yellow" -"diff.plus" = "green" -"diff.minus" = "red" -"diff.delta" = "yellow" - -# Interface -"ui.background"= { bg = "background" } -"ui.cursor" = { fg = "dark_gray", bg = "yellow" } -"ui.cursor.primary" = { fg = "dark_gray", bg = "orange" } -"ui.cursor.match" = "orange" -"ui.linenr" = "dark_gray" -"ui.linenr.selected" = "gray" -"ui.statusline" = { fg = "foreground", bg = "black" } -"ui.statusline.normal" = { fg = "black", bg = "blue" } -"ui.statusline.insert" = { fg = "black", bg = "orange" } -"ui.statusline.select" = { fg = "black", bg = "magenta" } -"ui.cursorline" = { bg = "black" } -"ui.popup" = { fg = "#7B91b3", bg = "black" } -"ui.window" = "dark_gray" -"ui.help" = { fg = "#7B91b3", bg = "black" } -"ui.text" = "foreground" -"ui.text.focus" = { bg = "dark_gray", fg = "foreground" } -"ui.text.info" = "foreground" -"ui.virtual.whitespace" = "dark_gray" -"ui.virtual.ruler" = { bg = "black" } -"ui.virtual.inlay-hint" = { fg = "#e6b450", bg = "#302a20" } # original bg #e6b45033 -"ui.menu" = { fg = "foreground", bg = "black" } -"ui.menu.selected" = { bg = "gray", fg = "background" } -"ui.selection" = { bg = "dark_gray" } -"warning" = "yellow" -"error" = { fg = "red", modifiers = ["bold"] } -"info" = { fg = "blue", modifiers = ["bold"] } -"hint" = { fg = "blue", modifiers = ["bold"] } -"diagnostic.hint" = { underline = { color = "blue", style="curl"} } -"diagnostic.info"= { underline = { color = "blue", style="curl"} } -"diagnostic.warning"= { underline = { color = "yellow", style="curl"} } -"diagnostic.error"= { underline = { color = "red", style="curl"} } -"diagnostic.unnecessary" = { modifiers = ["dim"] } -"diagnostic.deprecated" = { modifiers = ["crossed_out"] } -"ui.bufferline" = { fg = "gray", bg = "background" } -"ui.bufferline.active" = { fg = "foreground", bg = "dark_gray" } -"ui.debug" = { fg = "orange", bg = "background" } -"ui.highlight.frameline" = { bg = "#0067a3" } -"ui.virtual.jump-label" = { fg = "red", modifiers = ["italic", "bold"] } - -"special" = "orange" - -[palette] -background = "#0f1419" -foreground = "#bfbdb6" - -black = "#131721" -blue = "#59c2ff" -dark_gray = "#2d3640" -cyan = "#73b8ff" -gray = "#5c6773" -green = "#aad94c" -magenta = "#d2a6ff" -orange = "#ff8f40" -red = "#f07178" -yellow = "#e6b450" diff --git a/vendor/themes/ayu_dark_helix.toml b/vendor/themes/ayu_dark_helix.toml new file mode 100644 index 00000000..a2fbc316 --- /dev/null +++ b/vendor/themes/ayu_dark_helix.toml @@ -0,0 +1,92 @@ +# Author: André Sá +# Based on the AYU theme colors from https://github.com/dempfi/ayu + +# Syntax highlighting +"type" = "blue" +"type.builtin" = "blue" +"constructor" = "green" +"constant" = "magenta" +"string" = "green" +"string.regexp" = "orange" +"string.special" = "yellow" +"comment" = { fg = "gray", modifiers = ["italic"] } +"variable" = "foreground" +"label" = "orange" +"punctuation" = "foreground" +"keyword" = "orange" +"keyword.control" = "yellow" +"keyword.directive" = "yellow" +"operator" = "orange" +"function" = "yellow" +"tag" = "blue" +"namespace" = "blue" +"markup.heading" = "orange" +"markup.list" = "yellow" +"markup.bold" = { fg = "orange", modifiers = ["bold"] } +"markup.italic" = { fg = "orange", modifiers = ["italic"] } +"markup.strikethrough" = { modifiers = ["crossed_out"] } +"markup.raw.block" = "orange" +"markup.link.url" = "blue" +"markup.link.text" = "yellow" +"markup.link.label" = "green" +"markup.quote" = "yellow" +"diff.plus" = "green" +"diff.minus" = "red" +"diff.delta" = "yellow" + +# Interface +"ui.background"= { bg = "background" } +"ui.cursor" = { fg = "dark_gray", bg = "yellow" } +"ui.cursor.primary" = { fg = "dark_gray", bg = "orange" } +"ui.cursor.match" = "orange" +"ui.linenr" = "dark_gray" +"ui.linenr.selected" = "gray" +"ui.statusline" = { fg = "foreground", bg = "black" } +"ui.statusline.normal" = { fg = "black", bg = "blue" } +"ui.statusline.insert" = { fg = "black", bg = "orange" } +"ui.statusline.select" = { fg = "black", bg = "magenta" } +"ui.cursorline" = { bg = "black" } +"ui.popup" = { fg = "#7B91b3", bg = "black" } +"ui.window" = "dark_gray" +"ui.help" = { fg = "#7B91b3", bg = "black" } +"ui.text" = "foreground" +"ui.text.focus" = { bg = "dark_gray", fg = "foreground" } +"ui.text.info" = "foreground" +"ui.virtual.whitespace" = "dark_gray" +"ui.virtual.ruler" = { bg = "black" } +"ui.virtual.inlay-hint" = { fg = "#e6b450", bg = "#302a20" } # original bg #e6b45033 +"ui.menu" = { fg = "foreground", bg = "black" } +"ui.menu.selected" = { bg = "gray", fg = "background" } +"ui.selection" = { bg = "dark_gray" } +"warning" = "yellow" +"error" = { fg = "red", modifiers = ["bold"] } +"info" = { fg = "blue", modifiers = ["bold"] } +"hint" = { fg = "blue", modifiers = ["bold"] } +"diagnostic.hint" = { underline = { color = "blue", style="curl"} } +"diagnostic.info"= { underline = { color = "blue", style="curl"} } +"diagnostic.warning"= { underline = { color = "yellow", style="curl"} } +"diagnostic.error"= { underline = { color = "red", style="curl"} } +"diagnostic.unnecessary" = { modifiers = ["dim"] } +"diagnostic.deprecated" = { modifiers = ["crossed_out"] } +"ui.bufferline" = { fg = "gray", bg = "background" } +"ui.bufferline.active" = { fg = "foreground", bg = "dark_gray" } +"ui.debug" = { fg = "orange", bg = "background" } +"ui.highlight.frameline" = { bg = "#0067a3" } +"ui.virtual.jump-label" = { fg = "red", modifiers = ["italic", "bold"] } + +"special" = "orange" + +[palette] +background = "#0f1419" +foreground = "#bfbdb6" + +black = "#131721" +blue = "#59c2ff" +dark_gray = "#2d3640" +cyan = "#73b8ff" +gray = "#5c6773" +green = "#aad94c" +magenta = "#d2a6ff" +orange = "#ff8f40" +red = "#f07178" +yellow = "#e6b450" diff --git a/vendor/themes/ayu_evolve.toml b/vendor/themes/ayu_evolve.toml index b9c5d822..7a1b1728 100644 --- a/vendor/themes/ayu_evolve.toml +++ b/vendor/themes/ayu_evolve.toml @@ -1,4 +1,4 @@ -inherits = 'ayu_dark' +inherits = 'ayu_dark_helix' "keyword.control" = "orange" "keyword.storage" = "yellow" diff --git a/vendor/themes/ayu_light.toml b/vendor/themes/ayu_light.toml deleted file mode 100644 index c3ab1d4f..00000000 --- a/vendor/themes/ayu_light.toml +++ /dev/null @@ -1,94 +0,0 @@ -# Author: André Sá -# Based on the AYU theme colors from https://github.com/dempfi/ayu - -# Syntax highlighting -"type" = "blue" -"type.builtin" = "blue" -"constructor" = "green" -"constant" = "magenta" -"string" = "green" -"string.regexp" = "orange" -"string.special" = "yellow" -"comment" = { fg = "gray", modifiers = ["italic"] } -"variable" = "foreground" -"label" = "orange" -"punctuation" = "foreground" -"keyword" = "orange" -"keyword.control" = "yellow" -"keyword.directive" = "yellow" -"operator" = "orange" -"function" = "yellow" -"tag" = "blue" -"namespace" = "blue" -"markup.heading" = "orange" -"markup.list" = "yellow" -"markup.bold" = { fg = "orange", modifiers = ["bold"] } -"markup.italic" = { fg = "orange", modifiers = ["italic"] } -"markup.strikethrough" = { modifiers = ["crossed_out"] } -"markup.raw.block" = "orange" -"markup.link.url" = { fg = "blue", modifiers = ["underlined"] } -"markup.link.text" = "yellow" -"markup.link.label" = "green" -"markup.quote" = "yellow" -"diff.plus" = "green" -"diff.minus" = "red" -"diff.delta" = "yellow" - -# Interface -"ui.background"= { bg = "background" } -"ui.cursor" = { fg = "dark_gray", bg = "yellow" } -"ui.cursor.primary" = { fg = "dark_gray", bg = "orange" } -"ui.cursor.match" = "orange" -"ui.linenr" = "dark_gray" -"ui.linenr.selected" = "gray" -"ui.statusline" = { fg = "foreground", bg = "black" } -"ui.statusline.normal" = { fg = "black", bg = "blue" } -"ui.statusline.insert" = { fg = "black", bg = "orange" } -"ui.statusline.select" = { fg = "black", bg = "magenta" } -"ui.cursorline" = { bg = "black" } -"ui.popup" = { fg = "#7B91b3", bg = "black" } -"ui.window" = "dark_gray" -"ui.help" = { fg = "#7B91b3", bg = "black" } -"ui.text" = "foreground" -"ui.text.focus" = { bg = "dark_gray", fg = "foreground" } -"ui.text.info" = "foreground" -"ui.virtual.whitespace" = "dark_gray" -"ui.virtual.ruler" = { bg = "black" } -"ui.virtual.inlay-hint" = { fg = "#f4a028", bg = "#fcf2e3" } # bg original #ffaa3333 -"ui.menu" = { fg = "foreground", bg = "black" } -"ui.menu.selected" = { bg = "gray", fg = "background" } -"ui.selection" = { bg = "dark_gray" } -"warning" = "yellow" -"error" = { fg = "red", modifiers = ["bold"] } -"info" = { fg = "blue", modifiers = ["bold"] } -"hint" = { fg = "blue", modifiers = ["bold"] } -"diagnostic.hint"= { underline = { color = "blue", style = "curl" } } -"diagnostic.info"= { underline = { color = "blue", style = "curl" } } -"diagnostic.warning"= { underline = { color = "yellow", style = "curl" } } -"diagnostic.error"= { underline = { color = "red", style = "curl" } } -"diagnostic.unnecessary" = { modifiers = ["dim"] } -"diagnostic.deprecated" = { modifiers = ["crossed_out"] } -"ui.bufferline" = { fg = "gray", bg = "background" } -"ui.bufferline.active" = { fg = "foreground", bg = "dark_gray" } -"ui.debug" = { fg = "orange", bg = "background" } -"ui.highlight.frameline" = { bg = "#cfe0f2" } -"ui.virtual.jump-label" = { fg = "red", modifiers = ["italic", "bold"] } - -"special" = "orange" - -[palette] -background = "#fafafa" -foreground = "#5c6166" - -black = "#e7eaed" -white = "#fcfcfc" -blue = "#399ee6" -light_blue = "#55b4d4" -cyan = "#478acc" -dark_gray = "#d8d8d7" -gray = "#828c9a" -green = "#86b300" -magenta = "#a37acc" -orange = "#fa8d3e" -red = "#f07171" -yellow = "#ffaa33" diff --git a/vendor/themes/ayu_mirage.toml b/vendor/themes/ayu_mirage.toml deleted file mode 100644 index 0fd53a4b..00000000 --- a/vendor/themes/ayu_mirage.toml +++ /dev/null @@ -1,92 +0,0 @@ -# Author: André Sá -# Based on the AYU theme colors from https://github.com/dempfi/ayu - -# Syntax highlighting -"type" = "blue" -"type.builtin" = "blue" -"constructor" = "green" -"constant" = "magenta" -"string" = "green" -"string.regexp" = "orange" -"string.special" = "yellow" -"comment" = { fg = "gray", modifiers = ["italic"] } -"variable" = "foreground" -"label" = "orange" -"punctuation" = "foreground" -"keyword" = "orange" -"keyword.control" = "yellow" -"keyword.directive" = "yellow" -"operator" = "orange" -"function" = "yellow" -"tag" = "blue" -"namespace" = "blue" -"markup.heading" = "orange" -"markup.list" = "yellow" -"markup.bold" = { fg = "orange", modifiers = ["bold"] } -"markup.italic" = { fg = "orange", modifiers = ["italic"] } -"markup.strikethrough" = { modifiers = ["crossed_out"] } -"markup.raw.block" = "orange" -"markup.link.url" = "blue" -"markup.link.text" = "yellow" -"markup.link.label" = "green" -"markup.quote" = "yellow" -"diff.plus" = "green" -"diff.minus" = "red" -"diff.delta" = "yellow" - -# Interface -"ui.background"= { bg = "background" } -"ui.cursor" = { fg = "dark_gray", bg = "yellow" } -"ui.cursor.primary" = { fg = "dark_gray", bg = "orange" } -"ui.cursor.match" = "orange" -"ui.linenr" = "dark_gray" -"ui.linenr.selected" = "gray" -"ui.statusline" = { fg = "foreground", bg = "black" } -"ui.statusline.normal" = { fg = "black", bg = "blue" } -"ui.statusline.insert" = { fg = "black", bg = "orange" } -"ui.statusline.select" = { fg = "black", bg = "magenta" } -"ui.cursorline" = { bg = "black" } -"ui.popup" = { fg = "#7B91b3", bg = "black" } -"ui.window" = "dark_gray" -"ui.help" = { fg = "#7B91b3", bg = "black" } -"ui.text" = "foreground" -"ui.text.focus" = { bg = "dark_gray", fg = "foreground" } -"ui.text.info" = "foreground" -"ui.virtual.whitespace" = "dark_gray" -"ui.virtual.ruler" = { bg = "black" } -"ui.virtual.inlay-hint" = { fg = "#ffcc66", bg = "#47433d" } # original bg #ffcc6633 -"ui.menu" = { fg = "foreground", bg = "black" } -"ui.menu.selected" = { bg = "gray", fg = "background" } -"ui.selection" = { bg = "dark_gray" } -"warning" = "yellow" -"error" = { fg = "red", modifiers = ["bold"] } -"info" = { fg = "blue", modifiers = ["bold"] } -"hint" = { fg = "blue", modifiers = ["bold"] } -"diagnostic.hint"= { underline = { color = "blue", style = "curl" } } -"diagnostic.info"= { underline = { color = "blue", style = "curl" } } -"diagnostic.warning"= { underline = { color = "yellow", style = "curl" } } -"diagnostic.error"= { underline = { color = "red", style = "curl" } } -"diagnostic.unnecessary" = { modifiers = ["dim"] } -"diagnostic.deprecated" = { modifiers = ["crossed_out"] } -"ui.bufferline" = { fg = "gray", bg = "background" } -"ui.bufferline.active" = { fg = "foreground", bg = "dark_gray" } -"ui.debug" = { fg = "orange", bg = "background" } -"ui.highlight.frameline" = { bg = "#0067a3" } -"ui.virtual.jump-label" = { fg = "red", modifiers = ["italic", "bold"] } - -"special" = "orange" - -[palette] -background = "#1f2430" -foreground = "#cccac2" - -black = "#1a1f29" -blue = "#73d0ff" -dark_gray = "#323843" -cyan = "#444b55" -gray = "#565b66" -green = "#d5ff80" -magenta = "#dfbfff" -orange = "#ffad66" -red = "#f28779" -yellow = "#ffcc77" diff --git a/vendor/themes/catppuccin_frappe.toml b/vendor/themes/catppuccin_frappe.toml deleted file mode 100644 index 232e19c3..00000000 --- a/vendor/themes/catppuccin_frappe.toml +++ /dev/null @@ -1,35 +0,0 @@ -inherits = "catppuccin_mocha" - -[palette] -rosewater = "#f2d5cf" -flamingo = "#eebebe" -pink = "#f4b8e4" -mauve = "#ca9ee6" -red = "#e78284" -maroon = "#ea999c" -peach = "#ef9f76" -yellow = "#e5c890" -green = "#a6d189" -teal = "#81c8be" -sky = "#99d1db" -sapphire = "#85c1dc" -blue = "#8caaee" -lavender = "#babbf1" -text = "#c6d0f5" -subtext1 = "#b5bfe2" -subtext0 = "#a5adce" -overlay2 = "#949cbb" -overlay1 = "#838ba7" -overlay0 = "#737994" -surface2 = "#626880" -surface1 = "#51576d" -surface0 = "#414559" -base = "#303446" -mantle = "#292c3c" -crust = "#232634" - -cursorline = "#3b3f52" -secondary_cursor = "#b8a5a6" -secondary_cursor_select = "#9192be" -secondary_cursor_normal = "#b8a5a6" -secondary_cursor_insert = "#83a275" diff --git a/vendor/themes/catppuccin_latte.toml b/vendor/themes/catppuccin_latte.toml deleted file mode 100644 index be47423d..00000000 --- a/vendor/themes/catppuccin_latte.toml +++ /dev/null @@ -1,35 +0,0 @@ -inherits = "catppuccin_mocha" - -[palette] -rosewater = "#dc8a78" -flamingo = "#dd7878" -pink = "#ea76cb" -mauve = "#8839ef" -red = "#d20f39" -maroon = "#e64553" -peach = "#fe640b" -yellow = "#df8e1d" -green = "#40a02b" -teal = "#179299" -sky = "#04a5e5" -sapphire = "#209fb5" -blue = "#1e66f5" -lavender = "#7287fd" -text = "#4c4f69" -subtext1 = "#5c5f77" -subtext0 = "#6c6f85" -overlay2 = "#7c7f93" -overlay1 = "#8c8fa1" -overlay0 = "#9ca0b0" -surface2 = "#acb0be" -surface1 = "#bcc0cc" -surface0 = "#ccd0da" -base = "#eff1f5" -mantle = "#e6e9ef" -crust = "#dce0e8" - -cursorline = "#e8ecf1" -secondary_cursor = "#e1a99d" -secondary_cursor_select = "#97a7fb" -secondary_cursor_normal = "#e1a99d" -secondary_cursor_insert = "#74b867" diff --git a/vendor/themes/catppuccin_macchiato.toml b/vendor/themes/catppuccin_macchiato.toml deleted file mode 100644 index 4f3f49cf..00000000 --- a/vendor/themes/catppuccin_macchiato.toml +++ /dev/null @@ -1,35 +0,0 @@ -inherits = "catppuccin_mocha" - -[palette] -rosewater = "#f4dbd6" -flamingo = "#f0c6c6" -pink = "#f5bde6" -mauve = "#c6a0f6" -red = "#ed8796" -maroon = "#ee99a0" -peach = "#f5a97f" -yellow = "#eed49f" -green = "#a6da95" -teal = "#8bd5ca" -sky = "#91d7e3" -sapphire = "#7dc4e4" -blue = "#8aadf4" -lavender = "#b7bdf8" -text = "#cad3f5" -subtext1 = "#b8c0e0" -subtext0 = "#a5adcb" -overlay2 = "#939ab7" -overlay1 = "#8087a2" -overlay0 = "#6e738d" -surface2 = "#5b6078" -surface1 = "#494d64" -surface0 = "#363a4f" -base = "#24273a" -mantle = "#1e2030" -crust = "#181926" - -cursorline = "#303347" -secondary_cursor = "#b6a6a7" -secondary_cursor_select = "#8b91bf" -secondary_cursor_normal = "#b6a6a7" -secondary_cursor_insert = "#80a57a" diff --git a/vendor/themes/catppuccin_mocha.toml b/vendor/themes/catppuccin_mocha.toml deleted file mode 100644 index e4cbea7f..00000000 --- a/vendor/themes/catppuccin_mocha.toml +++ /dev/null @@ -1,168 +0,0 @@ -# NOTE: For contributors looking to modify the theme, please submit a pull request at https://github.com/catppuccin/helix instead of updating this file. Changes are frequently synchronized from the catppuccin/helix theme repository. -# Syntax highlighting -# ------------------- -"attribute" = "yellow" - -"type" = "yellow" -"type.builtin" = "mauve" -"type.enum.variant" = "teal" - -"constructor" = "sapphire" - -"constant" = "peach" -"constant.character" = "teal" -"constant.character.escape" = "pink" - -"string" = "green" -"string.regexp" = "pink" -"string.special" = "blue" -"string.special.symbol" = "red" - -"comment" = { fg = "overlay2", modifiers = ["italic"] } - -"variable" = "text" -"variable.parameter" = { fg = "maroon", modifiers = ["italic"] } -"variable.builtin" = "red" -"variable.other.member" = "blue" - -"label" = "sapphire" # used for lifetimes - -"punctuation" = "overlay2" -"punctuation.special" = "sky" - -"keyword" = "mauve" -"keyword.control.conditional" = { fg = "mauve", modifiers = ["italic"] } - -"operator" = "sky" - -"function" = "blue" -"function.macro" = "rosewater" - -"tag" = "blue" - -"namespace" = { fg = "yellow", modifiers = ["italic"] } - -"special" = "blue" # fuzzy highlight - -"markup.heading.1" = "red" -"markup.heading.2" = "peach" -"markup.heading.3" = "yellow" -"markup.heading.4" = "green" -"markup.heading.5" = "sapphire" -"markup.heading.6" = "lavender" -"markup.list" = "teal" -"markup.list.unchecked" = "overlay2" -"markup.list.checked" = "green" -"markup.bold" = { fg = "red", modifiers = ["bold"] } -"markup.italic" = { fg = "red", modifiers = ["italic"] } -"markup.strikethrough" = { modifiers = ["crossed_out"] } -"markup.link.url" = { fg = "blue", modifiers = ["italic", "underlined"] } -"markup.link.text" = "lavender" -"markup.link.label" = "sapphire" -"markup.raw" = "green" -"markup.quote" = "pink" - -"diff.plus" = "green" -"diff.minus" = "red" -"diff.delta" = "blue" - -# User Interface -# -------------- -"ui.background" = { fg = "text", bg = "base" } - -"ui.linenr" = { fg = "surface1" } -"ui.linenr.selected" = { fg = "lavender" } - -"ui.statusline" = { fg = "subtext1", bg = "mantle" } -"ui.statusline.inactive" = { fg = "surface2", bg = "mantle" } -"ui.statusline.normal" = { fg = "base", bg = "rosewater", modifiers = ["bold"] } -"ui.statusline.insert" = { fg = "base", bg = "green", modifiers = ["bold"] } -"ui.statusline.select" = { fg = "base", bg = "lavender", modifiers = ["bold"] } - -"ui.popup" = { fg = "text", bg = "surface0" } -"ui.window" = { fg = "crust" } -"ui.help" = { fg = "overlay2", bg = "surface0" } - -"ui.bufferline" = { fg = "subtext0", bg = "mantle" } -"ui.bufferline.active" = { fg = "mauve", bg = "base", underline = { color = "mauve", style = "line" } } -"ui.bufferline.background" = { bg = "crust" } - -"ui.text" = "text" -"ui.text.focus" = { fg = "text", bg = "surface0", modifiers = ["bold"] } -"ui.text.inactive" = { fg = "overlay1" } -"ui.text.directory" = { fg = "blue" } - -"ui.virtual" = "overlay0" -"ui.virtual.ruler" = { bg = "surface0" } -"ui.virtual.indent-guide" = "surface0" -"ui.virtual.inlay-hint" = { fg = "surface1", bg = "mantle" } -"ui.virtual.jump-label" = { fg = "rosewater", modifiers = ["bold"] } - -"ui.selection" = { bg = "surface1" } - -"ui.cursor" = { fg = "base", bg = "secondary_cursor" } -"ui.cursor.primary" = { fg = "base", bg = "rosewater" } -"ui.cursor.match" = { fg = "peach", modifiers = ["bold"] } - -"ui.cursor.primary.normal" = { fg = "base", bg = "rosewater" } -"ui.cursor.primary.insert" = { fg = "base", bg = "green" } -"ui.cursor.primary.select" = { fg = "base", bg = "lavender" } - -"ui.cursor.normal" = { fg = "base", bg = "secondary_cursor_normal" } -"ui.cursor.insert" = { fg = "base", bg = "secondary_cursor_insert" } -"ui.cursor.select" = { fg = "base", bg = "secondary_cursor_select" } - -"ui.cursorline.primary" = { bg = "cursorline" } - -"ui.highlight" = { bg = "surface1", modifiers = ["bold"] } - -"ui.menu" = { fg = "overlay2", bg = "surface0" } -"ui.menu.selected" = { fg = "text", bg = "surface1", modifiers = ["bold"] } - -"diagnostic.error" = { underline = { color = "red", style = "curl" } } -"diagnostic.warning" = { underline = { color = "yellow", style = "curl" } } -"diagnostic.info" = { underline = { color = "sky", style = "curl" } } -"diagnostic.hint" = { underline = { color = "teal", style = "curl" } } -"diagnostic.unnecessary" = { modifiers = ["dim"] } -"diagnostic.deprecated" = { modifiers = ["crossed_out"] } - -error = "red" -warning = "yellow" -info = "sky" -hint = "teal" - -rainbow = ["red", "peach", "yellow", "green", "sapphire", "lavender"] - -[palette] -rosewater = "#f5e0dc" -flamingo = "#f2cdcd" -pink = "#f5c2e7" -mauve = "#cba6f7" -red = "#f38ba8" -maroon = "#eba0ac" -peach = "#fab387" -yellow = "#f9e2af" -green = "#a6e3a1" -teal = "#94e2d5" -sky = "#89dceb" -sapphire = "#74c7ec" -blue = "#89b4fa" -lavender = "#b4befe" -text = "#cdd6f4" -subtext1 = "#bac2de" -subtext0 = "#a6adc8" -overlay2 = "#9399b2" -overlay1 = "#7f849c" -overlay0 = "#6c7086" -surface2 = "#585b70" -surface1 = "#45475a" -surface0 = "#313244" -base = "#1e1e2e" -mantle = "#181825" -crust = "#11111b" - -cursorline = "#2a2b3c" -secondary_cursor = "#b5a6a8" -secondary_cursor_select = "#878ec0" -secondary_cursor_normal = "#b5a6a8" -secondary_cursor_insert = "#7ea87f" diff --git a/vendor/themes/dark_plus.toml b/vendor/themes/dark_plus.toml deleted file mode 100644 index fcb25e77..00000000 --- a/vendor/themes/dark_plus.toml +++ /dev/null @@ -1,138 +0,0 @@ -# Author: David Else <12832280+David-Else@users.noreply.github.com> - -# SYNTAX -"attribute" = "variable" -"comment" = "dark_green" -"constant" = "constant" -"constant.builtin" = "blue2" -"constant.character" = "orange" -"constant.character.escape" = "gold" -"constant.numeric" = "pale_green" -"constructor" = "type" -"diff.delta" = "blue4" -"diff.minus" = "orange_red" -"diff.plus" = "dark_green2" -"function" = "fn_declaration" -"function.builtin" = "fn_declaration" -"function.macro" = "blue2" -"keyword" = "blue2" -"keyword.control" = "special" -"keyword.directive" = "special" -"label" = "blue2" -"module" = "type" -"namespace" = "type" -"operator" = "text" -"punctuation" = "text" -"punctuation.delimiter" = "text" -"special" = "light_blue" -"string" = "orange" -"string.regexp" = "gold" -"tag" = "blue2" -"type" = "type" -"type.builtin" = "type" -"type.enum.variant" = "constant" -"variable" = "variable" -"variable.mutable" = { fg = "variable", underline.style= "line" } -"variable.builtin" = "blue2" -"variable.builtin.mutable" = { fg = "blue2", underline.style= "line" } -"variable.other.member" = "variable" -"variable.parameter" = "variable" -"variable.parameter.mutable" = { fg = "variable", underline.style= "line" } - -# MARKUP -"markup.heading" = { fg = "blue2", modifiers = ["bold"] } -"markup.list" = "blue3" -"markup.bold" = { modifiers = ["bold"] } -"markup.italic" = { modifiers = ["italic"] } -"markup.strikethrough" = { modifiers = ["crossed_out"] } -"markup.link.url" = { underline.style= "line" } -"markup.link.text" = "orange" -"markup.quote" = "dark_green" -"markup.raw" = "orange" - -# UI -"ui.background" = { fg = "light_gray", bg = "dark_gray2" } -"ui.window" = { bg = "widget" } -"ui.popup" = { fg = "text", bg = "widget" } -"ui.help" = { fg = "text", bg = "widget" } -"ui.menu" = { fg = "text", bg = "widget" } -"ui.menu.selected" = { bg = "dark_blue2" } -# TODO: Alternate bg colour for `ui.cursor.match` and `ui.selection`. -"ui.cursor" = { fg = "cursor", modifiers = ["reversed"] } -"ui.cursor.primary" = { fg = "cursor", modifiers = ["reversed"] } -"ui.cursor.match" = { bg = "#3a3d41", underline.style = "line" } -"ui.selection" = { bg = "#3a3d41" } -"ui.selection.primary" = { bg = "dark_blue" } -"ui.linenr" = { fg = "dark_gray" } -"ui.linenr.selected" = { fg = "light_gray2" } -"ui.cursorline.primary" = { bg = "dark_gray3" } -"ui.statusline" = { fg = "white", bg = "blue" } -"ui.statusline.inactive" = { fg = "white", bg = "widget" } -"ui.statusline.insert" = { fg = "white", bg = "yellow" } -"ui.statusline.select" = { fg = "white", bg = "magenta" } -"ui.bufferline" = { fg = "text", bg = "widget" } -"ui.bufferline.active" = { fg = "white", bg = "blue" } -"ui.bufferline.background" = { bg = "background" } -"ui.text" = { fg = "text" } -"ui.text.focus" = { fg = "white" } -"ui.text.directory" = { fg = "blue2" } -"ui.text.inactive" = { fg = "dark_gray" } -"ui.virtual.whitespace" = { fg = "#3e3e3d" } -"ui.virtual.wrap" = { fg = "#3e3e3d" } -"ui.virtual.ruler" = { bg = "borders" } -"ui.virtual.indent-guide" = { fg = "dark_gray4" } -"ui.virtual.inlay-hint" = { fg = "dark_gray5"} -"ui.virtual.jump-label" = { fg = "yellow", modifiers = ["bold"] } -"ui.highlight.frameline" = { bg = "#4b4b18" } -"ui.debug.active" = { fg = "#ffcc00" } -"ui.debug.breakpoint" = { fg = "#e51400" } -"ui.picker.header.column" = { underline.style = "line" } -"ui.picker.header.column.active" = { fg ="white", underline.style = "line" } -"warning" = { fg = "gold2" } -"error" = { fg = "red" } -"info" = { fg = "light_blue" } -"hint" = { fg = "light_gray3" } -"diagnostic.error".underline = { color = "red", style = "curl" } -"diagnostic".underline = { color = "gold", style = "curl" } -"diagnostic.unnecessary" = { modifiers = ["dim"] } -"diagnostic.deprecated" = { modifiers = ["crossed_out"] } - -rainbow = ["#FFD700", "#DA70D6", "#179FFF"] - -[palette] -white = "#ffffff" -orange = "#ce9178" -gold = "#d7ba7d" -gold2 = "#cca700" -pale_green = "#b5cea8" -dark_green = "#6A9955" -dark_green2 = "#487e02" -light_gray = "#d4d4d4" -light_gray2 = "#c6c6c6" -light_gray3 = "#eeeeee" -dark_gray = "#858585" -dark_gray2 = "#1e1e1e" -dark_gray3 = "#282828" -dark_gray4 = "#404040" -dark_gray5 = "#8b949e" -blue = "#007acc" -blue2 = "#569CD6" -blue3 = "#6796E6" -blue4 = "#1b81a8" -light_blue = "#75beff" -dark_blue = "#264f78" -dark_blue2 = "#094771" -red = "#ff1212" -orange_red = "#f14c4c" - -type = "#4EC9B0" -special = "#C586C0" -variable = "#9CDCFE" -fn_declaration = "#DCDCAA" -constant = "#4FC1FF" - -background = "#1e1e1e" -text = "#d4d4d4" -cursor = "#a6a6a6" -widget = "#252526" -borders = "#323232" diff --git a/vendor/themes/doom-one.LICENSE b/vendor/themes/doom-one.LICENSE deleted file mode 100644 index 1d0112f1..00000000 --- a/vendor/themes/doom-one.LICENSE +++ /dev/null @@ -1,23 +0,0 @@ -MIT License - -Copyright (c) 2025 NTBBloodbath - -This theme has been ported by spentbliss . - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/vendor/themes/doom-one.toml b/vendor/themes/doom-one.toml deleted file mode 100644 index 60dbd874..00000000 --- a/vendor/themes/doom-one.toml +++ /dev/null @@ -1,127 +0,0 @@ -# Author: spentbliss -# License: MIT (originally by NTBBloodbath) - -"ui.background" = { bg = "bg", fg = "fg" } -"ui.text" = "fg" -"ui.text.focus" = { bg = "bg_highlight", fg = "cyan" } -"ui.cursor" = { bg = "cyan", fg = "bg" } -"ui.linenr" = "grey" -"ui.linenr.selected" = "yellow" -"ui.statusline" = { fg = "blue" } -"ui.selection" = { bg = "bg_highlight" } -"ui.selection.primary" = { bg = "bg_highlight" } -"ui.virtual.ruler" = { bg = "bg_highlight" } -"ui.virtual.jump-label" = { fg = "cyan", modifiers = ["bold"] } - -# Markdown Highlighting -"markup.raw" = { fg = "blue", bg = "bg" } -"markup.raw.inline" = { fg = "orange" } -"markup.heading.1" = { fg = "#E99BEA", bg = "#4F4258"} -"markup.heading.2" = { fg = "#51AFEF", bg = "#2F4456" } -"markup.heading.3" = { fg = "#A9A1E1", bg = "#3F4153" } -"markup.heading.4" = { fg = "#98BE65", bg = "#3C453D" } -"markup.heading.5" = { fg = "#ECBE7B", bg = "#4B4641" } -"markup.heading.6" = { fg = "#DA8549", bg = "#483C39" } -"markup.list" = { fg = "magenta" } -"markup.bold" = { fg = "orange", modifiers = ["bold"] } -"markup.italic" = { fg = "orange" } -"markup.strikethrough" = { fg = "red", modifiers = ["crossed_out"] } -"markup.link" = { fg = "cyan" } -"markup.quote" = { fg = "fg" } - -# Syntax Highlighting for Code -"comment" = { fg = "grey" } -"comment.line" = { fg = "grey" } -"comment.block" = { fg = "grey" } -"comment.documentation" = { fg = "blue" } - -"keyword" = "blue" -"keyword.control" = "blue" -"keyword.operator" = "fg" -"keyword.function" = "blue" -"keyword.directive" = "green" -"keyword.storage" = "blue" - -"type" = "yellow" -"type.builtin" = "yellow" -"type.enum.variant" = "purple" - -"function" = "magenta" -"function.builtin" = "fg" -"function.method" = "fg" -"function.macro" = "purple" - -"variable" = "fg" -"variable.builtin" = "red" -"variable.parameter" = "fg" - -"string" = "green" -"string.special" = "green" - -"constant" = "orange" -"constant.builtin" = "orange" -"constant.numeric" = "orange" -"constant.character" = "orange" -"constant.boolean" = "orange" - -"attribute" = "magenta" -"operator" = "blue" -"tag" = { fg = "magenta", modifiers = ["bold"] } -"tag.special" = { fg = "orange", modifiers = ["bold"] } -"namespace" = "blue" -"macro" = "orange" -"label" = "red" - -# Interface specific -"ui.cursorline.primary" = { bg = "bg_highlight" } -"ui.cursorline.secondary" = { bg = "bg_alt" } -"ui.cursorcolumn.primary" = { bg = "bg_highlight" } -"ui.cursorcolumn.secondary" = { bg = "bg_alt" } -"ui.statusline.normal" = { fg = "bg", bg = "blue" } -"ui.statusline.insert" = { fg = "bg", bg = "green" } -"ui.statusline.select" = { fg = "bg", bg = "purple" } - -# Git changes indicator -"diff.plus" = "green" -"diff.plus.gutter" = "green" -"diff.minus" = "red" -"diff.minus.gutter" = "red" -"diff.delta" = "green" -"diff.delta.gutter" = "green" -"diff.delta.moved" = "orange" -"diff.delta.conflict" = "purple" - -# Diagnostic styles -"warning" = { fg = "yellow", modifiers = ["bold"] } -"error" = { fg = "red", modifiers = ["bold"] } -"info" = { fg = "cyan", modifiers = ["bold"] } -"hint" = { fg = "blue", modifiers = ["bold"] } -"diagnostic.error" = { fg = "red" } -"diagnostic.warning" = { fg = "yellow" } -"diagnostic.info" = { fg = "cyan" } -"diagnostic.hint" = { fg = "blue" } - -# Popups for documentation or file picker -"ui.popup" = { fg = "fg", bg = "bg" } -"ui.popup.info" = { fg = "fg", bg = "bg_alt" } -"ui.menu" = { fg = "fg", bg = "bg" } -"ui.menu.selected" = { fg = "cyan", bg = "bg_highlight" } - -# Additional overrides -"ui.virtual.whitespace" = "grey" -"ui.virtual.indent-guide" = { fg = "grey" } - -[palette] -bg = "#282C34" -fg = "#BBC2CF" -grey = "#5B6268" -blue = "#51AFEF" -green = "#98BE65" -cyan = "#46D9FF" -red = "#FF6C6B" -yellow = "#ECBE7B" -purple = "#A8A1E1" -magenta = "#C678DD" -orange = "#DA8548" -bg_alt = "#21242B" -bg_highlight = "#3C4048" diff --git a/vendor/themes/dracula.toml b/vendor/themes/dracula.toml deleted file mode 100644 index 8b4abe16..00000000 --- a/vendor/themes/dracula.toml +++ /dev/null @@ -1,159 +0,0 @@ -# Author : Sebastian Zivota -# Author : Chirikumbrah - -"annotation" = { fg = "foreground" } - -"attribute" = { fg = "green", modifiers = ["italic"] } - -"comment" = { fg = "comment" } -"comment.block" = { fg = "comment" } -"comment.block.documentation" = { fg = "comment" } -"comment.line" = { fg = "comment" } -"comment.line.documentation" = { fg = "comment" } - -"constant" = { fg = "purple" } -"constant.builtin" = { fg = "purple" } -"constant.builtin.boolean" = { fg = "purple" } -"constant.character" = { fg = "cyan" } -"constant.character.escape" = { fg = "pink" } -"constant.macro" = { fg = "purple" } -"constant.numeric" = { fg = "purple" } -"constructor" = { fg = "purple" } - -"definition" = { underline = { color = "cyan" } } - -"diagnostic" = { underline = { color = "orange", style = "curl" } } -"diagnostic.hint" = { underline = { color = "purple", style = "curl" } } -"diagnostic.warning" = { underline = { color = "yellow", style = "curl" } } -"diagnostic.error" = { underline = { color = "red", style = "curl" } } -"diagnostic.info" = { underline = { color = "cyan", style = "curl" } } -"diagnostic.unnecessary" = { modifiers = ["dim"] } -"diagnostic.deprecated" = { modifiers = ["crossed_out"] } - -"error" = { fg = "red" } -"hint" = { fg = "purple" } -"info" = { fg = "cyan" } -"warning" = { fg = "yellow" } - -"diff.delta" = { fg = "orange" } -"diff.minus" = { fg = "red" } -"diff.plus" = { fg = "green" } - -# d -"function" = { fg = "green" } -"function.builtin" = { fg = "green" } -"function.call" = { fg = "green" } -"function.macro" = { fg = "purple" } -"function.method" = { fg = "green" } - -"keyword" = { fg = "pink" } -"keyword.control.conditional" = { fg = "pink" } -"keyword.control.exception" = { fg = "purple" } -"keyword.control.import" = { fg = "pink" } -"keyword.control.repeat" = { fg = "pink" } -"keyword.directive" = { fg = "green" } -"keyword.function" = { fg = "pink" } -"keyword.operator" = { fg = "pink" } -"keyword.return" = { fg = "pink" } -"keyword.storage" = { fg = "pink" } -"keyword.storage.modifier" = { fg = "pink" } -"keyword.storage.type" = { fg = "cyan", modifiers = ["italic"] } - -"label" = { fg = "cyan" } - -"markup.bold" = { fg = "orange", modifiers = ["bold"] } -"markup.heading" = { fg = "purple", modifiers = ["bold"] } -"markup.italic" = { fg = "yellow", modifiers = ["italic"] } -"markup.link.text" = { fg = "pink" } -"markup.link.url" = { fg = "cyan" } -"markup.list" = { fg = "cyan" } -"markup.quote" = { fg = "yellow", modifiers = ["italic"] } -"markup.raw" = { fg = "foreground" } -"markup.strikethrough" = { modifiers = ["crossed_out"] } - -"punctuation" = { fg = "foreground" } -"punctuation.bracket" = { fg = "foreground" } -"punctuation.delimiter" = { fg = "foreground" } -"punctuation.special" = { fg = "pink" } - -"special" = { fg = "pink" } - -"string" = { fg = "yellow" } -"string.regexp" = { fg = "red" } -"string.special" = { fg = "orange" } -"string.symbol" = { fg = "yellow" } - -"tag" = { fg = "pink" } -"tag.attribute" = { fg = "purple" } -"tag.delimiter" = { fg = "foreground" } - -"type" = { fg = "cyan", modifiers = ["italic"] } -"type.builtin" = { fg = "cyan" } -"type.enum.variant" = { fg = "foreground", modifiers = ["italic"] } - -"ui.background" = { fg = "foreground", bg = "background" } -"ui.cursor" = { fg = "background", bg = "purple", modifiers = ["dim"] } -"ui.cursor.insert" = { fg = "background", bg = "green", modifiers = ["dim"] } -"ui.cursor.match" = { fg = "foreground", bg = "grey" } -"ui.cursor.normal" = { fg = "background", bg = "purple", modifiers = ["dim"] } -"ui.cursor.primary.insert" = { fg = "background", bg = "green" } -"ui.cursor.primary.normal" = { fg = "background", bg = "purple" } -"ui.cursor.primary.select" = { fg = "background", bg = "cyan" } -"ui.cursor.select" = { fg = "background", bg = "cyan", modifiers = ["dim"] } -"ui.cursorline.primary" = { bg = "cursorline" } -"ui.debug" = { fg = "red" } -"ui.help" = { fg = "foreground", bg = "black" } -"ui.highlight.frameline" = { fg = "background", bg = "red" } -"ui.linenr" = { fg = "comment" } -"ui.linenr.selected" = { fg = "foreground" } -"ui.menu" = { fg = "foreground", bg = "current_line" } -"ui.menu.scroll" = { fg = "foreground", bg = "current_line" } -"ui.menu.selected" = { fg = "current_line", bg = "purple", modifiers = ["dim"] } -"ui.popup" = { fg = "foreground", bg = "black" } -"ui.selection" = { bg = "selection" } -"ui.selection.primary" = { bg = "current_line" } -"ui.statusline" = { fg = "foreground", bg = "darker" } -"ui.statusline.inactive" = { fg = "comment", bg = "darker" } -"ui.statusline.insert" = { fg = "black", bg = "green", modifiers = ["bold"] } -"ui.statusline.normal" = { fg = "black", bg = "purple", modifiers = ["bold"] } -"ui.statusline.select" = { fg = "black", bg = "cyan", modifiers = ["bold"] } -"ui.text" = { fg = "foreground" } -"ui.text.focus" = { fg = "cyan" } -"ui.text.directory" = { fg = "cyan" } -"ui.virtual.indent-guide" = { fg = "indent" } -"ui.virtual.inlay-hint" = { fg = "cyan" } -"ui.virtual.inlay-hint.parameter" = { fg = "cyan", modifiers = ["italic", "dim"] } -"ui.virtual.inlay-hint.type" = { fg = "cyan", modifiers = ["italic", "dim"] } -"ui.virtual.jump-label" = { fg = "pink", modifiers = ["bold"] } -"ui.virtual.ruler" = { bg = "black" } -"ui.virtual.whitespace" = { fg = "whitespace" } -"ui.virtual.wrap" = { fg = "current_line" } -"ui.window" = { fg = "foreground" } - -"variable" = { fg = "foreground" } -"variable.builtin" = { fg = "purple", modifiers = ["italic"] } -"variable.other" = { fg = "foreground" } -"variable.other.member" = { fg = "foreground" } -"variable.parameter" = { fg = "orange", modifiers = ["italic"] } - - -[palette] -background = "#282A36" -black = "#191A21" -comment = "#6272A4" -current_line = "#44475a" -cursorline = "#2d303e" -cyan = "#8be9fd" -darker = "#222430" -foreground = "#f8f8f2" -green = "#50fa7b" -grey = "#666771" -indent = "#56596a" -orange = "#ffb86c" -pink = "#ff79c6" -purple = "#BD93F9" -red = "#ff5555" -selection = "#363848" -whitespace = "#586693" -yellow = "#f1fa8c" - diff --git a/vendor/themes/molokai.toml b/vendor/themes/molokai.toml index 0e48f775..a2562180 100644 --- a/vendor/themes/molokai.toml +++ b/vendor/themes/molokai.toml @@ -1,6 +1,6 @@ # Author : Maxwell Anderson -inherits = "monokai" +inherits = "monokai_helix" "comment" = "comment" "comment.block.documentation" = { fg = "comment", modifiers = ["bold"] } diff --git a/vendor/themes/monokai.toml b/vendor/themes/monokai.toml deleted file mode 100644 index dfa7040c..00000000 --- a/vendor/themes/monokai.toml +++ /dev/null @@ -1,121 +0,0 @@ -# Author: Shafkath Shuhan - -"tag" = { fg = "tag" } - -"namespace" = { fg = "type" } -"module" = { fg = "type" } - -"type" = { fg = "type" } -"type.builtin" = { fg = "#66D9EF" } -"type.enum.variant" = { fg = "text" } -"constructor" = { fg = "fn_declaration" } -"variable.other.member" = { fg = "variable" } - -"keyword" = { fg = "keyword" } -"keyword.directive" = { fg = "keyword" } -"keyword.control" = { fg = "keyword" } -"label" = { fg = "keyword" } - -"special" = { fg = "keyword" } -"operator" = { fg = "text" } - -"punctuation" = { fg = "text" } -"punctuation.delimiter" = { fg = "text" } - -"variable" = { fg = "variable" } -"variable.parameter" = { fg = "#fd971f" } -"variable.builtin" = { fg = "keyword" } -"constant" = { fg = "variable" } -"constant.builtin" = { fg = "#ae81ff" } - -"function" = { fg = "fn_declaration" } -"function.builtin" = { fg = "fn_declaration" } -"function.macro" = { fg = "keyword" } -"attribute" = { fg = "fn_declaration" } - -"comment" = { fg = "#88846F" } -"ui.virtual.whitespace" = "#88846F" -"ui.virtual.ruler" = { bg = "#24241e" } -"ui.virtual.jump-label" = { fg = "special", modifiers = ["bold"] } - -"string" = { fg = "#e6db74" } -"constant.character" = { fg = "#e6db74" } -"string.regexp" = { fg = "regex" } -"constant.numeric" = { fg = "#ae81ff" } -"constant.character.escape" = { fg = "#ae81ff" } - -# TODO -"markup.heading" = "blue" -"markup.list" = "red" -"markup.bold" = { fg = "yellow", modifiers = ["bold"] } -"markup.italic" = { fg = "magenta", modifiers = ["italic"] } -"markup.strikethrough" = { modifiers = ["crossed_out"] } -"markup.link.url" = { fg = "yellow", modifiers = ["underlined"] } -"markup.link.text" = "red" -"markup.quote" = "cyan" -"markup.raw" = "green" - -"diff.plus" = { fg = "#a6e22e" } -"diff.delta" = { fg = "#fd971f" } -"diff.minus" = { fg = "#f92672" } - -"ui.background" = { fg = "text", bg = "background" } - -"ui.window" = { bg = "widget" } -"ui.popup" = { fg = "text", bg = "widget" } -"ui.help" = { fg = "text", bg = "widget" } -"ui.menu" = { fg = "text", bg = "widget" } -"ui.menu.selected" = { bg = "#414339" } - -"ui.cursor" = { fg = "cursor", modifiers = ["reversed"] } -"ui.cursor.primary" = { fg = "cursor", modifiers = ["reversed"] } -"ui.cursor.match" = { fg = "#888888", modifiers = ["reversed"] } - -"ui.selection" = { bg = "#878b91" } -"ui.selection.primary" = { bg = "#575b61" } - -"ui.linenr" = { fg = "#90908a" } -"ui.linenr.selected" = { fg = "#c2c2bf" } - -"ui.cursorline" = { bg = "#24241e" } -"ui.statusline" = { fg = "active_text", bg = "#414339" } -"ui.statusline.inactive" = { fg = "active_text", bg = "#75715e" } - -# Malformed ANSI: grey2, bg3. See 'https://github.com/helix-editor/helix/issues/5709' -# "ui.bufferline" = { fg = "grey2", bg = "bg3" } -"ui.bufferline.active" = { fg = "active_text", bg = "selection", modifiers = [ - "bold", -] } -"ui.virtual.inlay-hint" = { fg = "#88846F" } - -"ui.text" = { fg = "text" } -"ui.text.focus" = { fg = "active_text" } - -"warning" = { fg = "#cca700" } -"error" = { fg = "#f48771" } -"info" = { fg = "#75beff" } -"hint" = { fg = "#eeeeb3" } - -"diagnostic.warning" = { underline = { color = "#cca700", style = "curl" } } -"diagnostic.error" = { underline = { color = "#f48771", style = "curl" } } -"diagnostic.info" = { underline = { color = "#75beff", style = "curl" } } -"diagnostic.hint" = { underline = { color = "#eeeeb3", style = "curl" } } -"diagnostic.unnecessary" = { modifiers = ["dim"] } -"diagnostic.deprecated" = { modifiers = ["crossed_out"] } - -[palette] -type = "#A6E22E" -keyword = "#F92672" -regex = "#CE9178" -special = "#C586C0" -variable = "#F8F8F2" -fn_declaration = "#A6E22E" - -background = "#272822" -text = "#f8f8f2" -active_text = "#ffffff" -cursor = "#a6a6a6" -inactive_cursor = "#878b91" -widget = "#1e1f1c" -selection = "#414339" -tag = "#F92672" diff --git a/vendor/themes/monokai_aqua.toml b/vendor/themes/monokai_aqua.toml index b818a09e..61672230 100644 --- a/vendor/themes/monokai_aqua.toml +++ b/vendor/themes/monokai_aqua.toml @@ -1,4 +1,4 @@ -inherits = "monokai" +inherits = "monokai_helix" "keyword.control.import" = { fg = "cyan", modifiers = ["italic"] } "keyword.function" = { fg = "cyan", modifiers = ["italic"] } diff --git a/vendor/themes/monokai_helix.toml b/vendor/themes/monokai_helix.toml new file mode 100644 index 00000000..dfa7040c --- /dev/null +++ b/vendor/themes/monokai_helix.toml @@ -0,0 +1,121 @@ +# Author: Shafkath Shuhan + +"tag" = { fg = "tag" } + +"namespace" = { fg = "type" } +"module" = { fg = "type" } + +"type" = { fg = "type" } +"type.builtin" = { fg = "#66D9EF" } +"type.enum.variant" = { fg = "text" } +"constructor" = { fg = "fn_declaration" } +"variable.other.member" = { fg = "variable" } + +"keyword" = { fg = "keyword" } +"keyword.directive" = { fg = "keyword" } +"keyword.control" = { fg = "keyword" } +"label" = { fg = "keyword" } + +"special" = { fg = "keyword" } +"operator" = { fg = "text" } + +"punctuation" = { fg = "text" } +"punctuation.delimiter" = { fg = "text" } + +"variable" = { fg = "variable" } +"variable.parameter" = { fg = "#fd971f" } +"variable.builtin" = { fg = "keyword" } +"constant" = { fg = "variable" } +"constant.builtin" = { fg = "#ae81ff" } + +"function" = { fg = "fn_declaration" } +"function.builtin" = { fg = "fn_declaration" } +"function.macro" = { fg = "keyword" } +"attribute" = { fg = "fn_declaration" } + +"comment" = { fg = "#88846F" } +"ui.virtual.whitespace" = "#88846F" +"ui.virtual.ruler" = { bg = "#24241e" } +"ui.virtual.jump-label" = { fg = "special", modifiers = ["bold"] } + +"string" = { fg = "#e6db74" } +"constant.character" = { fg = "#e6db74" } +"string.regexp" = { fg = "regex" } +"constant.numeric" = { fg = "#ae81ff" } +"constant.character.escape" = { fg = "#ae81ff" } + +# TODO +"markup.heading" = "blue" +"markup.list" = "red" +"markup.bold" = { fg = "yellow", modifiers = ["bold"] } +"markup.italic" = { fg = "magenta", modifiers = ["italic"] } +"markup.strikethrough" = { modifiers = ["crossed_out"] } +"markup.link.url" = { fg = "yellow", modifiers = ["underlined"] } +"markup.link.text" = "red" +"markup.quote" = "cyan" +"markup.raw" = "green" + +"diff.plus" = { fg = "#a6e22e" } +"diff.delta" = { fg = "#fd971f" } +"diff.minus" = { fg = "#f92672" } + +"ui.background" = { fg = "text", bg = "background" } + +"ui.window" = { bg = "widget" } +"ui.popup" = { fg = "text", bg = "widget" } +"ui.help" = { fg = "text", bg = "widget" } +"ui.menu" = { fg = "text", bg = "widget" } +"ui.menu.selected" = { bg = "#414339" } + +"ui.cursor" = { fg = "cursor", modifiers = ["reversed"] } +"ui.cursor.primary" = { fg = "cursor", modifiers = ["reversed"] } +"ui.cursor.match" = { fg = "#888888", modifiers = ["reversed"] } + +"ui.selection" = { bg = "#878b91" } +"ui.selection.primary" = { bg = "#575b61" } + +"ui.linenr" = { fg = "#90908a" } +"ui.linenr.selected" = { fg = "#c2c2bf" } + +"ui.cursorline" = { bg = "#24241e" } +"ui.statusline" = { fg = "active_text", bg = "#414339" } +"ui.statusline.inactive" = { fg = "active_text", bg = "#75715e" } + +# Malformed ANSI: grey2, bg3. See 'https://github.com/helix-editor/helix/issues/5709' +# "ui.bufferline" = { fg = "grey2", bg = "bg3" } +"ui.bufferline.active" = { fg = "active_text", bg = "selection", modifiers = [ + "bold", +] } +"ui.virtual.inlay-hint" = { fg = "#88846F" } + +"ui.text" = { fg = "text" } +"ui.text.focus" = { fg = "active_text" } + +"warning" = { fg = "#cca700" } +"error" = { fg = "#f48771" } +"info" = { fg = "#75beff" } +"hint" = { fg = "#eeeeb3" } + +"diagnostic.warning" = { underline = { color = "#cca700", style = "curl" } } +"diagnostic.error" = { underline = { color = "#f48771", style = "curl" } } +"diagnostic.info" = { underline = { color = "#75beff", style = "curl" } } +"diagnostic.hint" = { underline = { color = "#eeeeb3", style = "curl" } } +"diagnostic.unnecessary" = { modifiers = ["dim"] } +"diagnostic.deprecated" = { modifiers = ["crossed_out"] } + +[palette] +type = "#A6E22E" +keyword = "#F92672" +regex = "#CE9178" +special = "#C586C0" +variable = "#F8F8F2" +fn_declaration = "#A6E22E" + +background = "#272822" +text = "#f8f8f2" +active_text = "#ffffff" +cursor = "#a6a6a6" +inactive_cursor = "#878b91" +widget = "#1e1f1c" +selection = "#414339" +tag = "#F92672" diff --git a/vendor/themes/monokai_pro.toml b/vendor/themes/monokai_pro.toml deleted file mode 100644 index 97f2a57c..00000000 --- a/vendor/themes/monokai_pro.toml +++ /dev/null @@ -1,134 +0,0 @@ -# Author : WindSoilder -# The unofficial Monokai Pro theme, simply migrate from jetbrains monokai pro theme: https://github.com/subtheme-dev/monokai-pro -# Credit goes to the original creator: https://monokai.pro - -"ui.linenr.selected" = { bg = "base3" } -"ui.text.focus" = { fg = "yellow", modifiers= ["bold"] } -"ui.menu" = { fg = "base8", bg = "base3" } -"ui.menu.selected" = { fg = "base2", bg = "yellow" } -"ui.virtual.whitespace" = "base5" -"ui.virtual.ruler" = { bg = "base1" } -"ui.virtual.jump-label" = { fg = "red", modifiers = ["bold"] } - -"info" = "base8" -"hint" = "base8" - -# background color -"ui.background" = { bg = "base2" } - -# status bars, panels, modals, autocompletion -"ui.statusline" = { fg = "base8", bg = "base4" } -"ui.statusline.inactive" = { fg = "base8", bg = "base8x0c" } -"ui.statusline.normal" = { fg = "base4", bg = "blue" } -"ui.statusline.insert" = { fg = "base4", bg = "green" } -"ui.statusline.select" = { fg = "base4", bg = "purple" } -"ui.popup" = { bg = "base3" } -"ui.window" = { bg = "base3" } -"ui.help" = { fg = "base8", bg = "base3" } - -# active line, highlighting -"ui.selection" = { bg = "base4" } -"ui.cursor.match" = { bg = "base4" } -"ui.cursorline" = { bg = "base1" } - -# bufferline, inlay hints -"ui.bufferline" = { fg = "base6", bg = "base8x0c" } -"ui.bufferline.active" = { fg = "base8", bg = "base4" } -"ui.virtual.inlay-hint" = { fg = "base6" } - -# comments, nord3 based lighter color -"comment" = { fg = "base5", modifiers = ["italic"] } -"ui.linenr" = { fg = "base5" } - -# cursor, variables, constants, attributes, fields -"ui.cursor.primary" = { fg = "base7", modifiers = ["reversed"] } -"attribute" = "blue" -"variable" = "base8" -"constant" = "orange" -"variable.builtin" = "red" -"constant.builtin" = "red" -"namespace" = "base8" - -# base text, punctuation -"ui.text" = { fg = "base8" } -"punctuation" = "base6" - -# classes, types, primitives -"type" = "green" -"type.builtin" = { fg = "red"} -"label" = "base8" - -# declaration, methods, routines -"constructor" = "blue" -"function" = "green" -"function.macro" = { fg = "blue" } -"function.builtin" = { fg = "cyan" } - -# operator, tags, units, punctuations -"operator" = "red" -"variable.other.member" = "base8" - -# keywords, special -"keyword" = { fg = "red" } -"keyword.directive" = "blue" -"variable.parameter" = "#f59762" - -# error -"error" = "red" - -# annotations, decorators -"special" = "#f59762" -"module" = "#f59762" - -# warnings, escape characters, regex -"warning" = "orange" -"constant.character.escape" = { fg = "base8" } - -# strings -"string" = "yellow" - -# integer, floating point -"constant.numeric" = "purple" - -# vcs -"diff.plus" = "green" -"diff.delta" = "orange" -"diff.minus" = "red" - -# make diagnostic underlined, to distinguish with selection text. -"diagnostic.warning" = { underline = { color = "orange", style = "curl" } } -"diagnostic.error" = { underline = { color = "red", style = "curl" } } -"diagnostic.info" = { underline = { color = "base8", style = "curl" } } -"diagnostic.hint" = { underline = { color = "base8", style = "curl" } } -"diagnostic.unnecessary" = { modifiers = ["dim"] } -"diagnostic.deprecated" = { modifiers = ["crossed_out"] } - -# markup highlight, no need for `markup.raw` and `markup.list`, make them to be default -"markup.heading" = "green" -"markup.bold" = { fg = "orange", modifiers = ["bold"] } -"markup.italic" = { fg = "orange", modifiers = ["italic"] } -"markup.strikethrough" = { modifiers = ["crossed_out"] } -"markup.link.url" = { fg = "orange", modifiers = ["underlined"] } -"markup.link.text" = "yellow" -"markup.quote" = "green" - -[palette] -# primary colors -"red" = "#ff6188" -"orange" = "#fc9867" -"yellow" = "#ffd866" -"green" = "#a9dc76" -"blue" = "#78dce8" -"purple" = "#ab9df2" -# base colors, sorted from darkest to lightest -"base0" = "#19181a" -"base1" = "#221f22" -"base2" = "#2d2a2e" -"base3" = "#403e41" -"base4" = "#5b595c" -"base5" = "#727072" -"base6" = "#939293" -"base7" = "#c1c0c0" -"base8" = "#fcfcfa" -# variants (for when transparency isn't supported) -"base8x0c" = "#363337" # using base2 as bg diff --git a/vendor/themes/monokai_pro_machine.toml b/vendor/themes/monokai_pro_machine.toml deleted file mode 100644 index e1f74b1c..00000000 --- a/vendor/themes/monokai_pro_machine.toml +++ /dev/null @@ -1,131 +0,0 @@ -# Author : WindSoilder -# The unofficial Monokai Pro theme, simply migrate from jetbrains monokai pro theme: https://github.com/subtheme-dev/monokai-pro -# Credit goes to the original creator: https://monokai.pro - -"ui.linenr.selected" = { bg = "base3" } -"ui.text.focus" = { fg = "yellow", modifiers= ["bold"] } -"ui.menu" = { fg = "base8", bg = "base3" } -"ui.menu.selected" = { fg = "base2", bg = "yellow" } -"ui.virtual.whitespace" = "base5" -"ui.virtual.ruler" = { bg = "base1" } -"ui.virtual.jump-label" = { fg = "red", modifiers = ["bold"] } - -"info" = "base8" -"hint" = "base8" - -# background color -"ui.background" = { bg = "base2" } -"ui.statusline.inactive" = { fg = "base8", bg = "base8x0c" } - -# status bars, panels, modals, autocompletion -"ui.statusline" = { fg = "base8", bg = "base4" } -"ui.popup" = { bg = "base3" } -"ui.window" = { bg = "base3" } -"ui.help" = { fg = "base8", bg = "base3" } - -# active line, highlighting -"ui.selection" = { bg = "base4" } -"ui.cursor.match" = { bg = "base4" } -"ui.cursorline" = { bg = "base1" } - -# bufferline, inlay hints -"ui.bufferline" = { fg = "base6", bg = "base8x0c" } -"ui.bufferline.active" = { fg = "base8", bg = "base4" } -"ui.virtual.inlay-hint" = { fg = "base6" } - -# comments, nord3 based lighter color -"comment" = { fg = "base5", modifiers = ["italic"] } -"ui.linenr" = { fg = "base5" } - -# cursor, variables, constants, attributes, fields -"ui.cursor.primary" = { fg = "base7", modifiers = ["reversed"] } -"attribute" = "blue" -"variable" = "base8" -"constant" = "orange" -"variable.builtin" = "red" -"constant.builtin" = "red" -"namespace" = "base8" - -# base text, punctuation -"ui.text" = { fg = "base8" } -"punctuation" = "base6" - -# classes, types, primitives -"type" = "green" -"type.builtin" = { fg = "red"} -"label" = "base8" - -# declaration, methods, routines -"constructor" = "blue" -"function" = "green" -"function.macro" = { fg = "blue" } -"function.builtin" = { fg = "cyan" } - -# operator, tags, units, punctuations -"operator" = "red" -"variable.other.member" = "base8" - -# keywords, special -"keyword" = { fg = "red" } -"keyword.directive" = "blue" -"variable.parameter" = "#f59762" - -# error -"error" = "red" - -# annotations, decorators -"special" = "#f59762" -"module" = "#f59762" - -# warnings, escape characters, regex -"warning" = "orange" -"constant.character.escape" = { fg = "base8" } - -# strings -"string" = "yellow" - -# integer, floating point -"constant.numeric" = "purple" - -# vcs -"diff.plus" = "green" -"diff.delta" = "orange" -"diff.minus" = "red" - -# make diagnostic underlined, to distinguish with selection text. -"diagnostic.warning" = { underline = { color = "orange", style = "curl" } } -"diagnostic.error" = { underline = { color = "red", style = "curl" } } -"diagnostic.info" = { underline = { color = "base8", style = "curl" } } -"diagnostic.hint" = { underline = { color = "base8", style = "curl" } } -"diagnostic.unnecessary" = { modifiers = ["dim"] } -"diagnostic.deprecated" = { modifiers = ["crossed_out"] } - -# markup highlight, no need for `markup.raw` and `markup.list`, make them to be default -"markup.heading" = "green" -"markup.bold" = { fg = "orange", modifiers = ["bold"] } -"markup.italic" = { fg = "orange", modifiers = ["italic"] } -"markup.strikethrough" = { modifiers = ["crossed_out"] } -"markup.link.url" = { fg = "orange", modifiers = ["underlined"] } -"markup.link.text" = "yellow" -"markup.quote" = "green" - -[palette] -# primary colors -"red" = "#ff6d7e" -"orange" = "#ffb270" -"yellow" = "#ffed72" -"green" = "#a2e57b" -"blue" = "#7cd5f1" -"purple" = "#baa0f8" -# base colors -"base0" = "#161b1e" -"base1" = "#1d2528" -"base2" = "#273136" -"base3" = "#3a4449" -"base4" = "#545f62" -"base5" = "#6b7678" -"base6" = "#798384" -"base7" = "#b8c4c3" -"base8" = "#f2fffc" -# variants -"base8x0c" = "#303a3e" diff --git a/vendor/themes/monokai_pro_octagon.toml b/vendor/themes/monokai_pro_octagon.toml deleted file mode 100644 index cfa85b65..00000000 --- a/vendor/themes/monokai_pro_octagon.toml +++ /dev/null @@ -1,134 +0,0 @@ -# Author : WindSoilder -# The unofficial Monokai Pro theme, simply migrate from jetbrains monokai pro theme: https://github.com/subtheme-dev/monokai-pro -# Credit goes to the original creator: https://monokai.pro - -"ui.linenr.selected" = { bg = "base3" } -"ui.text.focus" = { fg = "yellow", modifiers= ["bold"] } -"ui.menu" = { fg = "base8", bg = "base3" } -"ui.menu.selected" = { fg = "base2", bg = "yellow" } -"ui.virtual.whitespace" = "base5" -"ui.virtual.ruler" = { bg = "base1" } -"ui.virtual.jump-label" = { fg = "red", modifiers = ["bold"] } - -"info" = "base8" -"hint" = "base8" - -# background color -"ui.background" = { bg = "base2" } -"ui.statusline.inactive" = { fg = "base8", bg = "base8x0c" } - -# status bars, panels, modals, autocompletion -"ui.statusline" = { fg = "base8", bg = "base4" } -"ui.statusline.normal" = { fg = "base4", bg = "blue" } -"ui.statusline.insert" = { fg = "base4", bg = "green" } -"ui.statusline.select" = { fg = "base4", bg = "purple" } -"ui.popup" = { bg = "base3" } -"ui.window" = { bg = "base3" } -"ui.help" = { fg = "base8", bg = "base3" } - -# active line, highlighting -"ui.selection" = { bg = "base4" } -"ui.cursor.match" = { bg = "base4" } -"ui.cursorline" = { bg = "base1" } - -# bufferline, inlay hints -"ui.bufferline" = { fg = "base6", bg = "base8x0c" } -"ui.bufferline.active" = { fg = "base8", bg = "base4" } -"ui.virtual.inlay-hint" = { fg = "base6" } - -# comments, nord3 based lighter color -"comment" = { fg = "base5", modifiers = ["italic"] } -"ui.linenr" = { fg = "base5" } - -# cursor, variables, constants, attributes, fields -"ui.cursor.primary" = { fg = "base7", modifiers = ["reversed"] } -"attribute" = "blue" -"variable" = "base8" -"constant" = "orange" -"variable.builtin" = "red" -"constant.builtin" = "red" -"namespace" = "base8" - -# base text, punctuation -"ui.text" = { fg = "base8" } -"punctuation" = "base6" - -# classes, types, primitives -"type" = "green" -"type.builtin" = { fg = "red"} -"label" = "base8" - -# declaration, methods, routines -"constructor" = "blue" -"function" = "green" -"function.macro" = { fg = "blue" } -"function.builtin" = { fg = "cyan" } - -# operator, tags, units, punctuations -"operator" = "red" -"variable.other.member" = "base8" - -# keywords, special -"keyword" = { fg = "red" } -"keyword.directive" = "blue" -"variable.parameter" = "#f59762" - -# error -"error" = "red" - -# annotations, decorators -"special" = "#f59762" -"module" = "#f59762" - -# warnings, escape characters, regex -"warning" = "orange" -"constant.character.escape" = { fg = "base8" } - -# strings -"string" = "yellow" - -# integer, floating point -"constant.numeric" = "purple" - -# vcs -"diff.plus" = "green" -"diff.delta" = "orange" -"diff.minus" = "red" - -# make diagnostic underlined, to distinguish with selection text. -"diagnostic.warning" = { underline = { color = "orange", style = "curl" } } -"diagnostic.error" = { underline = { color = "red", style = "curl" } } -"diagnostic.info" = { underline = { color = "base8", style = "curl" } } -"diagnostic.hint" = { underline = { color = "base8", style = "curl" } } -"diagnostic.unnecessary" = { modifiers = ["dim"] } -"diagnostic.deprecated" = { modifiers = ["crossed_out"] } - -# markup highlight, no need for `markup.raw` and `markup.list`, make them to be default -"markup.heading" = "green" -"markup.bold" = { fg = "orange", modifiers = ["bold"] } -"markup.italic" = { fg = "orange", modifiers = ["italic"] } -"markup.strikethrough" = { modifiers = ["crossed_out"] } -"markup.link.url" = { fg = "orange", modifiers = ["underlined"] } -"markup.link.text" = "yellow" -"markup.quote" = "green" - -[palette] -# primary colors -"red" = "#ff657a" -"orange" = "#ff9b5e" -"yellow" = "#ffd76d" -"green" = "#bad761" -"blue" = "#9cd1bb" -"purple" = "#c39ac9" -# base colors -"base0" = "#161821" -"base1" = "#1e1f2b" -"base2" = "#282a3a" -"base3" = "#3a3d4b" -"base4" = "#535763" -"base5" = "#696d77" -"base6" = "#767b81" -"base7" = "#b2b9bd" -"base8" = "#eaf2f1" -# variants -"base8x0c" = "#303342" diff --git a/vendor/themes/monokai_pro_ristretto.toml b/vendor/themes/monokai_pro_ristretto.toml deleted file mode 100644 index a6ba6fcf..00000000 --- a/vendor/themes/monokai_pro_ristretto.toml +++ /dev/null @@ -1,131 +0,0 @@ -# Author : WindSoilder -# The unofficial Monokai Pro theme, simply migrate from jetbrains monokai pro theme: https://github.com/subtheme-dev/monokai-pro -# Credit goes to the original creator: https://monokai.pro - -"ui.linenr.selected" = { bg = "base3" } -"ui.text.focus" = { fg = "yellow", modifiers= ["bold"] } -"ui.menu" = { fg = "base8", bg = "base3" } -"ui.menu.selected" = { fg = "base2", bg = "yellow" } -"ui.virtual.whitespace" = "base5" -"ui.virtual.ruler" = { bg = "base1" } -"ui.virtual.jump-label" = { fg = "red", modifiers = ["bold"] } - -"info" = "base8" -"hint" = "base8" - -# background color -"ui.background" = { bg = "base2" } -"ui.statusline.inactive" = { fg = "base8", bg = "base8x0c" } - -# status bars, panels, modals, autocompletion -"ui.statusline" = { fg = "base8", bg = "base4" } -"ui.popup" = { bg = "base3" } -"ui.window" = { bg = "base3" } -"ui.help" = { fg = "base8", bg = "base3" } - -# active line, highlighting -"ui.selection" = { bg = "base4" } -"ui.cursor.match" = { bg = "base4" } -"ui.cursorline" = { bg = "base1" } - -# bufferline, inlay hints -"ui.bufferline" = { fg = "base6", bg = "base8x0c" } -"ui.bufferline.active" = { fg = "base8", bg = "base4" } -"ui.virtual.inlay-hint" = { fg = "base6" } - -# comments, nord3 based lighter color -"comment" = { fg = "base5", modifiers = ["italic"] } -"ui.linenr" = { fg = "base5" } - -# cursor, variables, constants, attributes, fields -"ui.cursor.primary" = { fg = "base7", modifiers = ["reversed"] } -"attribute" = "blue" -"variable" = "base8" -"constant" = "orange" -"variable.builtin" = "red" -"constant.builtin" = "red" -"namespace" = "base8" - -# base text, punctuation -"ui.text" = { fg = "base8" } -"punctuation" = "base6" - -# classes, types, primitives -"type" = "green" -"type.builtin" = { fg = "red"} -"label" = "base8" - -# declaration, methods, routines -"constructor" = "blue" -"function" = "green" -"function.macro" = { fg = "blue" } -"function.builtin" = { fg = "cyan" } - -# operator, tags, units, punctuations -"operator" = "red" -"variable.other.member" = "base8" - -# keywords, special -"keyword" = { fg = "red" } -"keyword.directive" = "blue" -"variable.parameter" = "#f59762" - -# error -"error" = "red" - -# annotations, decorators -"special" = "#f59762" -"module" = "#f59762" - -# warnings, escape characters, regex -"warning" = "orange" -"constant.character.escape" = { fg = "base8" } - -# strings -"string" = "yellow" - -# integer, floating point -"constant.numeric" = "purple" - -# vcs -"diff.plus" = "green" -"diff.delta" = "orange" -"diff.minus" = "red" - -# make diagnostic underlined, to distinguish with selection text. -"diagnostic.warning" = { underline = { color = "orange", style = "curl" } } -"diagnostic.error" = { underline = { color = "red", style = "curl" } } -"diagnostic.info" = { underline = { color = "base8", style = "curl" } } -"diagnostic.hint" = { underline = { color = "base8", style = "curl" } } -"diagnostic.unnecessary" = { modifiers = ["dim"] } -"diagnostic.deprecated" = { modifiers = ["crossed_out"] } - -# markup highlight, no need for `markup.raw` and `markup.list`, make them to be default -"markup.heading" = "green" -"markup.bold" = { fg = "orange", modifiers = ["bold"] } -"markup.italic" = { fg = "orange", modifiers = ["italic"] } -"markup.strikethrough" = { modifiers = ["crossed_out"] } -"markup.link.url" = { fg = "orange", modifiers = ["underlined"] } -"markup.link.text" = "yellow" -"markup.quote" = "green" - -[palette] -# primary colors -"red" = "#fd6883" -"orange" = "#f38d70" -"yellow" = "#f9cc6c" -"green" = "#adda78" -"blue" = "#85dacc" -"purple" = "#a8a9eb" -# base colors -"base0" = "#191515" -"base1" = "#211c1c" -"base2" = "#2c2525" -"base3" = "#403838" -"base4" = "#5b5353" -"base5" = "#72696a" -"base6" = "#8c8384" -"base7" = "#c3b7b8" -"base8" = "#fff1f3" -# variants -"base8x0c" = "#352e2e" diff --git a/vendor/themes/monokai_pro_spectrum.toml b/vendor/themes/monokai_pro_spectrum.toml deleted file mode 100644 index 1bfcb688..00000000 --- a/vendor/themes/monokai_pro_spectrum.toml +++ /dev/null @@ -1,131 +0,0 @@ -# Author : WindSoilder -# The unofficial Monokai Pro theme, simply migrate from jetbrains monokai pro theme: https://github.com/subtheme-dev/monokai-pro -# Credit goes to the original creator: https://monokai.pro - -"ui.linenr.selected" = { bg = "base3" } -"ui.text.focus" = { fg = "yellow", modifiers= ["bold"] } -"ui.menu" = { fg = "base8", bg = "base3" } -"ui.menu.selected" = { fg = "base2", bg = "yellow" } -"ui.virtual.whitespace" = "base4" -"ui.virtual.ruler" = { bg = "base1" } -"ui.virtual.jump-label" = { fg = "red", modifiers = ["bold"] } - -"info" = "base8" -"hint" = "base8" - -# background color -"ui.background" = { bg = "base2" } - -# status bars, panels, modals, autocompletion -"ui.statusline" = { fg = "base8", bg = "base4" } -"ui.statusline.inactive" = { fg = "base8", bg = "base8x0c" } -"ui.popup" = { bg = "base3" } -"ui.window" = { bg = "base3" } -"ui.help" = { fg = "base8", bg = "base3" } - -# active line, highlighting -"ui.selection" = { bg = "base4" } -"ui.cursor.match" = { bg = "base4" } -"ui.cursorline" = { bg = "base1" } - -# bufferline, inlay hints -"ui.bufferline" = { fg = "base6", bg = "base8x0c" } -"ui.bufferline.active" = { fg = "base8", bg = "base4" } -"ui.virtual.inlay-hint" = { fg = "base6" } - -# comments, nord3 based lighter color -"comment" = { fg = "base5", modifiers = ["italic"] } -"ui.linenr" = { fg = "base5" } - -# cursor, variables, constants, attributes, fields -"ui.cursor.primary" = { fg = "base7", modifiers = ["reversed"] } -"attribute" = "blue" -"variable" = "base8" -"constant" = "orange" -"variable.builtin" = "red" -"constant.builtin" = "red" -"namespace" = "base8" - -# base text, punctuation -"ui.text" = { fg = "base8" } -"punctuation" = "base6" - -# classes, types, primitives -"type" = "green" -"type.builtin" = { fg = "red"} -"label" = "base8" - -# declaration, methods, routines -"constructor" = "blue" -"function" = "green" -"function.macro" = { fg = "blue" } -"function.builtin" = { fg = "blue" } - -# operator, tags, units, punctuations -"operator" = "red" -"variable.other.member" = "base8" - -# keywords, special -"keyword" = { fg = "red" } -"keyword.directive" = "blue" -"variable.parameter" = "#f59762" - -# error -"error" = { fg = "red", modifiers = ["bold"] } - -# annotations, decorators -"special" = "#f59762" -"module" = "#f59762" - -# warnings, escape characters, regex -"warning" = "orange" -"constant.character.escape" = { fg = "base8" } - -# strings -"string" = "yellow" - -# integer, floating point -"constant.numeric" = "purple" - -# vcs -"diff.plus" = "green" -"diff.delta" = "orange" -"diff.minus" = "red" - -# make diagnostic underlined, to distinguish with selection text. -"diagnostic.warning" = { underline = { color = "orange", style = "curl" } } -"diagnostic.error" = { underline = { color = "red", style = "curl" } } -"diagnostic.info" = { underline = { color = "base8", style = "curl" } } -"diagnostic.hint" = { underline = { color = "base8", style = "curl" } } -"diagnostic.unnecessary" = { modifiers = ["dim"] } -"diagnostic.deprecated" = { modifiers = ["crossed_out"] } - -# markup highlight, no need for `markup.raw` and `markup.list`, make them to be default -"markup.heading" = "green" -"markup.bold" = { fg = "orange", modifiers = ["bold"] } -"markup.italic" = { fg = "orange", modifiers = ["italic"] } -"markup.strikethrough" = { modifiers = ["crossed_out"] } -"markup.link.url" = { fg = "orange", modifiers = ["underlined"] } -"markup.link.text" = "yellow" -"markup.quote" = "green" - -[palette] -# primary colors -"red" = "#fc618d" -"orange" = "#fd9353" -"yellow" = "#fce566" -"green" = "#7bd88f" -"blue" = "#5ad4e6" -"purple" = "#948ae3" -# base colors -"base0" = "#131313" -"base1" = "#191919" -"base2" = "#222222" -"base3" = "#363537" -"base4" = "#525053" -"base5" = "#69676c" -"base6" = "#8b888f" -"base7" = "#bab6c0" -"base8" = "#f7f1ff" -# variants -"base8x0c" = "#2b2b2b" diff --git a/vendor/themes/nord-night.toml b/vendor/themes/nord-night.toml index b759738b..92fc35bf 100644 --- a/vendor/themes/nord-night.toml +++ b/vendor/themes/nord-night.toml @@ -4,7 +4,7 @@ # The Background and the Primary Text color have been slightly darkened. # The Aurora color palette has been used more generously. -inherits = 'nord' +inherits = 'nord_helix' 'constant' = 'nord13' 'constant.builtin.boolean' = 'nord13' diff --git a/vendor/themes/nord.toml b/vendor/themes/nord.toml deleted file mode 100644 index db7b6190..00000000 --- a/vendor/themes/nord.toml +++ /dev/null @@ -1,199 +0,0 @@ -# Nord (Dark Ambiance) port for Helix (https://helix-editor.com/) -# https://docs.helix-editor.com/themes.html -# https://www.nordtheme.com/docs/colors-and-palettes - -## SYNTAX HIGHLIGHTING - -# Constants -"constant" = "nord4" -"constant.builtin" = "nord9" -"constant.builtin.boolean" = "nord9" -"constant.builtin.character" = "nord15" -"constant.character.escape" = "nord13" -"constant.macro" = "nord9" -"constant.numeric" = "nord15" -"constructor" = "nord8" - -# Diagnostics -"diagnostic" = { underline = { color = "nord13", style = "curl" } } -"diagnostic.error" = { underline = { color = "nord11", style = "curl" } } -"error" = "nord11" -"diagnostic.hint" = { underline = { color = "nord10", style = "curl" } } -"hint" = "nord10" -"diagnostic.info" = { underline = { color = "nord8", style = "curl" } } -"info" = "nord8" -"diagnostic.warning" = { underline = { color = "nord13", style = "curl" } } -"warning" = "nord13" -"diagnostic.unnecessary" = { modifiers = ["dim"] } -"diagnostic.deprecated" = { modifiers = ["crossed_out"] } - -# Diffs -"diff.delta" = "nord13" -"diff.minus" = "nord11" -"diff.plus" = "nord14" - -# Functions -"function" = "nord8" -"function.builtin" = "nord7" -"function.method" = "nord8" -"function.macro" = "nord9" -"function.special" = "nord9" - -# Git -"git.delta.moved" = "nord12" - -# Keywords -"keyword" = "nord9" -"keyword.control.conditional" = "nord9" -"keyword.control.exception" = "nord9" -"keyword.control.repeat" = "nord9" -"keyword.directive" = "nord9" -"keyword.function" = "nord9" -"keyword.operator" = "nord9" -"keyword.return" = "nord9" -"keyword.storage.modifier" = "nord9" -"keyword.storage.type" = "nord9" - -# Punctuation -"punctuation" = "nord6" -"punctuation.bracket" = "nord6" -"punctuation.delimiter" = "nord6" -"punctuation.special" = "nord9" - -# Strings -"string" = "nord14" -"string.escape" = "nord13" -"string.regex" = "nord13" -"string.special" = "nord13" - -# Types -"type" = "nord7" -"type.builtin" = "nord7" - -# Variables -"variable" = "nord4" -"variable.builtin" = "nord9" -"variable.other.member" = "nord4" -"variable.parameter" = "nord8" -"attribute" = "nord9" - -# Misc. -"label" = "nord7" -"namespace" = "nord4" -"operator" = "nord9" -"special" = "nord9" -"tag" = "nord7" -"comment" = { fg = "nord3_bright", modifiers = ["italic"] } - -## EDITOR UI COLORS - -"ui.background" = { bg = "nord0" } -"ui.text" = "nord4" -"ui.window" = "nord1" - -# Debug -"ui.debug.active" = "nord13" -"ui.debug.breakpoint" = "nord11" - -# Popus and menus -"ui.menu" = { bg = "nord1" } -"ui.menu.scroll" = { fg = "nord4", bg = "nord3" } -"ui.menu.selected" = { fg = "nord8", bg = "nord2" } -"ui.popup" = { bg = "nord1" } -"ui.popup.info" = { bg = "nord1" } -"ui.help" = { bg = "nord1" } -"ui.text.focus" = { fg = "nord8", bg = "nord2" } - -# Gutter -"ui.gutter" = "nord5" -"ui.linenr" = "nord3" -"ui.linenr.selected" = "nord5" - -# Cursor -"ui.cursor" = { fg = "nord4", modifiers = ["reversed"] } -"ui.cursorcolumn.primary" = { bg = "nord1" } -"ui.cursorline.primary" = { bg = "nord1" } -"ui.cursor.match" = { bg = "nord3" } - -"ui.selection" = { bg = "nord3" } -"ui.highlight" = { fg = "nord8", bg = "nord2" } - -# Statusline -"ui.statusline" = { bg = "nord1" } -"ui.statusline.inactive" = { fg = "nord8", bg = "nord1" } -"ui.statusline.insert" = { fg = "nord1", bg = "nord6" } -"ui.statusline.normal" = { fg = "nord1", bg = "nord8" } -"ui.statusline.select" = { fg = "nord1", bg = "nord7" } -"ui.statusline.separator" = "nord3" - -# Virtual/invisible text -"ui.virtual.indent-guide" = "nord3" -"ui.virtual.inlay-hint" = { fg = "nord3", modifiers = ["italic"] } -"ui.virtual.jump-label" = { fg = "nord11", modifiers = ["bold"] } -"ui.virtual.ruler" = { bg = "nord1" } -"ui.virtual.whitespace" = "nord3" -"ui.virtual.wrap" = "nord3" - -# Bufferline -"ui.bufferline" = { fg = "nord5", bg = "nord1" } -"ui.bufferline.active" = { fg = "nord6", bg = "nord2", underline = { color = "nord8", style = "line" }, modifiers = [ - "italic", -] } - -# Markup -"markup.heading" = "nord8" -"markup.list" = "nord9" -"markup.bold" = { modifiers = ["bold"] } -"markup.italic" = { modifiers = ["italic"] } -"markup.strikethrough" = { modifiers = ["crossed_out"] } -"markup.link.text" = "nord8" -"markup.raw" = "nord7" - -# Rainbow brackets -rainbow = ["nord13", "nord15", "nord14", "nord12"] - -[palette] -# Polar Night is made up of four darker colors that are commonly used for base elements like backgrounds or text color in bright ambiance designs. -# -# The origin color or the Polar Night palette -nord0 = "#2e3440" -# A brighter shade color based on nord0 -nord1 = "#3B4252" -# An even more brighter shade color of nord0 -nord2 = "#434C5E" -# The brightest shade color based on nord0 -nord3 = "#4C566A" -# 10% brighter for comments, see https://github.com/nordtheme/nord/issues/94 -nord3_bright = "#616e88" - -# Snow Storm is made up of three bright colors that are commonly used for text colors or base UI elements in bright ambiance designs. -# The origin color or the Snow Storm palette -nord4 = "#D8DEE9" -# A brighter shade color of nord4 -nord5 = "#E5E9F0" -# The brightest shade color based on nord4 -nord6 = "#ECEFF4" - -# Frost can be described as the heart palette of Nord, a group of four bluish colors that are commonly used for primary UI component and text highlighting and essential code syntax elements. -# -# A calm and highly contrasted color reminiscent of frozen polar water -nord7 = "#8FBCBB" -# The bright and shiny primary accent color reminiscent of pure and clear ice -nord8 = "#88C0D0" -# A more darkened and less saturated color reminiscent of arctic waters -nord9 = "#81A1C1" -# A dark and intensive color reminiscent of the deep arctic ocean -nord10 = "#5E81AC" - -# Aurora consists of five colorful components reminiscent of the "Aurora borealis", sometimes referred to as polar lights or northern lights. -# -# Red -nord11 = "#BF616A" -# Orange -nord12 = "#D08770" -# Yellow -nord13 = "#EBCB8B" -# Green -nord14 = "#A3BE8C" -# Purple -nord15 = "#B48EAD" diff --git a/vendor/themes/nord_helix.toml b/vendor/themes/nord_helix.toml new file mode 100644 index 00000000..db7b6190 --- /dev/null +++ b/vendor/themes/nord_helix.toml @@ -0,0 +1,199 @@ +# Nord (Dark Ambiance) port for Helix (https://helix-editor.com/) +# https://docs.helix-editor.com/themes.html +# https://www.nordtheme.com/docs/colors-and-palettes + +## SYNTAX HIGHLIGHTING + +# Constants +"constant" = "nord4" +"constant.builtin" = "nord9" +"constant.builtin.boolean" = "nord9" +"constant.builtin.character" = "nord15" +"constant.character.escape" = "nord13" +"constant.macro" = "nord9" +"constant.numeric" = "nord15" +"constructor" = "nord8" + +# Diagnostics +"diagnostic" = { underline = { color = "nord13", style = "curl" } } +"diagnostic.error" = { underline = { color = "nord11", style = "curl" } } +"error" = "nord11" +"diagnostic.hint" = { underline = { color = "nord10", style = "curl" } } +"hint" = "nord10" +"diagnostic.info" = { underline = { color = "nord8", style = "curl" } } +"info" = "nord8" +"diagnostic.warning" = { underline = { color = "nord13", style = "curl" } } +"warning" = "nord13" +"diagnostic.unnecessary" = { modifiers = ["dim"] } +"diagnostic.deprecated" = { modifiers = ["crossed_out"] } + +# Diffs +"diff.delta" = "nord13" +"diff.minus" = "nord11" +"diff.plus" = "nord14" + +# Functions +"function" = "nord8" +"function.builtin" = "nord7" +"function.method" = "nord8" +"function.macro" = "nord9" +"function.special" = "nord9" + +# Git +"git.delta.moved" = "nord12" + +# Keywords +"keyword" = "nord9" +"keyword.control.conditional" = "nord9" +"keyword.control.exception" = "nord9" +"keyword.control.repeat" = "nord9" +"keyword.directive" = "nord9" +"keyword.function" = "nord9" +"keyword.operator" = "nord9" +"keyword.return" = "nord9" +"keyword.storage.modifier" = "nord9" +"keyword.storage.type" = "nord9" + +# Punctuation +"punctuation" = "nord6" +"punctuation.bracket" = "nord6" +"punctuation.delimiter" = "nord6" +"punctuation.special" = "nord9" + +# Strings +"string" = "nord14" +"string.escape" = "nord13" +"string.regex" = "nord13" +"string.special" = "nord13" + +# Types +"type" = "nord7" +"type.builtin" = "nord7" + +# Variables +"variable" = "nord4" +"variable.builtin" = "nord9" +"variable.other.member" = "nord4" +"variable.parameter" = "nord8" +"attribute" = "nord9" + +# Misc. +"label" = "nord7" +"namespace" = "nord4" +"operator" = "nord9" +"special" = "nord9" +"tag" = "nord7" +"comment" = { fg = "nord3_bright", modifiers = ["italic"] } + +## EDITOR UI COLORS + +"ui.background" = { bg = "nord0" } +"ui.text" = "nord4" +"ui.window" = "nord1" + +# Debug +"ui.debug.active" = "nord13" +"ui.debug.breakpoint" = "nord11" + +# Popus and menus +"ui.menu" = { bg = "nord1" } +"ui.menu.scroll" = { fg = "nord4", bg = "nord3" } +"ui.menu.selected" = { fg = "nord8", bg = "nord2" } +"ui.popup" = { bg = "nord1" } +"ui.popup.info" = { bg = "nord1" } +"ui.help" = { bg = "nord1" } +"ui.text.focus" = { fg = "nord8", bg = "nord2" } + +# Gutter +"ui.gutter" = "nord5" +"ui.linenr" = "nord3" +"ui.linenr.selected" = "nord5" + +# Cursor +"ui.cursor" = { fg = "nord4", modifiers = ["reversed"] } +"ui.cursorcolumn.primary" = { bg = "nord1" } +"ui.cursorline.primary" = { bg = "nord1" } +"ui.cursor.match" = { bg = "nord3" } + +"ui.selection" = { bg = "nord3" } +"ui.highlight" = { fg = "nord8", bg = "nord2" } + +# Statusline +"ui.statusline" = { bg = "nord1" } +"ui.statusline.inactive" = { fg = "nord8", bg = "nord1" } +"ui.statusline.insert" = { fg = "nord1", bg = "nord6" } +"ui.statusline.normal" = { fg = "nord1", bg = "nord8" } +"ui.statusline.select" = { fg = "nord1", bg = "nord7" } +"ui.statusline.separator" = "nord3" + +# Virtual/invisible text +"ui.virtual.indent-guide" = "nord3" +"ui.virtual.inlay-hint" = { fg = "nord3", modifiers = ["italic"] } +"ui.virtual.jump-label" = { fg = "nord11", modifiers = ["bold"] } +"ui.virtual.ruler" = { bg = "nord1" } +"ui.virtual.whitespace" = "nord3" +"ui.virtual.wrap" = "nord3" + +# Bufferline +"ui.bufferline" = { fg = "nord5", bg = "nord1" } +"ui.bufferline.active" = { fg = "nord6", bg = "nord2", underline = { color = "nord8", style = "line" }, modifiers = [ + "italic", +] } + +# Markup +"markup.heading" = "nord8" +"markup.list" = "nord9" +"markup.bold" = { modifiers = ["bold"] } +"markup.italic" = { modifiers = ["italic"] } +"markup.strikethrough" = { modifiers = ["crossed_out"] } +"markup.link.text" = "nord8" +"markup.raw" = "nord7" + +# Rainbow brackets +rainbow = ["nord13", "nord15", "nord14", "nord12"] + +[palette] +# Polar Night is made up of four darker colors that are commonly used for base elements like backgrounds or text color in bright ambiance designs. +# +# The origin color or the Polar Night palette +nord0 = "#2e3440" +# A brighter shade color based on nord0 +nord1 = "#3B4252" +# An even more brighter shade color of nord0 +nord2 = "#434C5E" +# The brightest shade color based on nord0 +nord3 = "#4C566A" +# 10% brighter for comments, see https://github.com/nordtheme/nord/issues/94 +nord3_bright = "#616e88" + +# Snow Storm is made up of three bright colors that are commonly used for text colors or base UI elements in bright ambiance designs. +# The origin color or the Snow Storm palette +nord4 = "#D8DEE9" +# A brighter shade color of nord4 +nord5 = "#E5E9F0" +# The brightest shade color based on nord4 +nord6 = "#ECEFF4" + +# Frost can be described as the heart palette of Nord, a group of four bluish colors that are commonly used for primary UI component and text highlighting and essential code syntax elements. +# +# A calm and highly contrasted color reminiscent of frozen polar water +nord7 = "#8FBCBB" +# The bright and shiny primary accent color reminiscent of pure and clear ice +nord8 = "#88C0D0" +# A more darkened and less saturated color reminiscent of arctic waters +nord9 = "#81A1C1" +# A dark and intensive color reminiscent of the deep arctic ocean +nord10 = "#5E81AC" + +# Aurora consists of five colorful components reminiscent of the "Aurora borealis", sometimes referred to as polar lights or northern lights. +# +# Red +nord11 = "#BF616A" +# Orange +nord12 = "#D08770" +# Yellow +nord13 = "#EBCB8B" +# Green +nord14 = "#A3BE8C" +# Purple +nord15 = "#B48EAD" diff --git a/vendor/themes/rose_pine.toml b/vendor/themes/rose_pine.toml deleted file mode 100644 index 33c71486..00000000 --- a/vendor/themes/rose_pine.toml +++ /dev/null @@ -1,197 +0,0 @@ -# Author: Rosé Pine -# Upstream: https://github.com/rose-pine/helix -# Contributing: -# Please submit changes to https://github.com/rose-pine/helix. -# The Rosé Pine team will update Helix, including you as a co-author. - -"ui.background" = { bg = "base" } -"ui.background.separator" = { bg = "base" } - -"ui.cursor" = { fg = "text", bg = "highlight_high" } -# "ui.cursor.select" = {} -"ui.cursor.match" = { fg = "text", bg = "highlight_med" } -"ui.cursor.primary" = { fg = "text", bg = "muted" } - -# "ui.gutter" = {} -# "ui.gutter.selected" = {} - -"ui.linenr" = { fg = "muted" } -"ui.linenr.selected" = { fg = "text" } - -"ui.bufferline" = { fg = "muted", bg = "base" } -"ui.bufferline.active" = { fg = "text", bg = "overlay" } -"ui.statusline" = { fg = "subtle", bg = "surface" } -"ui.statusline.inactive" = { fg = "muted", bg = "surface" } -"ui.statusline.normal" = { fg = "rose", bg = "rose_10" } -"ui.statusline.insert" = { fg = "foam", bg = "foam_10" } -"ui.statusline.select" = { fg = "iris", bg = "iris_10" } -# "ui.statusline.separator" = {} - -"ui.popup" = { bg = "surface" } -"ui.popup.info" = { bg = "surface" } - -"ui.window" = { fg = "overlay", bg = "base" } -"ui.help" = { fg = "subtle", bg = "overlay" } - -"ui.text" = { fg = "text" } -"ui.text.focus" = { bg = "overlay" } -"ui.text.info" = { fg = "subtle" } -"ui.text.directory" = { fg = "iris" } - -"ui.virtual.jump-label" = { fg = "love", modifiers = ["bold"] } -"ui.virtual.ruler" = { bg = "overlay" } -"ui.virtual.whitespace" = { fg = "highlight_high" } -"ui.virtual.indent-guide" = { fg = "muted" } -"ui.virtual.inlay-hint" = { fg = "subtle" } - -"ui.menu" = { fg = "subtle", bg = "surface" } -"ui.menu.selected" = { fg = "text", bg = "overlay" } -"ui.menu.scroll" = { fg = "muted", bg = "highlight_med" } - -"ui.selection" = { bg = "overlay" } -"ui.selection.primary" = { bg = "highlight_med" } - -"ui.cursorline.primary" = { bg = "highlight_low" } -"ui.cursorline.secondary" = { bg = "surface" } - -"warning" = "gold" -"error" = "love" -"info" = "foam" -"hint" = "iris" -"debug" = "rose" - -"diagnostic" = { underline = { color = "subtle", style = "curl" } } -"diagnostic.hint" = { underline = { color = "iris", style = "curl" } } -"diagnostic.info" = { underline = { color = "foam", style = "curl" } } -"diagnostic.warning" = { underline = { color = "gold", style = "curl" } } -"diagnostic.error" = { underline = { color = "love", style = "curl" } } -"diagnostic.unnecessary" = { modifiers = ["dim"] } -"diagnostic.deprecated" = { modifiers = ["crossed_out"] } -"special" = "rose" - -"attribute" = "iris" - -"type" = "foam" -# "type.builtin" = "" - -"constructor" = "foam" - -"constant" = "foam" -"constant.builtin" = "love" -"constant.builtin.boolean" = "rose" -"constant.character" = "gold" -"constant.character.escape" = "pine" -"constant.numeric" = "gold" -# "constant.numeric.integer" = "" -# "constant.numeric.float" = "" - -"string" = "gold" -# "string.regexp" = "" -# "string.special" = "" -# "string.special.path" = "" -# "string.special.url" = "" -# "string.special.symbol" = "" - -"comment" = { fg = "muted", modifiers = ["italic"] } -# "comment.line" = "" -# "comment.line.documentation" = "" -# "comment.block" = "" -# "comment.block.documentation" = "" - -"variable" = "text" -"variable.builtin" = "love" -"variable.parameter" = "iris" -# "variable.other" = "" -"variable.other.member" = "foam" - -"label" = "foam" - -"punctuation" = "subtle" -# "punctuation.delimiter" = "" -# "punctuation.bracket" = "" -# "punctuation.special" = "" - -"keyword" = "pine" -# "keyword.control" = "" -# "keyword.control.conditional" = "" -# "keyword.control.repeat" = "" -# "keyword.control.import" = "" -# "keyword.control.return" = "" -# "keyword.control.exception" = "" -"keyword.operator" = "subtle" -# "keyword.directive" = "" -# "keyword.function" = "" -# "keyword.storage" = "" -# "keyword.storage.type" = "" -# "keyword.storage.modifier" = "" - -"operator" = "subtle" - -"function" = "rose" # maybe pine -"function.builtin" = "love" -# "function.method" = "" -# "function.macro" = "" -# "function.special" = "" - -"tag" = "foam" - -"namespace" = "text" - -"markup.heading.marker" = "muted" -"markup.heading" = { fg = "iris", modifiers = ["bold"] } -"markup.heading.1" = { fg = "iris", modifiers = ["bold"] } -"markup.heading.2" = { fg = "foam", modifiers = ["bold"] } -"markup.heading.3" = { fg = "rose", modifiers = ["bold"] } -"markup.heading.4" = { fg = "gold", modifiers = ["bold"] } -"markup.heading.5" = { fg = "pine", modifiers = ["bold"] } -"markup.heading.6" = { fg = "foam", modifiers = ["bold"] } -# "markup.heading.completion" = "" -# "markup.heading.hover" = "" -"markup.list" = "muted" -# "markup.list.unnumbered" = "" -# "markup.list.numbered" = "" -"markup.bold" = { modifiers = ["bold"] } -"markup.italic" = { modifiers = ["italic"] } -"markup.strikethrough" = { modifiers = ["crossed_out"] } -"markup.link" = "iris" -"markup.link.url" = { fg = "iris", underline = { color = "iris", style = "line" } } -"markup.link.label" = "subtle" -"markup.link.text" = "text" -"markup.quote" = "subtle" -"markup.raw" = "subtle" -# "markup.raw.inline" = {} -# "markup.raw.inline.completion" = {} -# "markup.raw.inline.hover" = {} -# "markup.raw.block" = {} -# "markup.normal" = "" -# "markup.normal.completion" = "" -# "markup.normal.hover" = "" - -"diff" = "overlay" -"diff.plus" = "foam" -"diff.minus" = "love" -"diff.delta" = "highlight_high" -# "diff.delta.moved" = "" - -[palette] -base = "#191724" -surface = "#1f1d2e" -overlay = "#26233a" -muted = "#6e6a86" -subtle = "#908caa" -text = "#e0def4" -love = "#eb6f92" -love_10 = "#311f30" -gold = "#f6c177" -gold_10 = "#30282c" -rose = "#ebbcba" -rose_10 = "#2f2834" -pine = "#31748f" -pine_10 = "#1a2030" -foam = "#9ccfd8" -foam_10 = "#252937" -iris = "#c4a7e7" -iris_10 = "#2b2539" -highlight_low = "#21202e" -highlight_med = "#403d52" -highlight_high = "#524f67" diff --git a/vendor/themes/rose_pine_dawn.toml b/vendor/themes/rose_pine_dawn.toml deleted file mode 100644 index d3949e1a..00000000 --- a/vendor/themes/rose_pine_dawn.toml +++ /dev/null @@ -1,30 +0,0 @@ -# Author: Rosé Pine -# Upstream: https://github.com/rose-pine/helix -# Contributing: -# Please submit changes to https://github.com/rose-pine/helix. -# The Rosé Pine team will update Helix, including you as a co-author. - -inherits = "rose_pine" - -[palette] -base = "#faf4ed" -surface = "#fffaf3" -overlay = "#f2e9e1" -muted = "#9893a5" -subtle = "#797593" -text = "#575279" -love = "#b4637a" -love_10 = "#f6e4e0" -gold = "#ea9d34" -gold_10 = "#fbead8" -rose = "#d7827e" -rose_10 = "#fae8e1" -pine = "#286983" -pine_10 = "#e5e6e2" -foam = "#56949f" -foam_10 = "#eaeae5" -iris = "#907aa9" -iris_10 = "#f1e8e6" -highlight_low = "#f4ede8" -highlight_med = "#dfdad9" -highlight_high = "#cecacd" diff --git a/vendor/themes/rose_pine_moon.toml b/vendor/themes/rose_pine_moon.toml deleted file mode 100644 index f1d04dd3..00000000 --- a/vendor/themes/rose_pine_moon.toml +++ /dev/null @@ -1,30 +0,0 @@ -# Author: Rosé Pine -# Upstream: https://github.com/rose-pine/helix -# Contributing: -# Please submit changes to https://github.com/rose-pine/helix. -# The Rosé Pine team will update Helix, including you as a co-author. - -inherits = "rose_pine" - -[palette] -base = "#232136" -surface = "#2a273f" -overlay = "#393552" -muted = "#6e6a86" -subtle = "#908caa" -text = "#e0def4" -love = "#eb6f92" -love_10 = "#3a2841" -gold = "#f6c177" -gold_10 = "#39313e" -rose = "#ea9a97" -rose_10 = "#392d41" -pine = "#3e8fb0" -pine_10 = "#252c44" -foam = "#9ccfd8" -foam_10 = "#2e3248" -iris = "#c4a7e7" -iris_10 = "#342e4a" -highlight_low = "#2a283e" -highlight_med = "#44415a" -highlight_high = "#56526e" diff --git a/vendor/themes/solarized_dark.toml b/vendor/themes/solarized_dark.toml deleted file mode 100644 index c4f6815a..00000000 --- a/vendor/themes/solarized_dark.toml +++ /dev/null @@ -1,135 +0,0 @@ -"attribute" = { fg = "violet" } -"keyword" = { fg = "green" } -"keyword.directive" = { fg = "orange" } -"namespace" = { fg = "violet" } -"operator" = { fg = "green" } -"special" = { fg = "orange" } -"variable.builtin" = { fg = "cyan", modifiers = ["bold"] } -"variable.function" = { fg = "blue" } -"type" = { fg = "yellow" } -"type.builtin" = { fg = "yellow", modifiers = ["bold"] } -"constructor" = { fg = "blue" } -"function" = { fg = "blue" } -"function.macro" = { fg = "magenta" } -"function.builtin" = { fg = "blue", modifiers = ["bold"] } -"function.special" = { fg = "magenta" } -"comment" = { fg = "base01" } -"string" = { fg = "cyan" } -"constant" = { fg = "cyan" } -"constant.builtin" = { fg = "cyan", modifiers = ["bold"] } -"constant.character.escape" = { fg = "red", modifiers = ["bold"] } -"label" = { fg = "green" } -"module" = { fg = "violet" } -"tag" = { fg = "magenta" } - -# TODO -"markup.heading" = "blue" -"markup.list" = "red" -"markup.bold" = { fg = "yellow", modifiers = ["bold"] } -"markup.italic" = { fg = "magenta", modifiers = ["italic"] } -"markup.strikethrough" = { modifiers = ["crossed_out"] } -"markup.link.url" = { fg = "yellow", modifiers = ["underlined"] } -"markup.link.text" = "red" -"markup.quote" = "cyan" -"markup.raw" = "green" - -"diff.plus" = { fg = "green" } -"diff.delta" = { fg = "yellow" } -"diff.minus" = { fg = "red" } - -# 背景 -"ui.background" = { bg = "base03" } - -"ui.virtual.whitespace" = { fg = "base01" } -"ui.virtual.inlay-hint" = { fg = "base01", modifiers = ["italic"] } -"ui.virtual.jump-label" = { fg = "red", modifiers = ["bold"] } - -# 行号栏 -"ui.linenr" = { fg = "base0", bg = "base02" } -# 当前行号栏 -"ui.linenr.selected" = { fg = "blue", modifiers = ["bold"] } -#cursorline -"ui.cursorline" = { bg = "base03" } - -# 状态栏 -"ui.statusline" = { fg = "base03", bg = "base0" } -"ui.statusline.normal" = { bg = "blue" } -"ui.statusline.insert" = { bg = "green" } -"ui.statusline.select" = { bg = "yellow" } - -# 非活动状态栏 -"ui.statusline.inactive" = { fg = "base1", bg = "base01" } - -# 补全窗口, preview窗口 -"ui.popup" = { bg = "base02" } -# 影响 补全选中 cmd弹出信息选中 -"ui.menu.selected" = { fg = "base02", bg = "base2"} -"ui.menu" = { fg = "base0", bg = "base02" } -# ?? -"ui.window" = { fg = "base3" } -# 命令行 补全的帮助信息 -"ui.help" = { modifiers = ["reversed"] } - -# 快捷键窗口 -"ui.popup.info" = {fg = "base02", bg = "base1", modifiers = ["bold"]} -# 快捷键字体 -"ui.text.info" = {fg = "base02", modifiers = ["bold"]} - -# 普通ui的字体样式 -"ui.text" = { fg = "base1" } -# 影响 picker列表选中, 快捷键帮助窗口文本 -"ui.text.focus" = { fg = "blue", modifiers = ["bold"]} - -# 主光标/selectio -"ui.cursor.primary" = { fg = "base03", bg = "base1" } -"ui.cursor.select" = { fg = "base02", bg = "cyan" } -"ui.cursorline.primary" = { bg = "base02" } -"ui.cursorline.secondary" = { bg = "base025" } - -"ui.selection" = { bg = "base0175" } -"ui.selection.primary" = { bg = "base015" } - -"ui.virtual.indent-guide" = { fg = "base02" } -"ui.virtual.ruler" = { bg = "base02" } - -# normal模式的光标 -"ui.cursor" = {fg = "base02", bg = "cyan"} -"ui.cursor.insert" = {fg = "base03", bg = "base3"} -# 当前光标匹配的标点符号 -"ui.cursor.match" = { fg = "base03", bg = "base00" } - -"warning" = { fg = "orange", modifiers= ["bold", "underlined"] } -"error" = { fg = "red", modifiers= ["bold", "underlined"] } -"info" = { fg = "blue", modifiers= ["bold", "underlined"] } -"hint" = { fg = "base01", modifiers= ["bold", "underlined"] } - -"diagnostic.warning" = { underline = { style = "curl", color = "orange" } } -"diagnostic.error" = { underline = { style = "curl", color = "red" } } -"diagnostic.info" = { underline = { style = "curl", color = "blue" } } -"diagnostic.hint" = { underline = { style = "curl", color = "base01" } } -"diagnostic.unnecessary" = { modifiers = ["dim"] } -"diagnostic.deprecated" = { modifiers = ["crossed_out"] } - -[palette] -# 深色 越来越深 -base03 = "#002b36" -base025 = "#03303b" -base02 = "#073642" -base0175 = "#16404b" -base015 = "#2c4f59" -base01 = "#586e75" -base00 = "#657b83" -base0 = "#839496" -base1 = "#93a1a1" -base2 = "#eee8d5" -base3 = "#fdf6e3" - -# 浅色 越來越浅 -yellow = "#b58900" -orange = "#cb4b16" -red = "#dc322f" -magenta = "#d33682" -violet = "#6c71c4" -blue = "#268bd2" -cyan = "#2aa198" -green = "#859900" diff --git a/vendor/themes/solarized_light.toml b/vendor/themes/solarized_light.toml deleted file mode 100644 index 2db54ca1..00000000 --- a/vendor/themes/solarized_light.toml +++ /dev/null @@ -1,155 +0,0 @@ -"attribute" = { fg = "violet" } -"keyword" = { fg = "green" } -"keyword.directive" = { fg = "orange" } -"namespace" = { fg = "violet" } -"operator" = { fg = "green" } -"special" = { fg = "orange" } -"variable.builtin" = { fg = "cyan", modifiers = ["bold"] } -"variable.function" = { fg = "blue" } -"type" = { fg = "yellow" } -"type.builtin" = { fg = "yellow", modifiers = ["bold"] } -"constructor" = { fg = "blue" } -"function" = { fg = "blue" } -"function.macro" = { fg = "magenta" } -"function.builtin" = { fg = "blue", modifiers = ["bold"] } -"function.special" = { fg = "magenta" } -"comment" = { fg = "base01" } -"string" = { fg = "cyan" } -"constant" = { fg = "cyan" } -"constant.builtin" = { fg = "cyan", modifiers = ["bold"] } -"constant.character.escape" = { fg = "red", modifiers = ["bold"] } -"label" = { fg = "green" } -"module" = { fg = "violet" } -"tag" = { fg = "magenta" } - -# TODO -"markup.heading" = "blue" -"markup.list" = "red" -"markup.bold" = { fg = "yellow", modifiers = ["bold"] } -"markup.italic" = { fg = "magenta", modifiers = ["italic"] } -"markup.strikethrough" = { modifiers = ["crossed_out"] } -"markup.link.url" = { fg = "yellow", modifiers = ["underlined"] } -"markup.link.text" = "red" -"markup.quote" = "cyan" -"markup.raw" = "green" - -"diff.plus" = { fg = "green" } -"diff.delta" = { fg = "yellow" } -"diff.minus" = { fg = "red" } - -# 背景 -# background -"ui.background" = { bg = "base03" } - -"ui.virtual.whitespace" = { fg = "base01" } -"ui.virtual.inlay-hint" = { fg = "base01", modifiers = ["italic"] } -"ui.virtual.jump-label" = { fg = "red", modifiers = ["bold"] } - -# 行号栏 -# line number column -"ui.linenr" = { fg = "base0", bg = "base02" } -# 当前行号栏 -# current line number column -"ui.linenr.selected" = { fg = "blue", modifiers = ["bold"] } -# cursorline -"ui.cursorline" = { bg = "base0" } - -# 状态栏 -# status bar -"ui.statusline" = { fg = "base03", bg = "base0" } -"ui.statusline.normal" = { bg = "blue" } -"ui.statusline.insert" = { bg = "green" } -"ui.statusline.select" = { bg = "yellow" } - -# 非活动状态栏 -# inactive status bar -"ui.statusline.inactive" = { fg = "base1", bg = "base01" } - -# 补全窗口, preview窗口 -# Completion window, preview window -"ui.popup" = { bg = "base02" } -# 影响 补全选中 cmd弹出信息选中 -# Affect completion selection, cmd pop-up information selection -"ui.menu.selected" = { fg = "base02", bg = "base2"} -"ui.menu" = { fg = "base0", bg = "base02" } -# ?? -"ui.window" = { fg = "base3" } -# 命令行 补全的帮助信息 -# Command line completion help information -"ui.help" = { modifiers = ["reversed"] } - -# 快捷键窗口 -# Shortcut window -"ui.popup.info" = { bg = "base1" } -# 快捷键字体 -# Shortcut font -"ui.text.info" = {fg = "base02", modifiers = ["bold"]} - -# 普通ui的字体样式 -# Normal ui font style -"ui.text" = { fg = "base1" } -# 影响 picker列表选中, 快捷键帮助窗口文本 -# Affects picker list selection, shortcut key help window text -"ui.text.focus" = { fg = "blue", modifiers = ["bold"]} - -# 主光标/selection -# main cursor/selection -"ui.cursor.primary" = { fg = "base03", bg = "base1" } -"ui.cursor.select" = { fg = "base02", bg = "cyan" } - -"ui.cursorline.primary" = { bg = "base02" } -"ui.cursorline.secondary" = { bg = "base025" } - -"ui.selection" = { bg = "base0175" } -"ui.selection.primary" = { bg = "base015" } - -"ui.virtual.indent-guide" = { fg = "base02" } -"ui.virtual.ruler" = { bg = "base02" } - -# normal模式的光标 -# normal mode cursor -"ui.cursor" = {fg = "base02", bg = "cyan"} -"ui.cursor.insert" = {fg = "base03", bg = "base3"} -# 当前光标匹配的标点符号 -# The punctuation character matched by the current cursor -"ui.cursor.match" = { fg = "base02", bg = "base015" } - -"warning" = { fg = "orange", modifiers= ["bold", "underlined"] } -"error" = { fg = "red", modifiers= ["bold", "underlined"] } -"info" = { fg = "blue", modifiers= ["bold", "underlined"] } -"hint" = { fg = "base01", modifiers= ["bold", "underlined"] } - -"diagnostic.warning" = { underline = { style = "curl", color = "orange" } } -"diagnostic.error" = { underline = { style = "curl", color = "red" } } -"diagnostic.info" = { underline = { style = "curl", color = "blue" } } -"diagnostic.hint" = { underline = { style = "curl", color = "base01" } } -"diagnostic.unnecessary" = { modifiers = ["dim"] } -"diagnostic.deprecated" = { modifiers = ["crossed_out"] } - - -[palette] -red = '#dc322f' -green = '#859900' -yellow = '#b58900' -blue = '#268bd2' -magenta = '#d33682' -cyan = '#2aa198' -orange = '#cb4b16' -violet = '#6c71c4' - -# 深色 越来越深 -# dark getting darker -base0 = '#657b83' -base1 = '#586e75' -base2 = '#073642' -base3 = '#002b36' - -# 浅色 越來越浅 -# Lighter and lighter -base00 = '#839496' -base01 = '#93a1a1' -base015 = '#c5c8bd' -base0175 = '#dddbcc' -base02 = '#eee8d5' -base025 = '#f5eedb' -base03 = '#fdf6e3' diff --git a/vendor/themes/tokyonight_day.toml b/vendor/themes/tokyonight_day.toml deleted file mode 100644 index 18c3b45f..00000000 --- a/vendor/themes/tokyonight_day.toml +++ /dev/null @@ -1,41 +0,0 @@ -# Author: Paul Graydon - -inherits = "tokyonight" - -[palette] -red = "#f52a65" -orange = "#b15c00" -yellow = "#8c6c3e" -light-green = "#587539" -green = "#387068" -aqua = "#188092" -teal = "#118c74" -turquoise = "#006a83" -light-cyan = "#2e5857" -cyan = "#007197" -blue = "#2e7de9" -purple = "#7847bd" -magenta = "#9854f1" -comment = "#848cb5" -black = "#a1a6c5" - -add = "#aecde6" -change = "#d6d8e3" -delete = "#dfccd4" - -error = "#c64343" -hint = "#118c74" -info = "#07879d" - -fg = "#3760bf" -fg-dark = "#6172b0" -fg-gutter = "#a8aecb" -fg-linenr = "#68709a" -fg-selected = "#b3b8d1" -border = "#e9e9ed" -border-highlight = "#2496ac" -bg = "#e1e2e7" -bg-inlay = "#acd7eb" -bg-selection = "#c4c8da" -bg-menu = "#e9e9ec" -bg-focus = "#b6bfe2" diff --git a/vendor/themes/tokyonight_moon.toml b/vendor/themes/tokyonight_moon.toml deleted file mode 100644 index 09b38db3..00000000 --- a/vendor/themes/tokyonight_moon.toml +++ /dev/null @@ -1,41 +0,0 @@ -# Author: Paul Graydon - -inherits = "tokyonight" - -[palette] -red = "#ff757f" -orange = "#ff966c" -yellow = "#ffc777" -light-green = "#c3e88d" -green = "#4fd6be" -aqua = "#65bcff" -teal = "#4fd6be" -turquoise = "#89ddff" -light-cyan = "#b4f9f8" -cyan = "#86e1fc" -blue = "#82aaff" -purple = "#fca7ea" -magenta = "#c099ff" -comment = "#636da6" -black = "#444a73" - -add = "#b8db87" -change = "#7ca1f2" -delete = "#e26a75" - -error = "#c53b53" -hint = "#4fd6be" -info = "#0db9d7" - -fg = "#c8d3f5" -fg-dark = "#828bb8" -fg-gutter = "#3b4261" -fg-linenr = "#737aa2" -fg-selected = "#363c58" -border = "#1b1d2b" -border-highlight = "#589ed7" -bg = "#222436" -bg-inlay = "#273644" -bg-selection = "#2f334d" -bg-menu = "#1e2030" -bg-focus = "#2d3f76" diff --git a/vendor/themes/tokyonight_storm.toml b/vendor/themes/tokyonight_storm.toml deleted file mode 100644 index 7bdddd8b..00000000 --- a/vendor/themes/tokyonight_storm.toml +++ /dev/null @@ -1,12 +0,0 @@ -# Author: Paul Graydon - -inherits = "tokyonight" - -[palette] -border = "#1d202f" -bg = "#24283b" -bg-inlay = "#233745" -bg-selection = "#373d5a" -bg-menu = "#1f2335" -bg-focus = "#2e3c64" -border-highlight = "#29a4bd" -- cgit v1.3 From 80314064f6e81c8828340e010202b446f0e1f36d Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Fri, 23 Oct 2026 11:00:44 -0300 Subject: Audit (misc): std mkdir -p and JSON escaping, a 9P late failure's errno from ctl.failureErrno, dead switches and dumpHex out Co-Authored-By: Claude Opus 5.5 --- src/9p_io.zig | 112 +++++++++++++++++++++----------------------------- src/File.zig | 5 +-- src/Output.zig | 52 ++++++----------------- src/builtins.zig | 86 ++++++++++++-------------------------- src/builtins_json.zig | 22 +++------- src/config.zig | 75 ++++++--------------------------- src/dump.zig | 11 +---- src/esp32p4/uart.zig | 16 -------- src/fs.zig | 12 +----- src/gui/gui.zig | 13 ++---- src/hunks.zig | 6 +-- src/locations.zig | 25 +++++------ src/look.zig | 8 ++-- src/main.zig | 40 +++++++----------- src/syntax.zig | 5 +-- src/tagline.zig | 7 +--- src/terminal.zig | 4 +- src/web.zig | 59 +++++--------------------- 18 files changed, 156 insertions(+), 402 deletions(-) (limited to 'src/File.zig') diff --git a/src/9p_io.zig b/src/9p_io.zig index a825475f..a089a7cf 100644 --- a/src/9p_io.zig +++ b/src/9p_io.zig @@ -11,10 +11,7 @@ const quic = if (quic_enabled) @import("9p_quic.zig") else struct {}; const log = std.log.scoped(.ninep); -pub const darwin = switch (builtin.os.tag) { - .macos, .ios, .tvos, .watchos, .visionos => true, - else => false, -}; +pub const darwin = builtin.os.tag.isDarwin(); pub const supported = builtin.os.tag == .linux or darwin; pub const sun_path_len = @typeInfo(@FieldType(libc.sockaddr.un, "path")).array.len; @@ -47,15 +44,8 @@ pub fn statNoFollow(path: [:0]const u8) ?FileFacts { pub fn ensureSocketDir(dir: [:0]const u8) bool { if (dir.len == 0) return false; - var partial: [sun_path_len:0]u8 = undefined; - @memcpy(partial[0 .. dir.len + 1], dir[0 .. dir.len + 1]); - for (1..dir.len) |i| { - if (dir[i] != '/') continue; - partial[i] = 0; - _ = libc.mkdir(partial[0..i :0], 0o700); - partial[i] = '/'; - } - _ = libc.mkdir(dir, 0o700); + // A failure shows in the stat below. + _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o700)) catch {}; const stat = statNoFollow(dir) orelse return false; return stat.mode & 0o170000 == 0o040000 and stat.uid == libc.getuid() and stat.mode & 0o077 == 0; } @@ -394,11 +384,11 @@ pub const Listener = struct { // settle in the same wait is told to this write too. if (l.core == core and core.fs.late_failure_len != 0) { const late = core.fs.late_failure[0..core.fs.late_failure_len]; - // What is not there (`no such directory`) is ENOENT, as a - // builtin's failure saying so is (ctl.failureErrno). - const errno = if (std.mem.indexOf(u8, late, "no such") != null or std.mem.indexOf(u8, late, "not found") != null) - pardes.ctlfs.E.NOENT - else if (std.mem.indexOf(u8, late, "no space") != null) pardes.ctlfs.E.NOSPC else if (std.mem.indexOf(u8, late, "permission denied") != null) pardes.ctlfs.E.PERM else if (std.mem.indexOf(u8, late, "invalid") != null) pardes.ctlfs.E.INVAL else pardes.ctlfs.E.IO; + // The errno a builtin's failure in the same words has; what + // that leaves EIO and says `no space` (a full disk under a + // Save) is ENOSPC. + const said = @import("ninep/ctl.zig").failureErrno(late); + const errno = if (said == pardes.ctlfs.E.IO and std.mem.indexOf(u8, late, "no space") != null) pardes.ctlfs.E.NOSPC else said; const failed = pardes.ctlfs.failText(req.tag, errno, late); // Its err record says it (the path in it), the one record: it // was said with no msg while this waited (fs.write_waits). @@ -1017,21 +1007,11 @@ fn onFatalSignal(s: std.posix.SIG) callconv(.c) void { pub fn sweepDeadSockets(io: std.Io, dir: [:0]const u8) void { if (comptime !supported) return; var names: [8192]u8 = undefined; - var staged: usize = 0; - { - const d = std.Io.Dir.openDirAbsolute(io, dir, .{ .iterate = true }) catch return; - defer d.close(io); - var read_buf: [std.Io.Dir.Iterator.reader_buffer_len]u8 align(@alignOf(usize)) = undefined; - var reader: std.Io.Dir.Reader = .init(d, &read_buf); - while (true) { - const listed = (reader.next(io) catch break) orelse break; - if (deadSocketPid(listed.name) == null) continue; - if (staged + 1 + listed.name.len > names.len) break; - names[staged] = @intCast(listed.name.len); - @memcpy(names[staged + 1 ..][0..listed.name.len], listed.name); - staged += 1 + listed.name.len; + const staged = stageNames(io, dir, &names, struct { + fn keep(name: []const u8) bool { + return deadSocketPid(name) != null; } - } + }.keep); var i: usize = 0; while (i < staged) { const name = names[i + 1 ..][0..names[i]]; @@ -1048,6 +1028,28 @@ pub fn sweepDeadSockets(io: std.Io, dir: [:0]const u8) void { } } +/// The names in `dir` that `keep` takes (all with none), into `names` as a length byte and +/// the name each, until it is full; the bytes staged. They are staged +/// before anything is unlinked, so a sweep never asks a directory to keep +/// reading while it is being edited. +fn stageNames(io: std.Io, dir: [:0]const u8, names: []u8, comptime keep: ?fn ([]const u8) bool) usize { + const d = std.Io.Dir.openDirAbsolute(io, dir, .{ .iterate = true }) catch return 0; + defer d.close(io); + var read_buf: [std.Io.Dir.Iterator.reader_buffer_len]u8 align(@alignOf(usize)) = undefined; + var reader: std.Io.Dir.Reader = .init(d, &read_buf); + var staged: usize = 0; + while (true) { + const listed = (reader.next(io) catch break) orelse break; + if (listed.name.len == 0 or listed.name.len > 255) continue; + if (keep) |takes| if (!takes(listed.name)) continue; + if (staged + 1 + listed.name.len > names.len) break; + names[staged] = @intCast(listed.name.len); + @memcpy(names[staged + 1 ..][0..listed.name.len], listed.name); + staged += 1 + listed.name.len; + } + return staged; +} + /// The pid a `pardes-9p-.sock` name carries, or null for any other. fn deadSocketPid(name: []const u8) ?std.c.pid_t { if (!std.mem.startsWith(u8, name, prefix) or !std.mem.endsWith(u8, name, ".sock")) return null; @@ -1279,24 +1281,8 @@ fn ourSocket(target: []const u8, sockets: []const u8) bool { fn sweepRegistry(io: std.Io, svc: [:0]const u8, sockets: []const u8) void { if (comptime !supported) return; - // The names are staged before anything is unlinked, so the sweep - // never asks a directory to keep reading while it is being edited. var names: [4096]u8 = undefined; - var staged: usize = 0; - { - const dir = std.Io.Dir.openDirAbsolute(io, svc, .{ .iterate = true }) catch return; - defer dir.close(io); - var read_buf: [std.Io.Dir.Iterator.reader_buffer_len]u8 align(@alignOf(usize)) = undefined; - var reader: std.Io.Dir.Reader = .init(dir, &read_buf); - while (true) { - const listed = (reader.next(io) catch break) orelse break; - if (listed.name.len == 0 or listed.name.len > 255) continue; - if (staged + 1 + listed.name.len > names.len) break; - names[staged] = @intCast(listed.name.len); - @memcpy(names[staged + 1 ..][0..listed.name.len], listed.name); - staged += 1 + listed.name.len; - } - } + const staged = stageNames(io, svc, &names, null); var reaped: usize = 0; var i: usize = 0; @@ -2179,10 +2165,8 @@ pub const Client = struct { if (comptime !supported) return error.Unsupported; var names: [max_depth][]const u8 = undefined; const n = try elements(path, &names); - var sock_buf: [sun_path_len]u8 = undefined; - const sock = try resolve(&sock_buf, dial); var remote: RemoteError = .{}; - return fetchBytes(gpa, sock, names[0..n], &remote, null, display_path, @min(max_bytes, limits.max_file_bytes)) catch |err| { + return fetchBytes(gpa, dial, names[0..n], &remote, null, display_path, @min(max_bytes, limits.max_file_bytes)) catch |err| { if (err == error.Remote) said = remote; return err; }; @@ -2209,10 +2193,8 @@ pub const Client = struct { if (comptime !supported) return error.Unsupported; var names: [max_depth][]const u8 = undefined; const n = try elements(path, &names); - var sock_buf: [sun_path_len]u8 = undefined; - const sock = try resolve(&sock_buf, dial); var remote: RemoteError = .{}; - const result = fetchBytes(gpa, sock, names[0..n], &remote, bytes, path, limits.max_file_bytes) catch |err| { + const result = fetchBytes(gpa, dial, names[0..n], &remote, bytes, path, limits.max_file_bytes) catch |err| { if (err == error.Remote) said = remote; return err; }; @@ -2470,7 +2452,7 @@ pub const Client = struct { fn fetchBytes( gpa: std.mem.Allocator, - sock: Dial, + dial: []const u8, names: []const []const u8, remote: *RemoteError, write_bytes: ?[]const u8, @@ -2478,7 +2460,7 @@ pub const Client = struct { read_limit: usize, ) ![]u8 { if (comptime !supported) return Error.Dial; - const s = try startSession(gpa, sock, display_path); + const s = try startSession(gpa, dial, display_path); defer endSession(gpa, s); var out: std.Io.Writer.Allocating = .init(gpa); errdefer out.deinit(); @@ -2486,8 +2468,10 @@ pub const Client = struct { return out.toOwnedSlice(); } - /// A connected session whose requests have the usual deadline. - fn startSession(gpa: std.mem.Allocator, sock: Dial, display_path: []const u8) !*Session { + /// A connected session at `dial` whose requests have the usual deadline. + fn startSession(gpa: std.mem.Allocator, dial: []const u8, display_path: []const u8) !*Session { + var sock_buf: [sun_path_len]u8 = undefined; + const sock = try resolve(&sock_buf, dial); const deadline = nowMs() +| budget_ms; const s = try gpa.create(Session); s.* = .{ .fd = -1, .deadline = deadline, .display_path = display_path }; @@ -2518,11 +2502,9 @@ pub const Client = struct { if (comptime !supported) return error.Unsupported; var names: [max_depth][]const u8 = undefined; const n = try elements(path, &names); - var sock_buf: [sun_path_len]u8 = undefined; - const sock = try resolve(&sock_buf, dial); var remote: RemoteError = .{}; errdefer said = remote; - const s = try startSession(gpa, sock, path); + const s = try startSession(gpa, dial, path); defer endSession(gpa, s); const fid = (try walkTo(s, names[0..n], &remote)).fid; _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); @@ -2562,10 +2544,8 @@ pub const Client = struct { if (comptime !supported) return error.Unsupported; var names: [max_depth][]const u8 = undefined; const n = try elements(path, &names); - var sock_buf: [sun_path_len]u8 = undefined; - const sock = try resolve(&sock_buf, dial); var remote: RemoteError = .{}; - const s = try startSession(gpa, sock, path); + const s = try startSession(gpa, dial, path); defer endSession(gpa, s); const fid = (try walkTo(s, names[0..n], &remote)).fid; _ = try s.ask(.{ .open = .{ .fid = fid, .mode = ninep.ordwr } }, &remote); @@ -2642,7 +2622,7 @@ pub const Client = struct { const before = nowMs(); try testing.expectError( Error.Dial, - fetchBytes(testing.allocator, .{ .unix = "/tmp/pardes-9p-no-such-socket.sock" }, names[0..n], &remote, null, "/pane/1/body", limits.max_file_bytes), + fetchBytes(testing.allocator, "/tmp/pardes-9p-no-such-socket.sock", names[0..n], &remote, null, "/pane/1/body", limits.max_file_bytes), ); try testing.expect(nowMs() - before < budget_ms); } diff --git a/src/File.zig b/src/File.zig index e92efaba..b1a4271f 100644 --- a/src/File.zig +++ b/src/File.zig @@ -2153,15 +2153,14 @@ pub const DiffOutput = struct { text[at] = '\n'; at += 1; } + // An empty slot, else the least recently used. var oldest: usize = 0; for (&o.slots, 0..) |*slot, i| { const e = slot.* orelse { oldest = i; break; }; - if (o.slots[oldest]) |old| if (e.used < old.used) { - oldest = i; - }; + if (e.used < o.slots[oldest].?.used) oldest = i; } if (o.slots[oldest]) |old| { p.gpa.free(old.text); diff --git a/src/Output.zig b/src/Output.zig index 3fc08d9a..9a11b2fc 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -949,51 +949,23 @@ fn helpContent(gpa: std.mem.Allocator, prefix: []const u8) ![]u8 { "C-left-click definition, by mouse\n" ++ "SPC l ... hover, rename, symbols,\n" ++ " calls, types: above\n"; - var len: usize = if (prefix.len == 0) - full_header.len + language_footer.len - else - group_header.len + prefix.len * 2 + 2; - if (show_calls_help) len += calls_help.len; + var out: std.Io.Writer.Allocating = .init(gpa); + errdefer out.deinit(); + const w = &out.writer; + if (prefix.len == 0) try w.writeAll(full_header) else { + try w.writeAll(group_header); + for (prefix) |c| try w.print(" {c}", .{c}); + try w.writeAll("\n\n"); + } for (pardes.builtin_rows) |row| { // a path-less builtin filters as the empty path: in the full listing // (which starts with nothing) and out of every group if (!std.mem.startsWith(u8, row.path orelse "", prefix)) continue; - len += row.line.len + 1; - } - const content = try gpa.alloc(u8, len); - var at: usize = 0; - if (prefix.len == 0) { - @memcpy(content[0..full_header.len], full_header); - at = full_header.len; - } else { - @memcpy(content[0..group_header.len], group_header); - at = group_header.len; - for (prefix) |c| { - content[at] = ' '; - content[at + 1] = c; - at += 2; - } - content[at] = '\n'; - content[at + 1] = '\n'; - at += 2; - } - for (pardes.builtin_rows) |row| { - if (!std.mem.startsWith(u8, row.path orelse "", prefix)) continue; - @memcpy(content[at..][0..row.line.len], row.line); - at += row.line.len; - content[at] = '\n'; - at += 1; - } - if (show_calls_help) { - @memcpy(content[at..][0..calls_help.len], calls_help); - at += calls_help.len; - } - if (prefix.len == 0) { - @memcpy(content[at..][0..language_footer.len], language_footer); - at += language_footer.len; + try w.print("{s}\n", .{row.line}); } - std.debug.assert(at == content.len); - return content; + if (show_calls_help) try w.writeAll(calls_help); + if (prefix.len == 0) try w.writeAll(language_footer); + return out.toOwnedSlice(); } pub fn openHelp(p: *Pardes, id: usize, prefix: []const u8) !void { diff --git a/src/builtins.zig b/src/builtins.zig index 7b1541ac..64710554 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -109,54 +109,27 @@ pub fn absentWhy(name: []const u8) ?[]const u8 { return null; } -fn manualBuiltinCount() comptime_int { +fn manualBuiltinList() []const type { comptime { - var count = 0; + @setEvalBranchQuota(4000); + var list: []const type = &.{}; for (@typeInfo(@This()).@"struct".decl_names) |d| { if (@TypeOf(@field(@This(), d)) != type) continue; const T = @field(@This(), d); if (@typeInfo(T) != .@"struct" or !@hasDecl(T, "run") or !isEnabled(T)) continue; if (@TypeOf(T.run) != fn (Ctx) void) @compileError(d ++ ".run must have signature fn (Ctx) void"); - count += 1; - } - return count; - } -} - -fn manualBuiltinList() [manualBuiltinCount()]type { - comptime { - @setEvalBranchQuota(4000); - var list: [manualBuiltinCount()]type = undefined; - var count = 0; - for (@typeInfo(@This()).@"struct".decl_names) |d| { - if (@TypeOf(@field(@This(), d)) != type) continue; - const T = @field(@This(), d); - if (@typeInfo(T) != .@"struct" or !@hasDecl(T, "run") or !isEnabled(T)) continue; - list[count] = T; - count += 1; + list = list ++ .{T}; } return list; } } -fn settingCount() comptime_int { +fn settingList() []const config.Runtime.Setting { comptime { - var count = 0; + var list: []const config.Runtime.Setting = &.{}; for (config.Runtime.settings) |setting| if (setting.enabled(capabilities)) { - count += 1; - }; - return count; - } -} - -fn settingList() [settingCount()]config.Runtime.Setting { - comptime { - var list: [settingCount()]config.Runtime.Setting = undefined; - var count = 0; - for (config.Runtime.settings) |setting| if (setting.enabled(capabilities)) { - list[count] = setting; - count += 1; + list = list ++ .{setting}; }; return list; } @@ -197,11 +170,17 @@ pub const registry = struct { return @Enum(Tag, .exhaustive, &names, &std.simd.iota(Tag, count)); } + /// What a hand-written builtin says as `name` (`pub const takes_arg = + /// true;`), `default` when it says nothing, and `setting` for a setting. + fn declOr(b: Builtin(), comptime name: []const u8, default: anytype, setting: @TypeOf(default)) @TypeOf(default) { + inline for (comptime manualBuiltinList(), 0..) |T, i| + if (@backingInt(b) == i) return if (@hasDecl(T, name)) @field(T, name) else default; + return setting; + } + pub fn takesArg(b: Builtin()) bool { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return @hasDecl(T, "takes_arg") and T.takes_arg; // Every setting takes its value, and a switch flips when bare. - return true; + return declOr(b, "takes_arg", false, true); } /// Whether the word takes its argument joined by a `+` as one word a @@ -209,9 +188,7 @@ pub const registry = struct { /// that says `pub const plus_arg = true;`: others have arguments a `+` /// may be in (`Dump+2024.zon` is a name, not Dump's argument). pub fn plusArg(b: Builtin()) bool { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return @hasDecl(T, "plus_arg") and T.plus_arg; - return false; + return declOr(b, "plus_arg", false, false); } /// Whether the word means nothing without its argument (`Mount`, @@ -222,15 +199,11 @@ pub const registry = struct { /// it says `pub const needs: PaneKind = .terminal;`, and on any other /// pane it is refused (exec.runBuiltinFrom), as Repl and Edit are. pub fn needs(b: Builtin()) ?PaneKind { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return if (@hasDecl(T, "needs")) T.needs else null; - return null; + return declOr(b, "needs", @as(?PaneKind, null), null); } pub fn requiresArg(b: Builtin()) bool { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return @hasDecl(T, "requires_arg") and T.requires_arg; - inline for (comptime settingList(), manualBuiltinCount()..) |setting, i| + inline for (comptime settingList(), comptime manualBuiltinList().len..) |setting, i| if (@backingInt(b) == i) return switch (setting.action) { // a switch flips bare, a choice steps, and DumpDir and Shell bare // are the default @@ -239,35 +212,28 @@ pub const registry = struct { // bare, it says the current value (exec.applySettingBuiltin) .tab, .callstack_depth => false, }; - unreachable; + return declOr(b, "requires_arg", false, false); } pub fn scope(b: Builtin()) Scope { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return if (@hasDecl(T, "scope")) T.scope else .pane; - return .session; // a setting + return declOr(b, "scope", Scope.pane, .session); } pub fn outputTraits(b: Builtin()) ?OutputTraits { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return if (@hasDecl(T, "output")) T.output else null; - inline for (comptime settingList(), manualBuiltinCount()..) |_, i| - if (@backingInt(b) == i) return null; - unreachable; + return declOr(b, "output", @as(?OutputTraits, null), null); } /// Does this builtin say its own name on the message row before it runs? /// The ones that own that row themselves declare `quiet` and do not. pub fn announces(b: Builtin()) bool { - inline for (manualBuiltinList(), 0..) |T, i| - if (@backingInt(b) == i) return !(@hasDecl(T, "quiet") and T.quiet); - return true; // a setting builtin changes something invisible; say so + // a setting builtin changes something invisible; say so + return !declOr(b, "quiet", false, false); } pub fn dispatch(b: Builtin(), c: Ctx) void { - inline for (manualBuiltinList(), 0..) |T, i| + inline for (comptime manualBuiltinList(), 0..) |T, i| if (@backingInt(b) == i) return T.run(c); - inline for (comptime settingList(), manualBuiltinCount()..) |setting, i| + inline for (comptime settingList(), comptime manualBuiltinList().len..) |setting, i| if (@backingInt(b) == i) return exec.applySettingBuiltin(c.p, setting, c.arg); unreachable; } diff --git a/src/builtins_json.zig b/src/builtins_json.zig index 7f998388..4440130d 100644 --- a/src/builtins_json.zig +++ b/src/builtins_json.zig @@ -11,17 +11,7 @@ const builtins = @import("builtins.zig"); const config = @import("config.zig"); const ctl = @import("ninep/ctl.zig"); -fn str(w: *std.Io.Writer, s: []const u8) !void { - try w.writeByte('"'); - for (s) |c| switch (c) { - '"' => try w.writeAll("\\\""), - '\\' => try w.writeAll("\\\\"), - '\n' => try w.writeAll("\\n"), - 0...9, 11...0x1f => try w.print("\\u{x:0>4}", .{c}), - else => try w.writeByte(c), - }; - try w.writeByte('"'); -} +const str = std.json.Stringify.encodeJsonString; const Entry = struct { name: []const u8, row: usize }; @@ -39,7 +29,7 @@ pub fn write(w: *std.Io.Writer) !void { const b = row.cmd; const name = @tagName(b); try w.writeAll(" {\"name\": "); - try str(w, name); + try str(name, .{}, w); try w.writeAll(", \"leader\": "); if (row.path) |p| { try w.writeAll("\"SPC"); @@ -55,21 +45,21 @@ pub fn write(w: *std.Io.Writer) !void { while (parts.next()) |part| if (part.len > 0) { if (!first) try w.writeAll(", "); first = false; - try str(w, part); + try str(part, .{}, w); }; try w.writeAll("], \"arg\": "); try w.writeAll(if (builtins.registry.takesArg(b)) "true" else "false"); try w.writeAll(", \"scope\": "); - try str(w, if (b == .Edit) "both" else if (builtins.registry.scope(b) == .session) "root" else "pane"); + try str(if (b == .Edit) "both" else if (builtins.registry.scope(b) == .session) "root" else "pane", .{}, w); const setting = config.Runtime.find(name); try w.writeAll(", \"setting\": "); try w.writeAll(if (setting != null) "true" else "false"); try w.writeAll(", \"choices\": "); - if (setting) |s| if (config.Runtime.choices(s.action)) |v| try str(w, v) else try w.writeAll("null") else try w.writeAll("null"); + if (setting) |s| if (config.Runtime.choices(s.action)) |v| try str(v, .{}, w) else try w.writeAll("null") else try w.writeAll("null"); var buf: [2048]u8 = undefined; const doc = if (setting) |s| s.doc else ctl.summaryOf(name, &buf); try w.writeAll(", \"doc\": "); - try str(w, doc); + try str(doc, .{}, w); try w.writeAll(if (n + 1 < order.len) "},\n" else "}\n"); } try w.writeAll("]\n"); diff --git a/src/config.zig b/src/config.zig index 5251b1e5..1fbf0d1b 100644 --- a/src/config.zig +++ b/src/config.zig @@ -293,9 +293,6 @@ pub const back_out: []const Chord = &.{.{ .cp = Key.escape, .shift = true }}; pub const tty_toggle_default: u21 = 'b'; -// OSC 133 prompt cells are hidden in normal mode; input columns stay intact. -pub const tty_blank: enum { prompt, prompt_and_input } = .prompt; - // Projected colors below this contrast use the theme's more legible anchor. pub const tty_filter_min_contrast: f64 = 1.5; @@ -386,9 +383,6 @@ pub const gui_topbar_pane_border_px: u8 = 1; // null follows the theme's scrollbar track. pub const gui_topbar_pane_border_rgb: ?[3]u8 = null; -// Transparency requires the SDL readback/blit path, even with an opaque theme. -pub const gui_transparent: bool = false; - // A vertical wheel tick suppresses this many subsequent horizontal ticks. pub const wheel_guard_ticks: u8 = 3; @@ -1428,12 +1422,12 @@ pub const Runtime = struct { /// effect but set by no word follows, after a blank line. pub fn writeReport(out: *std.Io.Writer, context: ReportContext) !void { const state = context.state; - for (settings) |setting| switch (setting.action) { + // TaglineSize is said wherever the shell sizes its tag, by its word + // or only at build time. + for (settings) |setting| if (!(if (setting.action == .tagline_size) context.capabilities.tagline_font_size else setting.enabled(context.capabilities))) + try out.print("# {s} unsupported\n", .{setting.word}) + else switch (setting.action) { .toggle => |field| { - if (!setting.enabled(context.capabilities)) { - try out.print("# {s} unsupported\n", .{setting.word}); - continue; - } const value = switch (field) { inline else => |f| @field(state, @tagName(f)), }; @@ -1443,18 +1437,8 @@ pub const Runtime = struct { try out.print("ThemeFile {s}\n", .{path}) else try out.print("{s} {s}\n", .{ setting.word, context.theme_name }), - .window_opacity => { - if (setting.enabled(context.capabilities)) - try out.print("{s} {d}\n", .{ setting.word, state.window_opacity }) - else - try out.print("# {s} unsupported\n", .{setting.word}); - }, - .window_blur => { - if (setting.enabled(context.capabilities)) - try out.print("{s} {d}\n", .{ setting.word, state.window_blur }) - else - try out.print("# {s} unsupported\n", .{setting.word}); - }, + .window_opacity => try out.print("{s} {d}\n", .{ setting.word, state.window_opacity }), + .window_blur => try out.print("{s} {d}\n", .{ setting.word, state.window_blur }), .dump_dir => { const dir = if (state.dump_dir.len > 0) state.dump_dir.get() else context.default_dump_dir; if (dir.len > 0) try out.print("{s} {s}\n", .{ setting.word, dir }) else try out.print("# {s} (none)\n", .{setting.word}); @@ -1466,9 +1450,7 @@ pub const Runtime = struct { const chosen = state.shell.requested.get(); try out.print("{s} {s}\n", .{ setting.word, if (chosen.len == 0) context.compiled_default_shell else chosen }); }, - .font => if (!setting.enabled(context.capabilities)) - try out.print("# {s} unsupported\n", .{setting.word}) - else { + .font => { // As `Font` takes it, `name:size`: the one asked for, else // the one in use. const f = &state.font; @@ -1483,28 +1465,14 @@ pub const Runtime = struct { if (f.requested_size_hundredths != 0) try out.print(":{d}.{d:0>2}", .{ f.requested_size_hundredths / 100, f.requested_size_hundredths % 100 }); try out.writeByte('\n'); }, - .tagline_size => if (!context.capabilities.tagline_font_size) - try out.print("# {s} unsupported\n", .{setting.word}) - else - try out.print("{s} {d}\n", .{ setting.word, state.font.tagline_percent }), + .tagline_size => try out.print("{s} {d}\n", .{ setting.word, state.font.tagline_percent }), // Each a switch of its own, the one in use on. - .transition => |transition| if (!setting.enabled(context.capabilities)) - try out.print("# {s} unsupported\n", .{setting.word}) - else - try out.print("{s} {s}\n", .{ setting.word, onOff(state.panel_transition == transition) }), + .transition => |transition| try out.print("{s} {s}\n", .{ setting.word, onOff(state.panel_transition == transition) }), .scene => |effect| { - if (!setting.enabled(context.capabilities)) { - try out.print("# {s} unsupported\n", .{setting.word}); - continue; - } const level = state.post.level(effect); if (level == 0) try out.print("{s} off\n", .{setting.word}) else try out.print("{s} {d}\n", .{ setting.word, level }); }, .shader => { - if (!setting.enabled(context.capabilities)) { - try out.print("# {s} unsupported\n", .{setting.word}); - continue; - } var files: usize = 0; for (state.post.list()) |entry| if (entry.scene == null) { try out.print("{s} {s}\n", .{ setting.word, entry.path.get() }); @@ -1512,25 +1480,16 @@ pub const Runtime = struct { }; if (files == 0) try out.print("{s} off\n", .{setting.word}); }, - .shader_animation => if (setting.enabled(context.capabilities)) - try out.print("{s} {s}\n", .{ setting.word, @tagName(state.shader_animation) }) - else - try out.print("# {s} unsupported\n", .{setting.word}), + .shader_animation => try out.print("{s} {s}\n", .{ setting.word, @tagName(state.shader_animation) }), .choice => |which| switch (which) { inline else => |field| try out.print("{s} {s}\n", .{ setting.word, @tagName(@field(state, @tagName(field))) }), }, - .lift => if (setting.enabled(context.capabilities)) - try out.print("{s} {s}\n", .{ setting.word, @tagName(state.lift) }) - else - try out.print("# {s} unsupported\n", .{setting.word}), + .lift => try out.print("{s} {s}\n", .{ setting.word, @tagName(state.lift) }), .motion => try out.print("{s} {s}\n", .{ setting.word, @tagName(state.motion) }), .inactive_dim => try out.print("{s} {d}\n", .{ setting.word, state.inactive_dim }), .callstack_depth => try out.print("{s} {d}\n", .{ setting.word, state.callstack_depth }), .tab => try out.print("{s} {d}\n", .{ setting.word, state.tab }), - .grip_width => if (setting.enabled(context.capabilities)) - try out.print("{s} {d}\n", .{ setting.word, state.grip_width }) - else - try out.print("# {s} unsupported\n", .{setting.word}), + .grip_width => try out.print("{s} {d}\n", .{ setting.word, state.grip_width }), }; if (context.locations.len > 0) try out.print("LocationsConfig {s}\n", .{context.locations}); @@ -1566,14 +1525,6 @@ pub const Runtime = struct { try out.print("# Pet: {s}\n", .{@tagName(state.pet)}); } - test "setting names are unique" { - for (settings, 0..) |setting, i| { - try std.testing.expect(setting.word.len > 0); - for (settings[i + 1 ..]) |later| - try std.testing.expect(!std.mem.eql(u8, setting.word, later.word)); - } - } - test "panel and scene effects flip bare and are set by on and off" { var state: Runtime = .{}; const slide = findAction(.{ .transition = .slide }).?; diff --git a/src/dump.zig b/src/dump.zig index 67934e0a..c8c302ab 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -38,16 +38,7 @@ pub fn outPath(buf: *[1024:0]u8, dir_setting: []const u8) ?[:0]const u8 { return std.fmt.bufPrintSentinel(buf, "{s}", .{std.mem.span(p)}, 0) catch null; var dir_buf: [900]u8 = undefined; const dir = directory(&dir_buf, dir_setting) orelse return null; - var dz: [901:0]u8 = undefined; - @memcpy(dz[0..dir.len], dir); - dz[dir.len] = 0; - // Each missing directory on the way, as `mkdir -p`: EEXIST is fine. - for (dz[1..dir.len], 1..) |c, i| if (c == '/') { - dz[i] = 0; - _ = std.c.mkdir(dz[0..i :0], 0o755); - dz[i] = '/'; - }; - _ = std.c.mkdir(dz[0..dir.len :0], 0o755); + _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o755)) catch {}; var ts: std.c.timespec = undefined; _ = std.c.clock_gettime(.REALTIME, &ts); const es: std.time.epoch.EpochSeconds = .{ .secs = @intCast(@max(0, ts.sec)) }; diff --git a/src/esp32p4/uart.zig b/src/esp32p4/uart.zig index 5690520c..a185737d 100644 --- a/src/esp32p4/uart.zig +++ b/src/esp32p4/uart.zig @@ -126,22 +126,6 @@ pub fn writeByte(b: u8) void { uart0.pushByte(b); } -/// Emit `n` bytes read from `addr` as two hex digits each, computing the digits arithmetically so -/// nothing here reads a lookup table. Used to answer "does a load from this address return what the -/// linker put there", which is not a question a string literal can be trusted to ask. -pub fn dumpHex(addr: u32, n: u32) void { - const p: [*]const volatile u8 = @ptrFromInt(addr); - var i: u32 = 0; - while (i < n) : (i += 1) { - const byte = p[i]; - for ([2]u8{ byte >> 4, byte & 0xf }) |nib| { - writeByte(if (nib < 10) '0' + nib else 'a' + (nib - 10)); - } - } - writeByte('\r'); - writeByte('\n'); -} - /// A u32 as eight hex digits, reading no memory at all. pub fn dumpWord(v: u32) void { var shift: u5 = 28; diff --git a/src/fs.zig b/src/fs.zig index 032ab9c0..e809eda5 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -686,18 +686,10 @@ test "a path with a part over 255 bytes is NameTooLong, never a panic" { /// that follows. pub fn makeDirs(dir: []const u8) void { if (comptime !platform_has_fs) return; - var z: [4096:0]u8 = undefined; - if (dir.len == 0 or dir.len >= z.len) return; - @memcpy(z[0..dir.len], dir); - z[dir.len] = 0; + if (dir.len == 0) return; pardes.turn.yield(); defer pardes.turn.back(); - for (z[1..dir.len], 1..) |c, i| if (c == '/') { - z[i] = 0; - _ = libc.mkdir(z[0..i :0], 0o755); - z[i] = '/'; - }; - _ = libc.mkdir(z[0..dir.len :0], 0o755); + _ = std.Io.Dir.cwd().createDirPathStatus(std.Io.Threaded.global_single_threaded.io(), dir, .fromMode(0o755)) catch {}; } /// Whether `dir` is not there to make because one above it refuses: its diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 2d01db33..795ea743 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -54,11 +54,6 @@ const Ground = struct { } }; -fn ground(theme_bg: ?[3]u8, transparent: bool) Ground { - if (theme_bg) |rgb| return .opaqueRgb(rgb); - return .{ .rgb = bg_default, .clear = transparent }; -} - const p9_arrow_clr = [32]u8{ 0xFF, 0xFF, 0x80, 0x01, 0x80, 0x02, 0x80, 0x0C, 0x80, 0x10, 0x80, 0x10, 0x80, 0x08, 0x80, 0x04, @@ -1769,7 +1764,6 @@ const Gui = struct { capture_xfer_size: u32 = 0, soft_present: bool = false, - transparent: bool = false, surface_opacity: bool = false, applied_window_opacity: u8 = 100, soft_renderer: ?*c.SDL_Renderer = null, @@ -2187,7 +2181,7 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u const native_wayland = !test_mode and std.mem.eql(u8, std.mem.span(c.SDL_GetCurrentVideoDriver()), "wayland"); // Background-only opacity needs per-pixel alpha; whole-window compositor // opacity would dim the text as well. SDL requires this flag at creation. - const surface_opacity = config.gui_transparent or native_wayland; + const surface_opacity = native_wayland; if (surface_opacity) win_flags |= c.SDL_WINDOW_TRANSPARENT; const window = c.SDL_CreateWindow("pardes", 1120, 720, win_flags) orelse { log.err("SDL_CreateWindow: {s}", .{c.SDL_GetError()}); @@ -2391,7 +2385,6 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u .capture_series = test_mode and env.get("PARDES_TEST_SERIES") != null, .capture_dir = capture_dir orelse "", .soft_present = soft_present, - .transparent = config.gui_transparent, .surface_opacity = surface_opacity, .soft_renderer = soft_renderer, }; @@ -6092,7 +6085,7 @@ fn renderFrame( coverFrame(previous_covered, surface.cols, surface.rows, surface.previous_body_layers, surface.previous_tag_layers, surface.previous_regions); try buildDecor(g, gpa, surface, &groups, layout, win_w, win_h, cursors_shown); - const page = ground(chrome.page, g.transparent); + const page: Ground = .opaqueRgb(chrome.page orelse bg_default); const background_opacity = backgroundOpacity(g.applied_window_opacity); var color_target = std.mem.zeroes(c.SDL_GPUColorTargetInfo); color_target.texture = scene; @@ -8449,7 +8442,7 @@ fn softPresentFrame(g: *Gui, cmd: *c.SDL_GPUCommandBuffer, target: *c.SDL_GPUTex // The cell shader already produced premultiplied backgrounds with opaque // foreground ink. Copy that alpha unchanged; never modulate the full frame. _ = c.SDL_SetRenderDrawBlendMode(renderer, c.SDL_BLENDMODE_NONE); - _ = c.SDL_SetRenderDrawColor(renderer, 0, 0, 0, if (g.transparent or g.surface_opacity) 0 else 255); + _ = c.SDL_SetRenderDrawColor(renderer, 0, 0, 0, if (g.surface_opacity) 0 else 255); _ = c.SDL_RenderClear(renderer); _ = c.SDL_RenderTexture(renderer, texture, null, null); _ = c.SDL_RenderPresent(renderer); diff --git a/src/hunks.zig b/src/hunks.zig index 24aaf63d..8cd5c43a 100644 --- a/src/hunks.zig +++ b/src/hunks.zig @@ -111,11 +111,7 @@ const Out = struct { fn deinit(out: *Out) void { out.text.deinit(); - for (out.rows.items) |r| { - out.p.gpa.free(r.path); - out.p.gpa.free(r.colors); - } - out.rows.deinit(out.p.gpa); + locations.freeRowList(out.p.gpa, &out.rows); } const Meta = struct { diff --git a/src/locations.zig b/src/locations.zig index 1e4a20cf..6f086214 100644 --- a/src/locations.zig +++ b/src/locations.zig @@ -33,6 +33,15 @@ pub fn freeRows(gpa: std.mem.Allocator, rows: []Row) void { gpa.free(rows); } +/// A list of rows being built, given up: each row's own bytes, then the list. +pub fn freeRowList(gpa: std.mem.Allocator, rows: *std.ArrayList(Row)) void { + for (rows.items) |row| { + gpa.free(row.path); + gpa.free(row.colors); + } + rows.deinit(gpa); +} + pub fn equalRows(a: []const Row, b: []const Row) bool { if (a.len != b.len) return false; for (a, b) |left, right| { @@ -316,13 +325,7 @@ pub fn formatCallstack(p: *pardes.Pardes, dir: []const u8, input: []const u8) !R var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); var rows: std.ArrayList(Row) = .empty; - errdefer { - for (rows.items) |row| { - p.gpa.free(row.path); - p.gpa.free(row.colors); - } - rows.deinit(p.gpa); - } + errdefer freeRowList(p.gpa, &rows); const stacked = p.settings.callstack_layout == .stacked; const resolved = try resolveCallstack(p, arena, dir, input); var lines = std.mem.splitScalar(u8, std.mem.trimEnd(u8, input, "\n"), '\n'); @@ -496,13 +499,7 @@ pub fn format(p: *pardes.Pardes, dir: []const u8, input: []const u8, anchor: ?us var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); var rows: std.ArrayList(Row) = .empty; - errdefer { - for (rows.items) |row| { - p.gpa.free(row.path); - p.gpa.free(row.colors); - } - rows.deinit(p.gpa); - } + errdefer freeRowList(p.gpa, &rows); var mapped = anchor; if (p.locations_config.layout == .stacked) { for (pending.items, 0..) |row, index| { diff --git a/src/look.zig b/src/look.zig index 588574ed..2d97cb9f 100644 --- a/src/look.zig +++ b/src/look.zig @@ -32,9 +32,7 @@ const Key = pardes.Key; const Event = pardes.Event; const Pardes = pardes.Pardes; -extern "c" fn fork() c_int; extern "c" fn execv(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; -extern "c" fn _exit(status: c_int) noreturn; const opener_path: ?[*:0]const u8 = switch (builtin.os.tag) { .linux => "/usr/bin/xdg-open", @@ -46,15 +44,15 @@ pub fn openLink(url: []const u8) void { const opener = opener_path orelse return; var buf: [1024]u8 = undefined; const url_z = std.fmt.bufPrintSentinel(&buf, "{s}", .{url}, 0) catch return; - const pid = fork(); + const pid = libc.fork(); if (pid < 0) return; if (pid == 0) { - if (fork() == 0) { + if (libc.fork() == 0) { @import("host_io.zig").resetChildSignals(); const argv: [3:null]?[*:0]const u8 = .{ opener, url_z.ptr, null }; _ = execv(opener, &argv); } - _exit(0); + libc._exit(0); } _ = libc.waitpid(pid, null, 0); } diff --git a/src/main.zig b/src/main.zig index ea2db917..52093b9a 100644 --- a/src/main.zig +++ b/src/main.zig @@ -144,32 +144,22 @@ fn pageInto(io: std.Io, gpa: std.mem.Allocator, dial: []const u8, text: []const /// Stdin to its end, as it came (its escapes are the session's to parse, /// pager.zig), at most a file's limit, a longer one cut there and said so /// at its end. -fn readStdinText(gpa: std.mem.Allocator) ![]u8 { +fn readStdinText(io: std.Io, gpa: std.mem.Allocator) ![]u8 { const limit = pardes.memory.limits.max_file_bytes; var raw: std.ArrayList(u8) = .empty; var chunk: [64 * 1024]u8 = undefined; - var cut = false; - while (true) { - const n = std.c.read(0, &chunk, chunk.len); - if (n < 0) { - if (std.posix.errno(n) == .INTR) continue; - return error.ReadFailed; - } - if (n == 0) break; - const got: usize = @intCast(n); - if (raw.items.len + got > limit) { - try raw.appendSlice(gpa, chunk[0 .. limit - raw.items.len]); - cut = true; - break; - } - try raw.appendSlice(gpa, chunk[0..got]); - } - if (cut) { - // CAN ends an escape the cut left half sent, and SGR 0 its colour, - // so the note is never swallowed or tinted. - const said = "\x18\x1b[m\n[pardes: the rest of stdin is cut: a pane holds at most a file's limit]\n"; - try raw.appendSlice(gpa, said); - } + var stdin = std.Io.File.stdin().readerStreaming(io, &chunk); + // One byte past the limit says there is more. + stdin.interface.appendRemaining(gpa, &raw, .limited(limit + 1)) catch |err| switch (err) { + error.StreamTooLong => { + raw.shrinkRetainingCapacity(limit); + // CAN ends an escape the cut left half sent, and SGR 0 its colour, + // so the note is never swallowed or tinted. + const said = "\x18\x1b[m\n[pardes: the rest of stdin is cut: a pane holds at most a file's limit]\n"; + try raw.appendSlice(gpa, said); + }, + else => |e| return e, + }; return raw.toOwnedSlice(gpa); } @@ -561,7 +551,7 @@ fn nativeMain(std_init: std.process.Init) !void { // made of it (as acme's `B` has no stdin, through pane/new, a name // and the body), and back at once: the PAGER a pane's shell gets. if (positional) |word| if (std.mem.eql(u8, word, "-")) { - const text = readStdinText(arena) catch |err| Refuse.with(init.io, "stdin", err); + const text = readStdinText(init.io, arena) catch |err| Refuse.with(init.io, "stdin", err); // Nothing paged: no pane, and done. if (text.len == 0) return; pageInto(init.io, arena, parent.dial, text); @@ -676,7 +666,7 @@ fn nativeMain(std_init: std.process.Init) !void { // `pardes -` outside a session: an editor whose first pane holds stdin, // as `vim -` does; the terminal is /dev/tty, never stdin. if (positional) |a| if (std.mem.eql(u8, a, "-")) { - opts.stdin_text = readStdinText(arena) catch |err| badArgs(init.io, "stdin: {s}", .{@errorName(err)}); + opts.stdin_text = readStdinText(init.io, arena) catch |err| badArgs(init.io, "stdin: {s}", .{@errorName(err)}); // Nothing paged: nothing to show. if (opts.stdin_text.?.len == 0) return; positional = null; diff --git a/src/syntax.zig b/src/syntax.zig index 1c09c9f3..803d815a 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -1172,15 +1172,14 @@ fn paintDiffPiece(gpa: std.mem.Allocator, window: anytype, bytes: []const u8, at errdefer syntax_allocator.free(colored); try paintHunk(gpa, colored, bytes, kinds, sel); window.put(at, colored); + // An empty slot, else the least recently used. var oldest: usize = 0; for (&diff_pieces, 0..) |*slot, i| { const piece = slot.* orelse { oldest = i; break; }; - if (diff_pieces[oldest]) |o| if (piece.used < o.used) { - oldest = i; - }; + if (piece.used < diff_pieces[oldest].?.used) oldest = i; } if (diff_pieces[oldest]) |old| syntax_allocator.free(old.styles); diff_pieces[oldest] = .{ .hash = hash, .styles = colored, .used = diff_clock }; diff --git a/src/tagline.zig b/src/tagline.zig index b6601d61..e668419d 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -192,12 +192,7 @@ pub fn defaultTail(pane: *const Pane) []const u8 { /// The tag as it is shown, read and pointed at: its computed prefix and /// its own text after it. pub fn tagText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]u8 { - const prefix = try tagPrefix(p, pane); - const tail = curTail(pane); - const out = try arena.alloc(u8, prefix.len + tail.len); - @memcpy(out[0..prefix.len], prefix); - @memcpy(out[prefix.len..], tail); - return out; + return std.mem.concat(arena, u8, &.{ try tagPrefix(p, pane), curTail(pane) }); } /// Give the keyboard to the tag in normal mode (`:`), its cursor where diff --git a/src/terminal.zig b/src/terminal.zig index 05054521..755fde6c 100644 --- a/src/terminal.zig +++ b/src/terminal.zig @@ -1363,7 +1363,8 @@ const Rows = struct { const empty_grid = [1][]const u8{""}; /// What LEAVING raw tty mode does to one prompt row, decided from its cells -/// alone. See config.tty_blank for why any of this happens. +/// alone: OSC 133 prompt cells are hidden in normal mode, what was typed at +/// them stays. const PromptCut = union(enum) { /// show the row exactly as ghostty dumped it keep, @@ -1375,7 +1376,6 @@ const PromptCut = union(enum) { }; fn promptCut(pin: ghostty_vt.Pin) PromptCut { - if (config.tty_blank == .prompt_and_input) return .blank; const cells = pin.cells(.all); var cols: usize = 0; while (cols < cells.len and cells[cols].semantic_content == .prompt) cols += 1; diff --git a/src/web.zig b/src/web.zig index f89aa7e9..fd6371c0 100644 --- a/src/web.zig +++ b/src/web.zig @@ -15,58 +15,19 @@ const mouse = @import("mouse.zig"); const gpa = std.heap.wasm_allocator; const embedded_dump = @embedFile("embedded.dump.zon"); const input_capacity = 64 * 1024; -const c_alloc_header_size = 16; const attr_tagline: u16 = 1 << 7; +/// Tree-sitter's C runtime is linked into this module: its malloc, calloc, +/// realloc and free are the wasm allocator's, as the Zig core's are. A var, +/// as c_heap compares the allocator it is at run time (wasm_allocator's +/// `ptr` is undefined, which comptime refuses to compare). +var c_allocator: std.mem.Allocator = gpa; +const c_heap = @import("c_heap").Heap(&c_allocator); comptime { - if (c_alloc_header_size < @sizeOf(usize)) @compileError("C allocation header is too small"); -} - -/// Tree-sitter's C runtime is linked into this module. Its conventional -/// allocation symbols share the same wasm allocator as the Zig core and keep -/// the original allocation size in a 16-byte, max-aligned prefix. -export fn malloc(size_arg: usize) callconv(.c) ?*anyopaque { - const size = @max(size_arg, 1); - const total = std.math.add(usize, c_alloc_header_size, size) catch return null; - const bytes = gpa.alignedAlloc(u8, .@"16", total) catch return null; - const header: *align(16) usize = @ptrCast(bytes.ptr); - header.* = total; - return @ptrCast(bytes.ptr + c_alloc_header_size); -} - -export fn calloc(count: usize, size: usize) callconv(.c) ?*anyopaque { - const len = std.math.mul(usize, count, size) catch return null; - const ptr = malloc(len) orelse return null; - if (len != 0) { - const bytes: [*]u8 = @ptrCast(ptr); - @memset(bytes[0..len], 0); - } - return ptr; -} - -export fn free(ptr: ?*anyopaque) callconv(.c) void { - const data = ptr orelse return; - const data_bytes: [*]u8 = @ptrCast(data); - const base: [*]align(16) u8 = @ptrCast(@alignCast(data_bytes - c_alloc_header_size)); - const header: *align(16) usize = @ptrCast(base); - gpa.free(base[0..header.*]); -} - -export fn realloc(ptr: ?*anyopaque, size: usize) callconv(.c) ?*anyopaque { - if (ptr == null) return malloc(size); - if (size == 0) { - free(ptr); - return null; - } - const data_bytes: [*]u8 = @ptrCast(ptr.?); - const base: [*]align(16) u8 = @ptrCast(@alignCast(data_bytes - c_alloc_header_size)); - const header: *align(16) usize = @ptrCast(base); - const old_size = header.* - c_alloc_header_size; - const replacement = malloc(size) orelse return null; - const replacement_bytes: [*]u8 = @ptrCast(replacement); - @memcpy(replacement_bytes[0..@min(old_size, size)], data_bytes[0..@min(old_size, size)]); - free(ptr); - return replacement; + @export(&c_heap.malloc, .{ .name = "malloc" }); + @export(&c_heap.calloc, .{ .name = "calloc" }); + @export(&c_heap.realloc, .{ .name = "realloc" }); + @export(&c_heap.free, .{ .name = "free" }); } pub const std_options: std.Options = .{ .logFn = logFn }; -- cgit v1.3 From 18d89dcedaed1f8437799621675e88ca47d7cdc1 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 10:29:10 -0300 Subject: Search converge 2/6: a pane's places, every match or listed place tinted and ticked on the rail, n/N stepping them silently, shifted by an edit rather than searched again --- src/File.zig | 10 +- src/Places.zig | 849 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/body_layer.zig | 1 + src/detached/wire.zig | 4 +- src/draw.zig | 11 + src/gui/gui.zig | 15 +- src/mouse.zig | 9 +- src/normal.zig | 30 +- src/panes.zig | 6 + src/pardes.zig | 8 + src/surface.zig | 12 + 11 files changed, 942 insertions(+), 13 deletions(-) create mode 100644 src/Places.zig (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index b1a4271f..3db22f95 100644 --- a/src/File.zig +++ b/src/File.zig @@ -184,6 +184,10 @@ pub const State = struct { /// One tree_sitter_gpa-owned syntax.Syn byte per highlighted source byte. highlights: []u8 = &.{}, location_rows: []locations.Row = &.{}, + /// The last edit's splice: what the text at `revision` kept of the one + /// before it at either end (`old_len` long). A pane's places shift by it + /// rather than search the whole text again (Places.shift). + splice: struct { revision: u32 = 0, head: usize = 0, tail: usize = 0, old_len: usize = 0 } = .{}, highlight_start: usize = 0, syntax_dirty: bool = true, tree_context: bool = false, @@ -1187,7 +1191,10 @@ pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void { reportEdit(p, f, new); if (f.mini) |*mini| mini.deinit(p.gpa); f.mini = null; - const starts: []usize = if (f.line_starts.len > 0) editedLineStarts(p.gpa, f.line_starts, f.content, new, span) catch &.{} else &.{}; + // Found once for the line index and the places both (32 bytes a step). + const known = span orelse spanOf(f.content, new); + const starts: []usize = if (f.line_starts.len > 0) editedLineStarts(p.gpa, f.line_starts, f.content, new, known) catch &.{} else &.{}; + const old_len = f.content.len; // ponytail: a whole-text hash per edit that keeps the saved length; a // rolling hash when that too matters. if (f.revision == f.saved_revision or f.saved_hash == null) { @@ -1199,6 +1206,7 @@ pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void { if (f.content.len > 0) p.gpa.rawFree(f.content, .of(u8), @returnAddress()); f.content = new; f.revision +%= 1; + f.splice = .{ .revision = f.revision, .head = known.head, .tail = known.tail, .old_len = old_len }; if (f.saved_hash) |h| if ((f.saved_len orelse new.len) == new.len and std.hash.Wyhash.hash(0, new) == h) { f.saved_revision = f.revision; }; diff --git a/src/Places.zig b/src/Places.zig new file mode 100644 index 00000000..435a138a --- /dev/null +++ b/src/Places.zig @@ -0,0 +1,849 @@ +//! A pane's places: where in its text the current search, or the current +//! list, says to look, and which of them is current. A query pane typed +//! into under this pane feeds them (`/pat` as it is typed, a Grep's hits +//! in this file, a language server's references), so do `*` and the `/` +//! register; whichever fed them last is their provenance. They are shown +//! three ways that read these fields and nothing else, so they cannot +//! disagree: every place tinted in the body (the current one stronger), a +//! tick on the scroll rail at each one's place in the file (B1 on a tick +//! goes there), and the current one selected and in view. n and N step +//! them, round the end without a word (the count in the query pane's tag +//! says where you are). +//! +//! A pattern's places are found where the text is shown first, then on to +//! the end, then from the top up to where it started, a frame's budget at +//! a time (`fill`, run after every step and on every tick until done), so +//! a keystroke in a big file costs what its view costs. They are for one +//! revision of the text: an edit shifts the ones it did not touch and +//! finds again only on the lines it touched (File.State.splice), so typing +//! in a pane whose places are shown costs a line, not the file. +const std = @import("std"); +const pardes = @import("pardes.zig"); +const panes = @import("panes.zig"); +const modal = @import("modal.zig"); +const colors = @import("colors.zig"); +const regexp = @import("regexp.zig"); +const normal = @import("normal.zig"); +const memory = @import("memory.zig"); +const Surface = @import("surface.zig").Surface; +const Pardes = pardes.Pardes; +const Pane = panes.Pane; +const Text = panes.Text; +const File = panes.File; + +const Places = @This(); + +/// One place: byte offsets into the file's text, `end` past its last byte. +pub const Hit = struct { start: usize, end: usize }; + +/// What fed them. `typed`: a query pane's `/pat` while it is typed, not +/// in the `/` register yet. `search`: the `/` register's pattern (a query +/// answered with Enter, `*`). `list`: a list's places in this text (a +/// Grep's hits in an open file, every pane's for All, a language server's +/// references or diagnostics), matched as given. +pub const Provenance = enum { typed, search, list }; + +/// Places past this many are not kept. ponytail: 16 bytes a place, 16 MB +/// at the cap; a sparse count past it if a million is ever too few. +pub const max_hits = 1 << 20; +/// What one frame spends finding places: about 4 ms on the clock, checked +/// between pieces of the text; mvzr's steps (Regex.budget is about 300 ms +/// of them, so this is about 5 ms), which bound one slow piece; and bytes +/// read, the bound where there is no clock (the board, the web). +pub const frame_ns: u64 = 4 * std.time.ns_per_ms; +pub const frame_steps: u64 = regexp.Regex.budget / 64; +pub const frame_bytes: usize = 8 << 20; +/// The text is searched in pieces of about this much, each ending at a +/// line's end, so that a budget runs out between pieces, not inside one. +/// A folding set lowers its copy of the text a piece at a time too. +const chunk_bytes = 16 << 10; +/// A rail's ticks are placed to 1/`tick_scale` of the file. +pub const tick_scale = @import("surface.zig").rail_tick_scale; + +pub fn nowNs() u64 { + if (comptime !pardes.hosted) return 0; + var ts: std.c.timespec = undefined; + if (std.c.clock_gettime(.MONOTONIC, &ts) != 0) return 0; + return @as(u64, @intCast(ts.sec)) *| std.time.ns_per_s +| @as(u64, @intCast(ts.nsec)); +} + +started: bool = false, +provenance: Provenance = .search, +/// The query pane that fed them, by serial; 0 for `*` and the register. +from: u32 = 0, +/// The pattern as it was typed (gpa); empty for a list's places. +pattern: []u8 = &.{}, +/// It did not compile as a regex (`foo(` while typing `foo(x)`), or it is +/// a Grep's: matched as the characters it is. +literal: bool = false, +/// No capital in it: matched without regard to case, on a lowered copy. +fold: bool = false, +re: ?normal.SearchRegex = null, +/// The lowered copy of the text a folding set searches (gpa), of the text +/// at `hay_revision`, lowered a piece at a time as it is searched (`low`, +/// one bit a `chunk_bytes`): kept across patterns, spliced by an edit. +hay: []u8 = &.{}, +hay_revision: u32 = 0, +low: std.DynamicBitSetUnmanaged = .{}, +/// Sorted, apart from one another. +hits: std.ArrayList(Hit) = .empty, +/// The text the places are of: its revision and length. +revision: u32 = 0, +len: usize = 0, +/// What has been searched: [lo, hi) from the view on, then [0, head_to). +/// `nhead` of the hits are from the second, all before `lo`. +lo: usize = 0, +hi: usize = 0, +head_to: usize = 0, +nhead: usize = 0, +/// Where the last budget ran out: a line too slow for a whole frame's +/// budget, run out at twice, is passed over and counted. +stuck_at: ?usize = null, +skipped: u32 = 0, +capped: bool = false, +current: ?usize = null, +/// The first place at or after this offset becomes current once the +/// search has got there; with `seek_moves` it takes the selection and view. +seek: ?usize = null, +seek_moves: bool = false, +/// The last step went round the end of the text (or its start). Said by +/// nothing but the count wrapping in the query pane's tag. +wrapped: bool = false, +/// Moves with every change to the places or the current one (the ticks' +/// cue and the query pane's); `hits_gen` only with the places. +gen: u32 = 0, +hits_gen: u32 = 0, +ticks: std.ArrayList(u16) = .empty, +ticks_gen: u32 = std.math.maxInt(u32), +/// The body as it was when a query began, for Esc to put back exactly +/// (gpa; empty: nothing remembered). +snap: []modal.Selection = &.{}, +snap_pri: usize = 0, +snap_expl: bool = false, +snap_scroll: usize = 0, +snap_hscroll: i32 = 0, + +pub fn deinit(set: *Places, gpa: std.mem.Allocator) void { + set.clear(gpa); + if (set.hay.len > 0) gpa.rawFree(set.hay, .of(u8), @returnAddress()); + set.low.deinit(gpa); + set.hits.deinit(gpa); + set.ticks.deinit(gpa); + gpa.free(set.snap); + set.* = .{}; +} + +/// No places here any more: no tint, no ticks. +pub fn clear(set: *Places, gpa: std.mem.Allocator) void { + if (set.re) |re| gpa.free(re.branches); + set.re = null; + gpa.free(set.pattern); + set.pattern = &.{}; + set.hits.clearRetainingCapacity(); + set.started = false; + set.from = 0; + set.current = null; + set.seek = null; + set.wrapped = false; + set.gen +%= 1; + set.hits_gen +%= 1; +} + +/// Whether the body and the rail show these places now: never a stale set. +pub fn shows(set: *const Places, pane: *const Pane) bool { + const f = pane.file orelse return false; + return set.started and set.revision == f.revision and set.len == f.content.len; +} + +pub fn complete(set: *const Places) bool { + return set.hi >= set.len and set.head_to >= set.lo; +} + +/// The first hit starting at or after `at`. +pub fn firstFrom(hits: []const Hit, at: usize) usize { + var lo: usize = 0; + var hi = hits.len; + while (lo < hi) { + const mid = lo + (hi - lo) / 2; + if (hits[mid].start < at) lo = mid + 1 else hi = mid; + } + return lo; +} + +/// Search `pane`'s text for `pattern` from now on, in place of whatever +/// fed the places before. A regex unless `literal`, smart case (no capital: +/// any case); one that does not compile is matched literally, so a pattern +/// half typed still finds what it says. `seek`: the place at or after it +/// becomes current, and with `moves` the selection and view go to it. +pub fn search(set: *Places, p: *Pardes, pane: *Pane, provenance: Provenance, from: u32, pattern: []const u8, literal: bool, seek: ?usize, moves: bool) void { + const f = if (pane.file) |*file| file else return; + const gpa = p.gpa; + // The same question again (a key that left the pattern as it was): + // the places stand, the current one too. + if (set.started and set.re != null and set.literal == literal and std.mem.eql(u8, set.pattern, pattern)) { + set.provenance = provenance; + set.from = from; + return; + } + set.clear(gpa); + if (pattern.len == 0) return; + set.pattern = gpa.dupe(u8, pattern) catch return; + set.provenance = provenance; + set.from = from; + set.fold = for (pattern) |c| { + if (std.ascii.isUpper(c)) break false; + } else true; + set.literal = literal; + const arena = p.scratch.allocator(); + const folded = if (set.fold) std.ascii.allocLowerString(arena, pattern) catch return else pattern; + set.re = if (literal) null else normal.SearchRegex.compile(gpa, folded) catch null; + if (set.re == null) { + set.literal = true; + var escaped: std.ArrayList(u8) = .empty; + normal.appendSearchLiteral(&escaped, arena, folded) catch return; + set.re = normal.SearchRegex.compile(gpa, escaped.items) catch return; + } + set.started = true; + set.revision = f.revision +% 1; // `fill` starts it over for the text as it is + set.seek = seek; + set.seek_moves = moves; + set.fill(p, pane, frame_bytes, frame_steps); +} + +/// A list's places in this text, as it gives them (sorted here), in place +/// of whatever fed them before: a language server's references, say. +/// `current`: the one at or after this offset is current. +pub fn feed(set: *Places, p: *Pardes, pane: *Pane, from: u32, hits: []const Hit, current: ?usize) void { + const f = if (pane.file) |*file| file else return; + set.clear(p.gpa); + set.hits.ensureTotalCapacity(p.gpa, hits.len) catch return; + for (hits) |h| if (h.end > h.start and h.end <= f.content.len) set.hits.appendAssumeCapacity(h); + std.mem.sort(Hit, set.hits.items, {}, struct { + fn lt(_: void, a: Hit, b: Hit) bool { + return a.start < b.start; + } + }.lt); + set.started = true; + set.provenance = .list; + set.from = from; + set.revision = f.revision; + set.len = f.content.len; + set.lo = 0; + set.hi = f.content.len; + set.head_to = 0; + set.nhead = 0; + if (current) |at| { + const i = firstFrom(set.hits.items, at); + set.current = if (i < set.hits.items.len) i else if (set.hits.items.len > 0) 0 else null; + } + set.hits_gen +%= 1; +} + +/// The lowered copy's pieces holding [from, to) lowered, as they are +/// first searched. +fn lower(set: *Places, content: []const u8, from: usize, to: usize) void { + if (to <= from) return; + var b = from / chunk_bytes; + const last = (to - 1) / chunk_bytes; + while (b <= last and b < set.low.bit_length) : (b += 1) { + if (set.low.isSet(b)) continue; + const lo = b * chunk_bytes; + const hi = @min(content.len, lo + chunk_bytes); + _ = std.ascii.lowerString(set.hay[lo..hi], content[lo..hi]); + set.low.set(b); + } +} + +/// A fresh lowered copy for the text as it is now, nothing of it lowered. +fn freshHay(set: *Places, gpa: std.mem.Allocator, f: *File.State) bool { + if (set.hay.len > 0) gpa.rawFree(set.hay, .of(u8), @returnAddress()); + set.hay = &.{}; + set.hay = memory.unfilled(gpa, f.content.len) catch return false; + set.low.resize(gpa, (f.content.len + chunk_bytes - 1) / chunk_bytes, false) catch return false; + set.low.unsetAll(); + set.hay_revision = f.revision; + return true; +} + +/// The text changed by one splice since the places were found (`fill` +/// checks): the ones before the lines it touched kept, the ones after +/// moved by what it added or took, those lines searched again. A list's +/// places on them are dropped (nothing says where they went). Costs the +/// places and the lines, never the whole text. +fn shift(set: *Places, p: *Pardes, f: *File.State) void { + const gpa = p.gpa; + const new = f.content; + const sp = f.splice; + const old_len = sp.old_len; + const head = @min(sp.head, new.len); + const tail_new = new.len - @min(sp.tail, new.len - head); + // The lines it touched, in the new text and in the old. + const ds = if (std.mem.lastIndexOfScalar(u8, new[0..head], '\n')) |nl| nl + 1 else 0; + const de = if (std.mem.indexOfScalarPos(u8, new, tail_new, '\n')) |nl| nl + 1 else new.len; + const ode = de + old_len - new.len; + var kept: usize = 0; + var after: usize = set.hits.items.len; + for (set.hits.items, 0..) |h, i| { + if (h.end <= ds) kept = i + 1; + if (h.start >= ode) { + after = i; + break; + } + } + const old_current = set.current; + // The lowered copy takes the same splice. + if (set.fold) { + const hay = memory.unfilled(gpa, new.len) catch return set.restart(p, f); + @memcpy(hay[0..head], set.hay[0..head]); + const tail_len = new.len - tail_new; + @memcpy(hay[tail_new..], set.hay[old_len - tail_len ..]); + _ = std.ascii.lowerString(hay[head..tail_new], new[head..tail_new]); + if (set.hay.len > 0) gpa.rawFree(set.hay, .of(u8), @returnAddress()); + set.hay = hay; + set.low.resize(gpa, (new.len + chunk_bytes - 1) / chunk_bytes, true) catch return set.restart(p, f); + set.low.setAll(); + set.hay_revision = f.revision; + } + // The lines it touched, searched again: what lies between. + var middle: std.ArrayList(Hit) = .empty; + defer middle.deinit(gpa); + if (set.re) |*re| { + const hay: []const u8 = if (set.fold) set.hay else new; + for (re.branches) |*b| b.re.steps = regexp.Regex.budget; + var at = ds; + while (at < de) { + const m = re.find(hay, at, de) orelse break; + if (m.start >= de) break; + if (m.end > m.start) middle.append(gpa, .{ .start = m.start, .end = m.end }) catch break; + at = if (m.end > m.start) m.end else m.end + 1; + } + } + const delta_add = new.len >= old_len; + for (set.hits.items[after..]) |*h| { + if (delta_add) { + h.start += new.len - old_len; + h.end += new.len - old_len; + } else { + h.start -= old_len - new.len; + h.end -= old_len - new.len; + } + } + set.hits.replaceRange(gpa, kept, after - kept, middle.items) catch return set.restart(p, f); + set.current = null; + if (old_current) |c| { + if (c < kept) set.current = c else if (c >= after) set.current = c - after + kept + middle.items.len else { + // It was on the lines touched: the first there now, or after. + set.seek = ds; + set.seek_moves = false; + } + } + set.revision = f.revision; + set.len = new.len; + set.lo = 0; + set.hi = new.len; + set.head_to = 0; + set.nhead = 0; + set.gen +%= 1; + set.hits_gen +%= 1; +} + +/// The places found again from nothing for the text as it is, the view +/// first; the current one looked for where it was. +fn restart(set: *Places, p: *Pardes, f: *File.State) void { + const gpa = p.gpa; + if (set.current) |c| if (set.seek == null and c < set.hits.items.len) { + set.seek = @min(set.hits.items[c].start, f.content.len); + set.seek_moves = false; + }; + set.current = null; + set.hits.clearRetainingCapacity(); + set.revision = f.revision; + set.len = f.content.len; + set.lo = File.lineStart(gpa, f, f.scroll); + set.hi = set.lo; + set.head_to = 0; + set.nhead = 0; + set.stuck_at = null; + set.skipped = 0; + set.capped = false; + set.gen +%= 1; + set.hits_gen +%= 1; + if (set.re == null) { + // A list's places have no pattern to be found again by: kept where + // the text still has room for them. ponytail: they go stale by what + // was added above them, until the list is asked again. + set.lo = 0; + set.hi = f.content.len; + } +} + +/// Find more of the places, `bytes` of text and `steps` of mvzr's at most, +/// the rows the pane shows always; and once the current place's offset has +/// been searched, make it current. Run after every step (with no budget: +/// the view only) and every tick (a frame's). +pub fn fill(set: *Places, p: *Pardes, pane: *Pane, bytes: usize, steps: u64) void { + const started_ns = nowNs(); + if (!set.started) return; + const f = if (pane.file) |*file| file else return set.clear(p.gpa); + const gpa = p.gpa; + if (f.revision != set.revision or f.content.len != set.len) { + const spans = if (set.re) |re| for (re.branches) |b| { + if (b.re.spans) break true; + } else false else false; + const one_splice = f.splice.revision == f.revision and set.revision +% 1 == f.revision and + f.splice.old_len == set.len and set.complete() and !spans and + (!set.fold or set.hay_revision == set.revision); + if (one_splice) set.shift(p, f) else set.restart(p, f); + if (set.re == null) { + // a list's: clamp what the text has no room for any more + var n: usize = 0; + for (set.hits.items) |h| if (h.end <= f.content.len) { + set.hits.items[n] = h; + n += 1; + }; + set.hits.shrinkRetainingCapacity(n); + if (set.current) |c| if (c >= n) { + set.current = null; + }; + } + } + if (set.fold and (set.hay_revision != f.revision or set.hay.len != f.content.len)) + if (!set.freshHay(gpa, f)) return set.clear(gpa); + if (set.re == null) return set.settleSeek(p, pane); + const re = &set.re.?; + const hay: []const u8 = if (set.fold) set.hay else f.content; + for (re.branches) |*b| b.re.steps = @max(1, steps / re.branches.len); + // A pattern naming a newline matches across lines: searched in one piece. + const spans = for (re.branches) |b| { + if (b.re.spans) break true; + } else false; + const view_end = File.lineStart(gpa, f, f.scroll + pane.rows + 1); + var left = bytes; + var head: std.ArrayList(Hit) = .empty; + defer head.deinit(gpa); + const found_before = set.hits.items.len; + while (left > 0 or (set.hi < view_end and set.hi >= set.lo)) { + const forward = set.hi < set.len; + if (!forward and set.head_to >= set.lo) break; + const from = if (forward) set.hi else set.head_to; + const limit = if (forward) set.len else set.lo; + var to = if (spans) limit else @min(limit, from + chunk_bytes); + if (to < limit) to = if (std.mem.indexOfScalarPos(u8, f.content, to, '\n')) |nl| @min(limit, nl + 1) else limit; + if (set.fold) set.lower(f.content, from -| 1, @min(f.content.len, to + 1)); + // Each piece is searched as sam searches a range (normal.zig + // applySelRegex): the text around it still says where lines begin. + var at = from; + var short = false; + const out = if (forward) &set.hits else &head; + head.clearRetainingCapacity(); + while (at < to) { + if (set.hits.items.len + head.items.len >= max_hits) { + set.capped = true; + at = to; + break; + } + const m = re.find(hay, at, to) orelse { + for (re.branches) |b| if (b.re.steps == 0) { + short = true; + }; + if (!short) at = to; + break; + }; + if (m.start >= to) { + at = to; + break; + } + if (m.end > m.start) out.append(gpa, .{ .start = m.start, .end = m.end }) catch return; + at = if (m.end > m.start) m.end else m.end + 1; + } + at = @min(at, to); + if (short) { + // Spent: the rest next frame, from here. Spent here twice, the + // line is past searching and is passed over. + if (set.stuck_at == at) { + at = if (std.mem.indexOfScalarPos(u8, hay, at, '\n')) |nl| @min(to, nl + 1) else to; + set.skipped += 1; + set.stuck_at = null; + } else set.stuck_at = at; + } + if (forward) set.hi = at else { + set.hits.insertSlice(gpa, set.nhead, head.items) catch return; + if (set.current) |*c| c.* += head.items.len; + set.nhead += head.items.len; + set.head_to = at; + } + left -|= at - from; + if (short) break; + // A frame's time spent (a whole search's for n and N, whose steps + // are mvzr's whole budget). + if (started_ns != 0 and bytes != std.math.maxInt(usize) and nowNs() - started_ns > frame_ns) break; + } + if (set.hits.items.len != found_before) { + set.gen +%= 1; + set.hits_gen +%= 1; + } + set.settleSeek(p, pane); +} + +/// The place at or after `seek` becomes current, once all the text +/// between them has been searched (never a false "next" across a gap). +fn settleSeek(set: *Places, p: *Pardes, pane: *Pane) void { + const seek = set.seek orelse return; + const hits = set.hits.items; + const i = firstFrom(hits, seek); + const between_to = if (i < hits.len) hits[i].start + 1 else set.len; + const searched = if (set.head_to >= set.lo) between_to <= set.hi else between_to <= set.head_to or (seek >= set.lo and between_to <= set.hi); + if (i < hits.len and searched) { + set.current = i; + set.wrapped = false; + } else if (set.complete()) { + set.current = if (hits.len > 0) 0 else null; + set.wrapped = hits.len > 0 and seek > 0; + } else return; + set.seek = null; + set.gen +%= 1; + if (!set.seek_moves) return; + if (set.current) |c| return set.goTo(pane, c, false); + // Nothing matches: the body as it was before the query, as helix + // leaves it. + set.restore(p, pane); +} + +/// The places have more to do on a frame of their own: places still to +/// find, or a text changed under them. +pub fn busy(set: *const Places, pane: *const Pane) bool { + if (!set.started) return false; + const f = pane.file orelse return false; + return !set.complete() or set.revision != f.revision or set.len != f.content.len; +} + +/// Make place `i` current: the primary selection on it (a new one beside +/// the others in select mode, `add`), the view on it, centred when it was +/// off it. +pub fn goTo(set: *Places, pane: *Pane, i: usize, add: bool) void { + const f = if (pane.file) |*file| file else return; + if (i >= set.hits.items.len) return; + const t = &pane.body; + const text = f.content; + const h = set.hits.items[i]; + var ranges: [Text.max_selections]modal.Selection = undefined; + const got = t.ranges(text, 0, &ranges); + const old = ranges[got.pri]; + const next: modal.Selection = if (old.anchor > old.head) + .{ .anchor = h.end, .head = h.start } + else + .{ .anchor = h.start, .head = h.end }; + if (add and got.n < ranges.len) { + ranges[got.n] = next; + t.setRanges(text, ranges[0 .. got.n + 1], &.{}, got.n, true); + } else { + ranges[got.pri] = next; + t.setRanges(text, ranges[0..got.n], &.{}, got.pri, true); + } + set.current = i; + set.gen +%= 1; + const off = pane.scroll(); + if (t.cur_row < off or t.cur_row >= off + @as(i32, pane.rows)) + pane.scrollBy(t.cur_row - off - @divTrunc(@as(i32, pane.rows), 2)); + t.show(); +} + +/// n and N (and Ctrl-n, Ctrl-p on a query's line): the next place after +/// the primary selection, or the last before it, `count` times, round the +/// end of the text when there is none, silently. It needs them all, so it +/// finishes the search first. ponytail: within mvzr's whole budget (300 +/// ms), which a file of millions of lines can outrun; past it a step sees +/// what was found. +pub fn step(set: *Places, p: *Pardes, pane: *Pane, forward: bool, count: u32, add: bool) void { + const f = if (pane.file) |*file| file else return; + set.fill(p, pane, std.math.maxInt(usize), regexp.Regex.budget); + const hits = set.hits.items; + if (hits.len == 0) return; + const t = &pane.body; + var wrapped = false; + for (0..count) |_| { + var ranges: [Text.max_selections]modal.Selection = undefined; + const got = t.ranges(f.content, 0, &ranges); + const old = ranges[got.pri]; + var i: usize = 0; + if (forward) { + i = firstFrom(hits, @max(old.anchor, old.head)); + if (i == hits.len) { + i = 0; + wrapped = true; + } + } else { + const from = @min(old.anchor, old.head); + i = firstFrom(hits, from); + while (i > 0 and hits[i - 1].end > from) i -= 1; + if (i == 0) { + i = hits.len - 1; + wrapped = true; + } else i -= 1; + } + set.goTo(pane, i, add); + } + set.wrapped = wrapped; +} + +/// Whether n and N in this pane are these places' to step: a list's or a +/// query's always; a search's while it is what the register says (an `s`, +/// a `/` elsewhere or `"a` since makes them helix's register search again). +pub fn answersN(set: *const Places, p: *Pardes, pane: *const Pane) bool { + if (!set.shows(pane) and !set.started) return false; + if (set.provenance != .search) return p.register == 0; + const name = if (p.register != 0) p.register else p.registers.last_search; + const pat = p.registers.value(name, 0) orelse return false; + if (!set.literal) return std.mem.eql(u8, pat, set.pattern); + var spelled: std.ArrayList(u8) = .empty; + normal.appendSearchLiteral(&spelled, p.scratch.allocator(), set.pattern) catch return false; + return std.mem.eql(u8, pat, spelled.items) or std.mem.eql(u8, pat, set.pattern); +} + +/// The body as it is now, for `restore` to put back: when a query begins. +pub fn remember(set: *Places, p: *Pardes, pane: *Pane) void { + const f = if (pane.file) |*file| file else return; + var ranges: [Text.max_selections]modal.Selection = undefined; + const got = pane.body.ranges(f.content, 0, &ranges); + p.gpa.free(set.snap); + set.snap = p.gpa.dupe(modal.Selection, ranges[0..got.n]) catch &.{}; + set.snap_pri = got.pri; + set.snap_expl = (pane.body.vsel.active and pane.body.vsel.explicit) or pane.body.msel.active; + set.snap_scroll = f.scroll; + set.snap_hscroll = pane.hscroll; +} + +/// The body as `remember` kept it: its selections and its view. +pub fn restore(set: *Places, p: *Pardes, pane: *Pane) void { + _ = p; + const f = if (pane.file) |*file| file else return; + if (set.snap.len == 0) return; + for (set.snap) |*r| { + r.anchor = @min(r.anchor, f.content.len); + r.head = @min(r.head, f.content.len); + } + pane.body.setRanges(f.content, set.snap, &.{}, set.snap_pri, set.snap_expl); + f.scroll = set.snap_scroll; + f.syntax_dirty = true; + pane.hscroll = set.snap_hscroll; +} + +/// What `remember` kept, let go: the query was answered. +pub fn forget(set: *Places, gpa: std.mem.Allocator) void { + gpa.free(set.snap); + set.snap = &.{}; +} + +/// Where the query began: the primary selection's end when it was +/// remembered, else now. +pub fn origin(set: *const Places, pane: *const Pane) usize { + if (set.snap.len > 0) return @max(set.snap[set.snap_pri].anchor, set.snap[set.snap_pri].head); + const f = pane.file orelse return 0; + const r = pane.body.primaryRange(f.content, 0); + return @min(r.anchor, r.head); +} + +/// Every place on the rows shown, tinted over the text; the current one in +/// the search colour itself, the rest halfway to the page. +pub fn paint(set: *Places, p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: u16) void { + if (!set.shows(pane)) return; + const f = &pane.file.?; + const th = p.theme(); + const strong = p.chromeTheme().search_bg; + const quiet = colors.mix(th.bg orelse th.tag_bg, strong); + const hits = set.hits.items; + if (hits.len == 0) return; + const nlines = File.nlines(p.gpa, f); + var last_line: i32 = -1; + var vr: i32 = 0; + while (vr < body_h) : (vr += 1) { + const line = pane.wrapAt(vr).line; + if (line == last_line or line < 0) continue; + if (line >= nlines) break; + last_line = line; + const ls = File.lineStart(p.gpa, f, @intCast(line)); + const next = File.lineStart(p.gpa, f, @intCast(line + 1)); + const le = if (next > ls and next <= f.content.len and f.content[next - 1] == '\n') next - 1 else next; + // the first hit ending past the line's start + var lo: usize = 0; + var hi = hits.len; + while (lo < hi) { + const mid = lo + (hi - lo) / 2; + if (hits[mid].end <= ls) lo = mid + 1 else hi = mid; + } + var i = lo; + while (i < hits.len and hits[i].start <= le) : (i += 1) { + const a = @max(hits[i].start, ls) - ls; + const b = @min(hits[i].end, le) - ls; + if (b <= a) continue; + const current = set.current != null and set.current.? == i; + File.paintWordSelection(p, s, pane, r, line, @intCast(a), @intCast(b), if (current) strong else quiet); + } + } +} + +/// The rail's ticks, in 1/`tick_scale`s of the file: one per such step +/// that holds a place, made again only when the places or the current one +/// move. +fn buildTicks(set: *Places, p: *Pardes, f: *File.State) void { + if (set.ticks_gen == set.gen) return; + set.ticks_gen = set.gen; + set.ticks.clearRetainingCapacity(); + const index = File.lineIndex(p.gpa, f) catch return; + const total = @max(1, index.len); + var line: usize = 0; + for (set.hits.items) |h| { + while (line + 1 < index.len and index[line + 1] <= h.start) line += 1; + const b: u16 = @intCast(@min(tick_scale - 1, line * tick_scale / total)); + if (set.ticks.items.len == 0 or set.ticks.items[set.ticks.items.len - 1] != b) + set.ticks.append(p.gpa, b) catch return; + } +} + +/// The step of the rail holding place `i`. +fn tickOf(set: *Places, p: *Pardes, f: *File.State, i: usize) ?u16 { + const index = File.lineIndex(p.gpa, f) catch return null; + const at = set.hits.items[i].start; + var lo: usize = 0; + var hi = index.len; + while (lo < hi) { + const mid = lo + (hi - lo) / 2; + if (index[mid] <= at) lo = mid + 1 else hi = mid; + } + const line = lo -| 1; + return @intCast(@min(tick_scale - 1, line * tick_scale / @max(1, index.len))); +} + +/// These places' ticks onto the frame's, for rail `owner` (draw.place): +/// the cell shells paint them on the rail's track, the pixel ones at their +/// place along it. +pub fn addTicks(set: *Places, p: *Pardes, pane: *Pane, s: *Surface, owner: u8) void { + if (!set.shows(pane)) return; + const f = &pane.file.?; + set.buildTicks(p, f); + const cur = if (set.current) |c| set.tickOf(p, f, c) else null; + for (set.ticks.items) |b| { + if (s.nrail_ticks == s.rail_ticks.len) return; + s.rail_ticks[s.nrail_ticks] = .{ .owner = owner, .at = b, .current = cur != null and cur.? == b }; + s.nrail_ticks += 1; + } +} + +/// The place a click on row `row` of a rail `rows` tall goes to: the first +/// of the tick drawn in that cell, as a cell shell draws it; null where +/// there is none, and the click scrolls as on any rail. +pub fn tickHit(set: *Places, p: *Pardes, pane: *Pane, row: u16, rows: u16) ?usize { + if (!set.shows(pane) or rows == 0) return null; + const f = &pane.file.?; + set.buildTicks(p, f); + const total = File.nlines(p.gpa, f); + for (set.ticks.items) |b| { + if (@as(usize, b) * rows / tick_scale != row) continue; + const first_line = (@as(usize, b) * total + tick_scale - 1) / tick_scale; + const i = firstFrom(set.hits.items, File.lineStart(p.gpa, f, first_line)); + if (i < set.hits.items.len) return i; + } + return null; +} + +/// At the end of every step: more of the places found (a frame's worth on +/// a tick, the view's on anything else), and the current one taken from +/// the selection when something else put it on one (a Look, a click). +pub fn settle(set: *Places, p: *Pardes, pane: *Pane, tick: bool) void { + if (!set.started) return; + set.fill(p, pane, if (tick) frame_bytes else 0, frame_steps); + if (!set.shows(pane)) return; + const f = &pane.file.?; + const r = pane.body.primaryRange(f.content, 0); + const i = firstFrom(set.hits.items, @min(r.anchor, r.head)); + if (i < set.hits.items.len and set.hits.items[i].start == @min(r.anchor, r.head) and + set.hits.items[i].end == @max(r.anchor, r.head) and (set.current == null or set.current.? != i)) + { + set.current = i; + set.gen +%= 1; + } +} + +fn typeKeys(p: *Pardes, keys: []const u8) void { + for (keys) |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); +} + +test "places: * finds them all, n and N step them round the end silently, an edit shifts them" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha beta\ngamma alpha\nALPHA delta\nalphabet\n"); + // `e` selects `alpha`; `*` makes the places from it. + typeKeys(p, "e*"); + const set = &pane.places; + try std.testing.expect(set.started and set.shows(pane)); + try std.testing.expectEqual(Provenance.search, set.provenance); + // smart case: `alpha` has no capital, so ALPHA counts; `*` keeps to + // whole words, so `alphabet` does not + try std.testing.expectEqual(@as(usize, 3), set.hits.items.len); + try std.testing.expectEqual(@as(?usize, 0), set.current); + typeKeys(p, "n"); + try std.testing.expectEqual(@as(?usize, 1), set.current); + typeKeys(p, "n"); + try std.testing.expectEqual(@as(?usize, 2), set.current); + const logged = p.messages.len; + typeKeys(p, "n"); + try std.testing.expectEqual(@as(?usize, 0), set.current); + try std.testing.expect(set.wrapped); + // round the end without a word anywhere + try std.testing.expectEqual(logged, p.messages.len); + typeKeys(p, "N"); + try std.testing.expectEqual(@as(?usize, 2), set.current); + + // An edit on one line: the others shifted, that line found again. + const f = &pane.file.?; + const before = set.hits.items[2]; + const new = try std.testing.allocator.dupe(u8, "alpha beta\ngamma alpha alpha\nALPHA delta\nalphabet\n"); + File.setContentSpan(p, f, new, null); + set.fill(p, pane, 0, frame_steps); + try std.testing.expect(set.shows(pane)); + try std.testing.expectEqual(@as(usize, 4), set.hits.items.len); + try std.testing.expectEqual(before.start + 6, set.hits.items[3].start); + try std.testing.expectEqual(@as(?usize, 3), set.current); + // Another `/` register (an `s`, a search elsewhere): n is helix's again. + p.registers.put(p.gpa, '/', "gamma", 0, 1, true); + try std.testing.expect(!set.answersN(p, pane)); +} + +test "places: a big file costs a keystroke its view, the ticks find the rest, an edit costs a line" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); + defer p.deinit(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(std.testing.allocator); + for (0..40_000) |i| try text.print(std.testing.allocator, "line {d}: some words and a needle {d} here\n", .{ i, i % 7 }); + const pane = try p.setTestFile(text.items); + const set = &pane.places; + // The line index is the file's, made once whatever asks for it first. + _ = try File.lineIndex(p.gpa, &pane.file.?); + const t0 = nowNs(); + set.search(p, pane, .typed, 0, "needle 3", false, 0, true); + const first_ns = nowNs() - t0; + try std.testing.expect(set.hits.items.len > 0); + var ticks: usize = 0; + while (set.busy(pane) and ticks < 10_000) : (ticks += 1) set.settle(p, pane, true); + try std.testing.expect(set.complete()); + const all = set.hits.items.len; + try std.testing.expect(all > 5000); + // An edit: one splice, shifted, no rescan of the file. + const f = &pane.file.?; + const at = 10; + const new = try std.testing.allocator.alloc(u8, f.content.len + 1); + @memcpy(new[0..at], f.content[0..at]); + new[at] = 'x'; + @memcpy(new[at + 1 ..], f.content[at..]); + const t1 = nowNs(); + File.setContentSpan(p, f, new, null); + const t2 = nowNs(); + set.settle(p, pane, false); + const edit_ns = nowNs() - t2; + const text_ns = t2 - t1; + try std.testing.expect(set.complete() and set.shows(pane)); + try std.testing.expectEqual(all, set.hits.items.len); + // PLACES_TIMES=1 says the numbers (on stderr, which fails the run). + if (std.c.getenv("PLACES_TIMES") != null) + std.debug.print("places: first key {d} us, {d} ticks, an edit {d} us (the text's own splice {d} us)\n", .{ first_ns / 1000, ticks, edit_ns / 1000, text_ns / 1000 }); +} diff --git a/src/body_layer.zig b/src/body_layer.zig index 0ddda41d..d44045a6 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -274,6 +274,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane if (p.settings.colors and pane.colorAlgo() != .none) panes.File.recolorSyntax(p, s, pane, f, r, tx, tw, body_h); panes.File.drawWrapMarkers(p, s, pane, r, tx, tw, body_h, pane_bg); + pane.places.paint(p, s, pane, r, body_h); } else if (pane.isTerminal() and p.settings.colors) { panes.terminal.recolorAnsi(p, s, pane, r, tx, tw, body_h, body); panes.File.recolorDiffOutput(p, s, pane, r, tx, tw, body_h, body); diff --git a/src/detached/wire.zig b/src/detached/wire.zig index 2252ce3b..2318d319 100644 --- a/src/detached/wire.zig +++ b/src/detached/wire.zig @@ -12,11 +12,11 @@ const ShaderAnimation = pardes.config.Runtime.ShaderAnimation; /// to be refused, which is what this number is for. /// 8: one layer type: a tag band carries all its rows (not a layer per /// line), and a frame carries the core's placed regions after its layers. -pub const version: u16 = 10; +pub const version: u16 = 11; /// The Chrome palette is carried field by field as its declaration lists /// them, so any change to it changes the wire: bump `version`, then this. -const chrome_layout: u64 = 0x5e758b47fb0cf8da; +const chrome_layout: u64 = 0xbe608bed776ff502; comptime { @setEvalBranchQuota(10_000); var hash = std.hash.Fnv1a_64.init(); diff --git a/src/draw.zig b/src/draw.zig index 93a78090..5c1844bb 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -46,6 +46,7 @@ const NOTICE_LAYER_BASE = pardes.NOTICE_LAYER_BASE; /// painters below and every shell read these rectangles. pub fn place(p: *Pardes, s: *Surface) void { s.nregions = 0; + s.nrail_ticks = 0; s.addRegion(.{ .kind = .page, .rect = .{ .x = 0, .y = 0, .w = s.cols, .h = s.rows } }); for (&p.panes, 0..) |*slot, id| { const pane = slot.* orelse continue; @@ -89,6 +90,7 @@ pub fn place(p: *Pardes, s: *Surface) void { rail.thumb_span = @as(f32, @floatFromInt(@max(1, sb.len))) / @as(f32, @floatFromInt(total)); } s.addRegion(rail); + if (body_h > 0 and pane.image == null) pane.places.addTicks(p, pane, s, owner); // Each notice a chip at the right edge, one to a row in the order // collectNotices chose, as wide as its own message and no wider, so // the text beneath the rest of the row keeps reading as the file. @@ -566,6 +568,8 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { .tag_fg = chrome.tag_fg, .scroll_track = chrome.scroll_track, .scroll_thumb = chrome.scroll_thumb, + .match_tick = chrome.search_bg, + .match_current = p.theme().fg orelse chrome.tag_fg, .accent = chrome.box, .sel_fg = p.theme().sel_fg, .sel_bg = p.theme().sel_bg, @@ -973,6 +977,13 @@ fn renderPane(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r: } try body_layer.joinBody(p, s, arena, pane, r, id, active, rail.*); + // A query's places' ticks, each in the track's cell of its row: chrome, + // painted with the rail (a pixel shell draws its own from the same list). + for (s.rail_ticks[0..s.nrail_ticks]) |tick| { + if (tick.owner != id or rail.rect.h == 0) continue; + const row: u16 = @intCast(@min(rail.rect.h - 1, @as(usize, tick.at) * rail.rect.h / panes.Places.tick_scale)); + s.fill(rail.rect.x, rail.rect.y + row, 1, 1, .{ .bg = .{ .rgb = if (tick.current) s.chrome.match_current else s.chrome.match_tick } }); + } } /// The workspace and column tags: each line a tag layer, and the grid's diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 1daf8f41..5017ab53 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -8718,7 +8718,8 @@ fn buildDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, g nbodies += 1; }; const bodies = body_buf[0..nbodies]; - try paneDecor(g, gpa, placed, groups, index, chrome, layout, surface.cols, surface.rows, win_w, win_h, track); + const ticks: []const pardes.RailTick = if (closing) &.{} else surface.rail_ticks[0..surface.nrail_ticks]; + try paneDecor(g, gpa, placed, ticks, groups, index, chrome, layout, surface.cols, surface.rows, win_w, win_h, track); // G9, while nothing moves: a halo round the body's selection. if (index == 0 and groups.tracks == 0 and chrome.fx & 1 != 0) try glowBlocks(g, gpa, surface, .selection, layout, win_w, win_h); // G11: a glow under the word a look-hover would open. @@ -8817,7 +8818,7 @@ fn buildDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, g /// Each pane's rule between its tag and body, and its scroll rail: a page /// coloured gutter with a thin track and its thumb, running down through the /// pixels past the last whole row. Only the panes of group `index`. -fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, groups: *const Groups, index: usize, chrome: *const pardes.Chrome, layout: CellLayout, cols: u16, rows: u16, win_w: f32, win_h: f32, track: ?pardes.animation.Track) !void { +fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, ticks: []const pardes.RailTick, groups: *const Groups, index: usize, chrome: *const pardes.Chrome, layout: CellLayout, cols: u16, rows: u16, win_w: f32, win_h: f32, track: ?pardes.animation.Track) !void { const page = chrome.page orelse bg_default; for (regions) |rail| { if (rail.kind != .rail or rail.rect.h == 0 or groupOf(groups, rail.serial) != index) continue; @@ -8889,6 +8890,16 @@ fn paneDecor(g: *Gui, gpa: std.mem.Allocator, regions: []const pardes.Region, gr const thumb_y1 = if (rail.thumb_y + rail.thumb_h == rail.rect.h) y1 else @as(f32, @floatFromInt(rail.rect.y + rail.thumb_y + rail.thumb_h)) * layout.h; try addDecor(g, gpa, column[0], thumb_y0, column[1] - dp(1), thumb_y1, chrome.scroll_thumb, 1, track, win_w, win_h); } + // A query's places' ticks over the track and thumb, where its matches + // are in the file (Places.addTicks); the current one last, on top. + const track_px = body_y1 - y0; + for (0..2) |pass| for (ticks) |tick| { + if (tick.owner != rail.owner or tick.current != (pass == 1)) continue; + const at = @as(f32, @floatFromInt(tick.at)) / @as(f32, @floatFromInt(pardes.panes.Places.tick_scale)); + const h = if (tick.current) dp(3) else dp(2); + const ty = y0 + std.math.clamp(at * track_px, 0, track_px - h); + try addDecor(g, gpa, column[0], ty, column[1], ty + h, if (tick.current) chrome.match_current else chrome.match_tick, 1, track, win_w, win_h); + }; } } diff --git a/src/mouse.zig b/src/mouse.zig index eeb987b2..ec5560d0 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -751,8 +751,15 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { const tag_y = p.tagTop(pane, r); const body_y = p.bodyTop(pane, r); if (mcol < r.x + config.GUTTER) { - // gutter scrollbar: a left click scrolls UP to that row p.active = id; + // A tick of the pane's places: that place, selected and in view. + // The rail is chrome, and only the tick's cell does this. + const rail_h = r.h -| pane.tag_rows; + if (mrow >= body_y and mrow < body_y + rail_h) if (pane.places.tickHit(p, pane, mrow - body_y, rail_h)) |i| { + pane.focus = .body; + return pane.places.goTo(pane, i, false); + }; + // gutter scrollbar: a left click scrolls UP to that row pane.scrollBy(-(@as(i32, mrow) - @as(i32, body_y))); } else { const on_tag = mrow >= tag_y and mrow < tag_y + pane.tag_rows; diff --git a/src/normal.zig b/src/normal.zig index 8de23d1c..808ac886 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -256,18 +256,20 @@ pub fn searchSelection(p: *Pardes, t: *Text, text: []const u8, boundary: bool) v } // mvzr's word boundary is ASCII-only. Strip outer boundaries and check -// them against Unicode characters for search-selection patterns. -const SearchRegex = struct { +// them against Unicode characters for search-selection patterns. A pane's +// Places keep one of these, compiled with the gpa, for as long as they live. +pub const SearchRegex = struct { const Branch = struct { re: regexp.Regex, start_word: bool, end_word: bool }; branches: []Branch, - fn compile(arena: std.mem.Allocator, pattern: []const u8) !SearchRegex { + pub fn compile(arena: std.mem.Allocator, pattern: []const u8) !SearchRegex { if (std.mem.indexOf(u8, pattern, "\\b") == null) { const branches = try arena.alloc(Branch, 1); branches[0] = try branch(pattern); return .{ .branches = branches }; } var branches: std.ArrayList(Branch) = .empty; + errdefer branches.deinit(arena); var from: usize = 0; var depth: usize = 0; var escaped = false; @@ -291,7 +293,7 @@ const SearchRegex = struct { } try branches.append(arena, try branch(pattern[from..])); for (branches.items) |*b| b.re.steps = regexp.Regex.budget / branches.items.len; - return .{ .branches = branches.items }; + return .{ .branches = try branches.toOwnedSlice(arena) }; } fn branch(pattern: []const u8) !Branch { @@ -303,7 +305,7 @@ const SearchRegex = struct { return .{ .re = try regexp.Regex.compile(pat), .start_word = start, .end_word = end }; } - fn find(self: *SearchRegex, hay: []const u8, from: usize, to: usize) ?regexp.Regex.Match { + pub fn find(self: *SearchRegex, hay: []const u8, from: usize, to: usize) ?regexp.Regex.Match { var best: ?regexp.Regex.Match = null; for (self.branches) |*b| { var at = from; @@ -929,8 +931,22 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void }, .pipe_selection => |how| return p.startPrompt(pane, t, .{ .pipe = how }), .search => return p.startPrompt(pane, &pane.body, .{ .search = config.search_marker }), - .search_step => |step| return searchStep(p, t, text, step.direction, step.count), - .search_selection => |boundary| return searchSelection(p, t, text, boundary), + // In a file's text, n and N step its places while they answer for + // the register (Places.answersN); else helix's search of the register. + .search_step => |step| if (t.what == .body and pane.file != null and pane.places.answersN(p, pane)) + return pane.places.step(p, pane, step.direction == .forward, step.count, t.select) + else + return searchStep(p, t, text, step.direction, step.count), + .search_selection => |boundary| { + searchSelection(p, t, text, boundary); + // The pattern's places: the selection is already on one of them. + if (t.what == .body and pane.file != null) { + const name = if (p.register != 0) p.register else '/'; + const pat = p.registers.value(name, 0) orelse return; + const r = pane.body.primaryRange(text, 0); + pane.places.search(p, pane, .search, 0, pat, false, @min(r.anchor, r.head), false); + } + }, .node => |walk| return nodeSelect(p, pane, t, walk), .goto_word => return startJump(p, pane, t), .object_jump => |jump| return objectJump(p, pane, t, text, range, jump.object, jump.direction == .forward, jump.count), diff --git a/src/panes.zig b/src/panes.zig index 14df07e9..73794b91 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -187,6 +187,10 @@ pub const Pane = struct { input: Text = .{ .what = .input }, search_pane: ?usize = null, search_row: ?usize = null, + /// Where in this pane's text the current search or list says to look + /// (`/`, `*`, a query pane's rows, n/N): tinted, ticked on the rail, + /// the current one selected (Places.zig). + places: Places = .{}, look_at: ?LookSpot = null, /// `gw`'s words, labelled in order while it waits for a label to be /// typed (gpa-owned); `jump_first` is the label's first letter once typed. @@ -649,6 +653,8 @@ pub const File = @import("File.zig"); pub const Output = @import("Output.zig"); +pub const Places = @import("Places.zig"); + pub const Dir = @import("Dir.zig"); pub const mini = @import("mini.zig"); diff --git a/src/pardes.zig b/src/pardes.zig index c58452ee..c4011f7d 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -44,6 +44,7 @@ pub const ImagePlace = @import("surface.zig").ImagePlace; pub const Surface = @import("surface.zig").Surface; pub const Region = @import("surface.zig").Region; pub const Chrome = @import("surface.zig").Chrome; +pub const RailTick = @import("surface.zig").RailTick; pub const MAX_REGIONS = @import("surface.zig").MAX_REGIONS; pub const builtins = @import("builtins.zig"); /// Every builtin as JSON, for the docs (tools/gen_builtins_json.zig). @@ -484,6 +485,7 @@ test { _ = @import("Presentation.zig"); _ = @import("animation.zig"); _ = @import("pager.zig"); + _ = @import("Places.zig"); } pub const Builtin = builtins.registry.Builtin(); @@ -5081,6 +5083,7 @@ pub const Pardes = struct { pane.tag.deinit(p.gpa); pane.input.deinit(p.gpa); pane.jump.deinit(p.gpa); + pane.places.deinit(p.gpa); panes.terminal.deinitEmulator(pane, p.gpa); pane.clearCwd(); pane.fs.deinit(p.gpa); @@ -6115,6 +6118,9 @@ pub const Pardes = struct { look.advanceLookHover(p); }, } + // Each pane's places find a frame's more on a tick, and on any other + // step the ones an edit or a scroll left unfound in the view. + for (p.panes) |slot| if (slot) |pane| pane.places.settle(p, pane, ev == .tick); _ = p.scratch.reset(.{ .retain_with_limit = memory.limits.scratch_kept }); p.sync(); p.fsReport(); @@ -7580,6 +7586,8 @@ pub const Pardes = struct { // seen are stamped 0, which `advance` would count back from). if (p.fs.batch.bytes.items.len > 0) return @max(next, p.fs.batch.last_ns + ctlfs.pane.batch_pause_ns); if (p.chrome_animation.isActive() or p.presentation.animating()) return next; + // Places still to find resume on the next frame. + for (p.panes) |slot| if (slot) |pane| if (pane.places.busy(pane)) return next; var frames: ?u64 = null; if (p.look_hover_wait) |waiting| { const delay = config.look_preview_delay_frames orelse return next; diff --git a/src/surface.zig b/src/surface.zig index 839e8f33..8ed4074c 100644 --- a/src/surface.zig +++ b/src/surface.zig @@ -392,6 +392,10 @@ pub const MAX_REGIONS = 1 + MAX_PANES * (4 + panes.Pane.Notices.max) + pardes.MA /// The colours a pixel shell draws its chrome in (rules, rails, grips, the /// tag underlay), resolved by the core each frame, so a frontend attached /// to a detached session draws them from the frame alone. +pub const RailTick = struct { owner: u8, at: u16, current: bool }; +pub const max_rail_ticks = 4096; +pub const rail_tick_scale = 1024; + pub const Chrome = struct { /// The theme's ground and ink; null where it leaves them to the shell. page: ?[3]u8 = null, @@ -407,6 +411,9 @@ pub const Chrome = struct { tag_fg: [3]u8 = .{ 0, 0, 0 }, scroll_track: [3]u8 = .{ 0, 0, 0 }, scroll_thumb: [3]u8 = .{ 0, 0, 0 }, + /// A pane's places' ticks on its rail, and its current one's. + match_tick: [3]u8 = .{ 0, 0, 0 }, + match_current: [3]u8 = .{ 0, 0, 0 }, /// The theme's accent (a glow's tint). accent: [3]u8 = .{ 0, 0, 0 }, /// A selection's text and ground: a lift keeps their contrast too. @@ -477,6 +484,11 @@ pub const Surface = struct { rows: u16 = 0, regions: [MAX_REGIONS]Region = undefined, nregions: u16 = 0, + /// The panes' places' ticks on their rails (Places.addTicks), + /// placed with the regions: each at `at` 1/`rail_tick_scale`s down its + /// rail's track, the pane's current match's marked. + rail_ticks: [max_rail_ticks]RailTick = undefined, + nrail_ticks: u16 = 0, chrome: Chrome = .{}, cells: []Cell = &.{}, /// bar: draw an insert-style thin cursor instead of the block -- cgit v1.3 From 51903dd947f90381d1a908c488a019289a1c8413 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 11:57:26 -0300 Subject: Search converge 3/6: the query pane, line 1 the query and its first word the source, rows made live like Callstack's, the owner's places showing the set, a +Preview promoted in place, Enter freezes, Esc restores --- docs/typ/builtins-gui.json | 7 +- docs/typ/builtins-tty.json | 7 +- src/File.zig | 2 + src/Names.zig | 446 +++++++++ src/Output.zig | 8 +- src/Places.zig | 39 +- src/Query.zig | 2155 ++++++++++++++++++++++++++++++++++++++++++++ src/Text.zig | 5 +- src/body_layer.zig | 1 + src/builtins.zig | 35 +- src/config.zig | 54 +- src/edit.zig | 20 + src/exec.zig | 20 + src/fs.zig | 2 +- src/layout.zig | 18 +- src/look.zig | 2 + src/mouse.zig | 9 + src/ninep/ctl.zig | 16 +- src/normal.zig | 16 +- src/panes.zig | 7 + src/pardes.zig | 54 +- src/tagline.zig | 8 + test/output.zig | 59 +- 23 files changed, 2921 insertions(+), 69 deletions(-) create mode 100644 src/Names.zig create mode 100644 src/Query.zig (limited to 'src/File.zig') diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index de8fde9c..a502836e 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -102,6 +102,7 @@ {"name": "PanelVertical", "leader": "SPC a v", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close with a vertical wipe, on or off."}, {"name": "PanelWave", "leader": "SPC a w", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close in a wave, on or off."}, {"name": "PanelZoom", "leader": "SPC a z", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes zoom in and out as they open and close, on or off."}, + {"name": "Panes", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pick an open pane by its name in a query pane under this one (SPC b b)."}, {"name": "Parallax", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A theme's page pattern moves with the text at a quarter of its speed, on or off."}, {"name": "PdfFit", "leader": "SPC t z", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Fit the PDF page to the pane by width or by height, flipping between them (or to the one named, `width|height`)."}, {"name": "PdfSections", "leader": "SPC t s", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the PDF's sections in a pane, each a place to go."}, @@ -111,7 +112,7 @@ {"name": "Placement", "leader": "SPC c p", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "acme, pardes", "doc": "Where a new pane goes: acme, as makenewwindow does, or pardes, the older rules."}, {"name": "ProgramEsc", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "In a raw terminal, Esc goes to the program and Shift-Esc backs out, on; off (the default) swaps them."}, {"name": "Putall", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "acme's Putall: every pane holding unsaved edits to a file is saved, each as its own Save; one that is refused (changed on disk since, a write that fails) says so and the rest are saved all the same."}, - {"name": "Recent", "leader": "SPC f r", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "List the files opened lately, closed ones too, each a place to open again."}, + {"name": "Recent", "leader": "SPC f r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "List the files opened lately, closed ones too, each a place to open again."}, {"name": "Redo", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Redo the last undone edit."}, {"name": "Refs", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "List the references to the symbol under the cursor; with an argument (a 2-1 chord's selection), to that symbol, where it is nearest."}, {"name": "Rename", "leader": "SPC l r", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Rename the symbol under the cursor everywhere, to its argument."}, @@ -119,6 +120,10 @@ {"name": "Restore", "leader": "SPC s r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Replace every pane with those of a dump file, the last one Dump wrote when bare."}, {"name": "Right", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane, or column tag, to the right."}, {"name": "Save", "leader": "SPC f s", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Write the pane's text to its file, or to the file its argument names."}, + {"name": "Search", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Search in a query pane under this pane, line 1 the argument (`Panes`, `Symbols lay`, `All needle`, `/re`, any of its words); bare, `/`."}, + {"name": "SearchPane", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "reuse, new", "doc": "A search from a pane that has a query pane: reuse it, or open a new one and leave the last where it is."}, + {"name": "SearchPlace", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "attached, column", "doc": "Where a query pane goes: attached, under the pane that asked, out of its rows alone, or column, in the finder column."}, + {"name": "SearchRows", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The rows a query pane is born with under its line 1, 1 through 100; default 8. It never resizes itself."}, {"name": "SelectRefs", "leader": "SPC l h", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Select every reference to the symbol under the cursor."}, {"name": "SelectionGlow", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A soft halo of the selection's colour round it in the body, on or off."}, {"name": "Shader", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "A Shadertoy file into the post chain, or out of it, compiled again when saved; off empties the chain."}, diff --git a/docs/typ/builtins-tty.json b/docs/typ/builtins-tty.json index 4db29e6e..7e9ba678 100644 --- a/docs/typ/builtins-tty.json +++ b/docs/typ/builtins-tty.json @@ -91,6 +91,7 @@ {"name": "PanelVertical", "leader": "SPC a v", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close with a vertical wipe, on or off."}, {"name": "PanelWave", "leader": "SPC a w", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes open and close in a wave, on or off."}, {"name": "PanelZoom", "leader": "SPC a z", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "Panes zoom in and out as they open and close, on or off."}, + {"name": "Panes", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pick an open pane by its name in a query pane under this one (SPC b b)."}, {"name": "PdfFit", "leader": "SPC t z", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Fit the PDF page to the pane by width or by height, flipping between them (or to the one named, `width|height`)."}, {"name": "PdfSections", "leader": "SPC t s", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the PDF's sections in a pane, each a place to go."}, {"name": "PdfTint", "leader": "SPC t i", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Tint the PDF page to the theme, or show it as printed, stepping through them (or to the one named, `disabled|filtered|full`)."}, @@ -98,7 +99,7 @@ {"name": "Placement", "leader": "SPC c p", "also": [], "arg": true, "scope": "root", "setting": true, "choices": "acme, pardes", "doc": "Where a new pane goes: acme, as makenewwindow does, or pardes, the older rules."}, {"name": "ProgramEsc", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "In a raw terminal, Esc goes to the program and Shift-Esc backs out, on; off (the default) swaps them."}, {"name": "Putall", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "acme's Putall: every pane holding unsaved edits to a file is saved, each as its own Save; one that is refused (changed on disk since, a write that fails) says so and the rest are saved all the same."}, - {"name": "Recent", "leader": "SPC f r", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "List the files opened lately, closed ones too, each a place to open again."}, + {"name": "Recent", "leader": "SPC f r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "List the files opened lately, closed ones too, each a place to open again."}, {"name": "Redo", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Redo the last undone edit."}, {"name": "Refs", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "List the references to the symbol under the cursor; with an argument (a 2-1 chord's selection), to that symbol, where it is nearest."}, {"name": "Rename", "leader": "SPC l r", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Rename the symbol under the cursor everywhere, to its argument."}, @@ -106,6 +107,10 @@ {"name": "Restore", "leader": "SPC s r", "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Replace every pane with those of a dump file, the last one Dump wrote when bare."}, {"name": "Right", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Move the keyboard to the pane, or column tag, to the right."}, {"name": "Save", "leader": "SPC f s", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Write the pane's text to its file, or to the file its argument names."}, + {"name": "Search", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Search in a query pane under this pane, line 1 the argument (`Panes`, `Symbols lay`, `All needle`, `/re`, any of its words); bare, `/`."}, + {"name": "SearchPane", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "reuse, new", "doc": "A search from a pane that has a query pane: reuse it, or open a new one and leave the last where it is."}, + {"name": "SearchPlace", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "attached, column", "doc": "Where a query pane goes: attached, under the pane that asked, out of its rows alone, or column, in the finder column."}, + {"name": "SearchRows", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The rows a query pane is born with under its line 1, 1 through 100; default 8. It never resizes itself."}, {"name": "SelectRefs", "leader": "SPC l h", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Select every reference to the symbol under the cursor."}, {"name": "Shell", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "The shell new terminals run; bare, $SHELL if it is executable, else /bin/sh."}, {"name": "Subtypes", "leader": "SPC l T", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the subtypes of the type under the cursor."}, diff --git a/src/File.zig b/src/File.zig index 3db22f95..f633cad0 100644 --- a/src/File.zig +++ b/src/File.zig @@ -598,6 +598,8 @@ pub fn gutterWidth(pane: *const Pane) u16 { // pager and delta show none. if (file.pager) return 0; if (file.output) |o| if (std.meta.eql(o.from, Output.Origin{ .cmd = .Diff })) return 0; + // A query pane's rows carry their own line numbers (Query.zig). + if (pane.query != null) return 0; var lines = if (file.line_starts.len > 0) file.line_starts.len else lineCount(file.content); var digits: u16 = 1; while (lines >= 10) : (lines /= 10) digits += 1; diff --git a/src/Names.zig b/src/Names.zig new file mode 100644 index 00000000..48447f56 --- /dev/null +++ b/src/Names.zig @@ -0,0 +1,446 @@ +//! Names a query pane picks from by a fuzzy query: the files under a +//! directory (walked a slice a frame), the recent files, the open panes, +//! a file's declarations. Each keystroke scores them again with a small +//! fzf-style scorer (subsequence, Smith-Waterman with affine gaps, bonuses +//! at the starts of words and path segments), a frame's budget at a time, +//! the best kept first. Lifted from the pick prototype (Pick.zig), whose +//! scorer took ~1 ms for 20k paths in a release build. Embedded in a +//! Query; the rows it shows are the Query's to make. +const Names = @This(); + +const std = @import("std"); +const pardes = @import("pardes.zig"); +const panes = @import("panes.zig"); +const config = @import("config.zig"); +const filesystem = @import("fs.zig"); +const Pardes = pardes.Pardes; + +/// The candidates' rows, back to back, no newlines. +bytes: std.ArrayList(u8) = .empty, +/// `bytes` in lowercase, for a lowercase query to match without folding. +lower: std.ArrayList(u8) = .empty, +cands: std.ArrayList(Cand) = .empty, +/// The candidates `query` matches, best first. +hits: std.ArrayList(Hit) = .empty, +/// `cands[0..scored]` were scored against `query` (in `hits` or not): the +/// ones a walk adds past it are scored as they come. +scored: u32 = 0, +/// Candidates to score before `cands[scored..]`: what the last query +/// matched, when this one only grew from it. +pending: std.ArrayList(u32) = .empty, +pending_at: usize = 0, +query_buf: [max_query]u8 = undefined, +query_len: u8 = 0, +/// The files walk, while it lasts (Find in a query pane until the disk +/// engine has it). +walk: ?Walk = null, +/// Bumped whenever `hits` change: the rows are made again only then. +gen: u32 = 0, + +pub const Cand = struct { + /// The row: `bytes[start..][0..len]`. + start: u32, + len: u16, + /// What is scored: the row's `[key..][0..key_len]` (a path, a + /// declaration's text, a name), its basename from `base` within it. + key: u16, + key_len: u16, + base: u16, + /// What the row is of: a line of the owner (Symbols, 1-based), a + /// pane's serial (Panes); 0 for a path. + ref: u32 = 0, +}; + +pub const Hit = struct { cand: u32, score: i32 }; + +/// The most rows shown: the rest are counted. +pub const max_rows = 200; +pub const max_query = 64; +/// A candidate is scored over its first this many bytes. +const max_text = 512; +const max_cands = 200_000; +/// Entries a walk reads a frame: ~1-3 ms warm. +const walk_slice = 2000; +const walk_max_depth = 16; +/// A keystroke's scoring, and a frame's: what is left waits a frame. +const score_budget_ns = 4 * std.time.ns_per_ms; + +const Walk = struct { + root: std.Io.Dir, + walker: std.Io.Dir.SelectiveWalker, + done: bool = false, + skipped: u32 = 0, + + fn deinit(w: *Walk) void { + const io = std.Io.Threaded.global_single_threaded.io(); + // The walker closes a directory only as it leaves it: the ones it + // is still in (all but the root, which is ours) are closed here. + if (w.walker.stack.items.len > 1) for (w.walker.stack.items[1..]) |*item| item.iter.reader.dir.close(io); + w.walker.deinit(); + w.root.close(io); + } +}; + +pub fn deinit(n: *Names, gpa: std.mem.Allocator) void { + if (n.walk) |*w| w.deinit(); + n.bytes.deinit(gpa); + n.lower.deinit(gpa); + n.cands.deinit(gpa); + n.hits.deinit(gpa); + n.pending.deinit(gpa); + n.* = .{}; +} + +/// No candidates, no walk: for a source filled again. +pub fn reset(n: *Names) void { + if (n.walk) |*w| w.deinit(); + n.walk = null; + n.bytes.clearRetainingCapacity(); + n.lower.clearRetainingCapacity(); + n.cands.clearRetainingCapacity(); + n.hits.clearRetainingCapacity(); + n.pending.clearRetainingCapacity(); + n.pending_at = 0; + n.scored = 0; + n.gen +%= 1; +} + +pub fn queryText(n: *const Names) []const u8 { + return n.query_buf[0..n.query_len]; +} + +pub fn add(n: *Names, gpa: std.mem.Allocator, row_in: []const u8, key: usize, key_len: usize, base: u16, ref: u32) !void { + if (n.cands.items.len >= max_cands) return; + const text = row_in[0..@min(row_in.len, std.math.maxInt(u16))]; + try n.cands.append(gpa, .{ + .start = @intCast(n.bytes.items.len), + .len = @intCast(text.len), + .key = @intCast(@min(key, text.len)), + .key_len = @intCast(@min(key_len, text.len - @min(key, text.len))), + .base = base, + .ref = ref, + }); + try n.bytes.appendSlice(gpa, text); + try n.lower.ensureUnusedCapacity(gpa, text.len); + for (text) |c| n.lower.appendAssumeCapacity(std.ascii.toLower(c)); +} + +pub fn relative(path: []const u8, dir: []const u8) []const u8 { + const d = std.mem.trimEnd(u8, dir, "/"); + if (d.len > 0 and path.len > d.len + 1 and std.mem.startsWith(u8, path, d) and path[d.len] == '/') return path[d.len + 1 ..]; + return path; +} + +pub fn baseOf(path: []const u8) u16 { + const slash = std.mem.lastIndexOfScalar(u8, std.mem.trimEnd(u8, path, "/"), '/') orelse return 0; + return @intCast(@min(slash + 1, max_text)); +} + +/// The files under `dir`, walked from now on a slice a frame (`walkSlice`): +/// the first slice now, so a small tree is whole before the first frame. +pub fn startWalk(n: *Names, gpa: std.mem.Allocator, dir: []const u8) !void { + if (comptime !filesystem.platform_has_fs) return error.NoFilesystem; + const io = std.Io.Threaded.global_single_threaded.io(); + pardes.turn.yield(); + defer pardes.turn.back(); + var dir_handle = try std.Io.Dir.cwd().openDir(io, dir, .{ .iterate = true }); + errdefer dir_handle.close(io); + n.walk = .{ .root = dir_handle, .walker = try dir_handle.walkSelectively(gpa) }; + n.walkSlice(gpa); +} + +/// One frame's slice of a walk: up to `walk_slice` entries, files kept, +/// what a Find skips skipped and dot-directories too. +pub fn walkSlice(n: *Names, gpa: std.mem.Allocator) void { + const w = if (n.walk) |*w| w else return; + if (w.done) return; + const io = std.Io.Threaded.global_single_threaded.io(); + pardes.turn.yield(); + defer pardes.turn.back(); + var steps: usize = 0; + walk: while (steps < walk_slice) : (steps += 1) { + const e = (w.walker.next(io) catch { + w.skipped += 1; + continue; + }) orelse { + w.done = true; + break; + }; + if (e.kind != .directory) { + n.add(gpa, e.path, 0, e.path.len, baseOf(e.path), 0) catch { + w.done = true; + break; + }; + if (n.cands.items.len >= max_cands) { + w.done = true; + break; + } + continue; + } + if (e.depth() >= walk_max_depth or e.basename[0] == '.') continue; + for (filesystem.find_skip) |s| if (std.mem.eql(u8, e.basename, s)) continue :walk; + w.walker.enter(io, e) catch { + w.skipped += 1; + }; + } +} + +pub fn walking(n: *const Names) bool { + return if (n.walk) |w| !w.done else false; +} + +/// Still walking, or still scoring what it has: it wants the next frame. +pub fn busy(n: *const Names) bool { + return n.walking() or n.scored < n.cands.items.len or n.pending_at < n.pending.items.len; +} + +/// A new query: scored again, from what the last one matched when it only +/// grew from it. +pub fn typed(n: *Names, gpa: std.mem.Allocator, text: []const u8) void { + const q = text[0..@min(text.len, max_query)]; + if (std.mem.eql(u8, q, n.queryText()) and n.scored > 0) return; + // A query that only grew matches a subset of what the last one did: + // only those are scored again (and then the ones not yet scored). + const grew = n.query_len > 0 and std.mem.startsWith(u8, q, n.queryText()) and std.mem.indexOfScalar(u8, q[n.query_len..], ' ') == null; + n.query_len = @intCast(q.len); + @memcpy(n.query_buf[0..q.len], q); + if (grew) { + const pending = n.pending.items[n.pending_at..]; + std.mem.copyForwards(u32, n.pending.items[0..pending.len], pending); + n.pending.items.len = pending.len; + n.pending.ensureUnusedCapacity(gpa, n.hits.items.len) catch return; + for (n.hits.items) |h| n.pending.appendAssumeCapacity(h.cand); + } else { + n.scored = 0; + n.pending.clearRetainingCapacity(); + } + n.pending_at = 0; + n.hits.clearRetainingCapacity(); + n.rescore(gpa); +} + +/// Scores the pending candidates, then `cands[scored..]`, into `hits`, and +/// sorts them: at most `score_budget_ns` of it a call, the rest on the +/// next frames while the best so far is shown. +pub fn rescore(n: *Names, gpa: std.mem.Allocator) void { + const q = n.queryText(); + const empty = std.mem.trim(u8, q, " ").len == 0; + const io = std.Io.Threaded.global_single_threaded.io(); + const started = std.Io.Clock.awake.now(io); + const had = n.hits.items.len; + const was_scored = n.scored; + var count: usize = 0; + while (true) : (count += 1) { + const i: u32 = if (n.pending_at < n.pending.items.len) blk: { + n.pending_at += 1; + break :blk n.pending.items[n.pending_at - 1]; + } else if (n.scored < n.cands.items.len) blk: { + n.scored += 1; + break :blk n.scored - 1; + } else break; + const c = n.cands.items[i]; + const key = n.bytes.items[c.start + c.key ..][0..c.key_len]; + const s = if (empty) 0 else match(q, key, n.lower.items[c.start + c.key ..][0..c.key_len], c.base, null, null, null); + if (s) |score| n.hits.append(gpa, .{ .cand = i, .score = score }) catch break; + // The clock every 256 candidates: reading it is not free either. + if (!empty and count % 256 == 255 and + started.durationTo(std.Io.Clock.awake.now(io)).toNanoseconds() > score_budget_ns) break; + } + // An empty query keeps the source's order (the walk's, recency): no + // row moves as the walk goes on, it only grows at the foot. + if (!empty) std.sort.pdq(Hit, n.hits.items, n.cands.items, struct { + fn lt(cands: []const Cand, a: Hit, b: Hit) bool { + if (a.score != b.score) return a.score > b.score; + const la = cands[a.cand].key_len; + const lb = cands[b.cand].key_len; + if (la != lb) return la < lb; + return a.cand < b.cand; + } + }.lt); + if (n.hits.items.len != had or n.scored != was_scored or count > 0) n.gen +%= 1; +} + +/// The row of hit `i` and, in `marks`, the bytes of it the query matched. +pub fn row(n: *const Names, i: usize, marks: []u16, nmarks: *usize) []const u8 { + const c = n.cands.items[n.hits.items[i].cand]; + nmarks.* = 0; + const q = n.queryText(); + if (std.mem.trim(u8, q, " ").len > 0) { + const key = n.bytes.items[c.start + c.key ..][0..c.key_len]; + _ = match(q, key, n.lower.items[c.start + c.key ..][0..c.key_len], c.base, marks, nmarks, &dp_trace); + for (marks[0..nmarks.*]) |*m| m.* += c.key; + } + return n.bytes.items[c.start..][0..c.len]; +} + +// ---- the scorer (pick's) ---- + +const neg: i32 = -(1 << 24); +const score_match = 16; +const gap_start = 3; +const gap_ext = 1; +const bonus_consecutive = 7; +/// At the start of the text or of a path segment. +const bonus_start = 12; +/// After `_ - . : space`. +const bonus_delim = 9; +/// A camelCase hump, or a word after other punctuation. +const bonus_camel = 8; +/// Each matched character in the basename. +const bonus_base = 2; + +/// The scorer's two rows, and the whole table the marks are backtracked +/// through: the main loop's, one score at a time. Not locals: a safe build +/// fills an undefined local, 4 KB a candidate, which was most of a +/// keystroke's time. +var dp_rows: [2][max_text]i32 = undefined; +var dp_trace: [max_query * max_text]i32 = undefined; + +fn bonusAt(text: []const u8, j: usize) i32 { + if (j == 0) return bonus_start; + const prev = text[j - 1]; + const c = text[j]; + if (prev == '/') return bonus_start; + switch (prev) { + '_', '-', '.', ':', ' ', '\t' => return bonus_delim, + else => {}, + } + if (std.ascii.isLower(prev) and std.ascii.isUpper(c)) return bonus_camel; + if (!std.ascii.isAlphanumeric(prev) and std.ascii.isAlphanumeric(c)) return bonus_camel; + return 0; +} + +/// `query`'s score against `text` (`lower` its lowercase copy, its +/// basename from `base`), null if some term of it is not a subsequence of +/// `text`. Terms split on spaces are ANDed; smart case per term. With +/// `marks`, the bytes matched are written there, ascending. +pub fn match(query: []const u8, text_in: []const u8, lower_in: []const u8, base: usize, marks: ?[]u16, marks_len: ?*usize, trace: ?[]i32) ?i32 { + const text = text_in[0..@min(text_in.len, max_text)]; + const lower = lower_in[0..text.len]; + var total: i32 = 0; + var nmarks: usize = 0; + var terms = std.mem.tokenizeScalar(u8, query, ' '); + while (terms.next()) |term_in| { + const term = term_in[0..@min(term_in.len, max_query)]; + const m = term.len; + const sensitive = for (term) |c| { + if (std.ascii.isUpper(c)) break true; + } else false; + // A lowercase term is matched against the lowercase copy. + var low_buf: [max_query]u8 = undefined; + const want = if (sensitive) term else std.ascii.lowerString(&low_buf, term); + const hay = if (sensitive) text else lower; + // The window a match can be in: from the first character's first + // place to the last one's last place, else no match at all. + const lo = std.mem.indexOfScalar(u8, hay, want[0]) orelse return null; + var pos = lo + 1; + for (want[1..]) |c| pos = (std.mem.indexOfScalarPos(u8, hay, pos, c) orelse return null) + 1; + const end = std.mem.lastIndexOfScalar(u8, hay, want[m - 1]).? + 1; + // D[i][j]: the best score with term[i] matched at text[j]. + var prev = &dp_rows[0]; + var cur = &dp_rows[1]; + const width = text.len; + const keep = if (trace) |t| t.len >= m * width else false; + for (0..m) |i| { + var gapped: i32 = neg; // max over k <= j-2 of D[i-1][k], less the gap to j + for (lo..end) |col| { + var best: i32 = neg; + if (i > 0 and col >= lo + 2) gapped = @max(gapped - gap_ext, prev[col - 2] - gap_start); + if (hay[col] == want[i]) { + const own: i32 = score_match + bonusAt(text, col) + @as(i32, if (col >= base) bonus_base else 0); + if (i == 0) { + best = own; + } else if (col > lo) { + const from = @max(if (prev[col - 1] > neg) prev[col - 1] + bonus_consecutive else neg, gapped); + if (from > neg) best = from + own; + } + } + cur[col] = best; + if (keep) trace.?[i * width + col] = best; + } + const t = prev; + prev = cur; + cur = t; + } + var best: i32 = neg; + var at: usize = lo; + for (lo..end) |col| if (prev[col] > best) { + best = prev[col]; + at = col; + }; + if (best <= neg) return null; + total += best; + // Back from the best end, the place each character was matched at. + if (keep and marks != null) { + const out = marks.?; + const t = trace.?; + var i = m; + var col = at; + while (i > 0) { + i -= 1; + if (nmarks < out.len) { + out[nmarks] = @intCast(col); + nmarks += 1; + } + if (i == 0) break; + const here = t[i * width + col]; + const own: i32 = score_match + bonusAt(text, col) + @as(i32, if (col >= base) bonus_base else 0); + if (col > lo and t[(i - 1) * width + col - 1] > neg and t[(i - 1) * width + col - 1] + bonus_consecutive + own == here) { + col -= 1; + continue; + } + var found = col - 1; + if (col >= lo + 2) { + var k = col - 2; + while (true) { + const d = t[(i - 1) * width + k]; + if (d > neg and d - gap_start - @as(i32, @intCast(col - 2 - k)) * gap_ext + own == here) { + found = k; + break; + } + if (k == lo) break; + k -= 1; + } + } + col = found; + } + } + } + if (marks_len) |count| { + if (marks) |out| std.mem.sort(u16, out[0..nmarks], {}, std.sort.asc(u16)); + count.* = nmarks; + } + return total; +} + +const test_paths = [_][]const u8{ + "src/layout.zig", "src/locations.zig", "src/Output.zig", "src/hunks.zig", + "src/pardes.zig", "src/pdf.zig", "src/look.zig", "src/syntax.zig", + "src/body_layer.zig", "build.zig", "src/ninep/ctl.zig", "docs/helix-keys.md", + "notes/helix-keys.md", "src/gui/Post.zig", "cmd/tool/ui_review.py", +}; + +fn topFor(q: []const u8) []const u8 { + var best: ?[]const u8 = null; + var best_score: i32 = std.math.minInt(i32); + for (test_paths) |path| { + var low: [256]u8 = undefined; + const s = match(q, path, std.ascii.lowerString(&low, path), baseOf(path), null, null, null) orelse continue; + if (s > best_score or (s == best_score and path.len < best.?.len)) { + best = path; + best_score = s; + } + } + return best orelse ""; +} + +test "Names ranks real paths as the pick prototype did" { + try std.testing.expectEqualStrings("src/layout.zig", topFor("layout")); + try std.testing.expectEqualStrings("src/Output.zig", topFor("out")); + try std.testing.expectEqualStrings("src/pardes.zig", topFor("prz")); + try std.testing.expectEqualStrings("src/body_layer.zig", topFor("bl")); + try std.testing.expectEqualStrings("src/ninep/ctl.zig", topFor("ctl ninep")); + try std.testing.expectEqualStrings("docs/helix-keys.md", topFor("helkey")); + try std.testing.expectEqualStrings("src/gui/Post.zig", topFor("gui/po")); + try std.testing.expectEqualStrings("src/Output.zig", topFor("Out")); +} diff --git a/src/Output.zig b/src/Output.zig index 9a11b2fc..1e62b04a 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -35,6 +35,9 @@ pub const Origin = union(enum) { unsaved, /// A directory's entries (Dir.zig), the pane named for it. dir, + /// A query pane's +Preview (Query.zig): a file's text shown, not yet + /// its pane; Enter promotes it to one where it stands. + preview, }; pub const max_arg = dump.max_origin_arg; @@ -259,6 +262,7 @@ pub fn traits(o: Origin) Traits { .errors => .{ .name = config.errors_buffer, .doc = true }, .pdf_links => .{ .name = config.pdf_links_buffer, .steps = true, .locations = true }, .unsaved => .{ .name = config.unsaved_buffer, .doc = true }, + .preview => .{ .name = config.preview_buffer, .doc = true }, // Named for its directory, not a `+` name in it. .dir => .{ .name = "", .doc = true }, .cmd => |b| builtins.registry.outputTraits(b) orelse unreachable, @@ -324,6 +328,7 @@ pub fn word(o: Origin) []const u8 { .pdf_links => config.pdf_links_buffer, .unsaved => config.unsaved_buffer, .dir => dir_word, + .preview => config.preview_buffer, }; } @@ -337,6 +342,7 @@ pub fn fromWord(w: []const u8) ?Origin { if (std.mem.eql(u8, w, config.pdf_links_buffer)) return .pdf_links; if (std.mem.eql(u8, w, config.unsaved_buffer)) return .unsaved; if (std.mem.eql(u8, w, dir_word)) return .dir; + if (std.mem.eql(u8, w, config.preview_buffer)) return .preview; if (std.meta.stringToEnum(Builtin, w)) |b| if (builtins.registry.outputTraits(b) != null) return .{ .cmd = b }; if (std.meta.stringToEnum(lsp.Kind, w)) |k| return .{ .query = k }; @@ -399,7 +405,7 @@ fn sortResults(arena: std.mem.Allocator, from: Origin, content: []u8, anchor: ?u => {}, else => return anchor, }, - .errors, .pdf_links, .unsaved, .dir => return anchor, + .errors, .pdf_links, .unsaved, .dir, .preview => return anchor, } if (content.len == 0) return anchor; const path_only = std.meta.eql(from, Origin{ .cmd = .Find }); diff --git a/src/Places.zig b/src/Places.zig index 435a138a..cff7c22e 100644 --- a/src/Places.zig +++ b/src/Places.zig @@ -207,7 +207,8 @@ pub fn search(set: *Places, p: *Pardes, pane: *Pane, provenance: Provenance, fro set.revision = f.revision +% 1; // `fill` starts it over for the text as it is set.seek = seek; set.seek_moves = moves; - set.fill(p, pane, frame_bytes, frame_steps); + // The keystroke's share: the view; the rest a frame's slice a tick. + set.fill(p, pane, 0, frame_steps); } /// A list's places in this text, as it gives them (sorted here), in place @@ -589,7 +590,7 @@ pub fn step(set: *Places, p: *Pardes, pane: *Pane, forward: bool, count: u32, ad /// Whether n and N in this pane are these places' to step: a list's or a /// query's always; a search's while it is what the register says (an `s`, /// a `/` elsewhere or `"a` since makes them helix's register search again). -pub fn answersN(set: *const Places, p: *Pardes, pane: *const Pane) bool { +pub fn answersN(set: *const Places, p: *Pardes, pane: *Pane) bool { if (!set.shows(pane) and !set.started) return false; if (set.provenance != .search) return p.register == 0; const name = if (p.register != 0) p.register else p.registers.last_search; @@ -634,10 +635,11 @@ pub fn forget(set: *Places, gpa: std.mem.Allocator) void { set.snap = &.{}; } -/// Where the query began: the primary selection's end when it was -/// remembered, else now. -pub fn origin(set: *const Places, pane: *const Pane) usize { - if (set.snap.len > 0) return @max(set.snap[set.snap_pri].anchor, set.snap[set.snap_pri].head); +/// Where the query began: the primary selection's start when it was +/// remembered, else now; a place there counts (helix's `/` from the +/// cursor). +pub fn origin(set: *const Places, pane: *Pane) usize { + if (set.snap.len > 0) return @min(set.snap[set.snap_pri].anchor, set.snap[set.snap_pri].head); const f = pane.file orelse return 0; const r = pane.body.primaryRange(f.content, 0); return @min(r.anchor, r.head); @@ -847,3 +849,28 @@ test "places: a big file costs a keystroke its view, the ticks find the rest, an if (std.c.getenv("PLACES_TIMES") != null) std.debug.print("places: first key {d} us, {d} ticks, an edit {d} us (the text's own splice {d} us)\n", .{ first_ns / 1000, ticks, edit_ns / 1000, text_ns / 1000 }); } + +test "zz stress analysis cost" { + const path = "/home/goblin/00-projects/0x4200.cafe/pardes-s-converge/.scratch/stress/src/layout.zig"; + if (std.c.getenv("PLACES_TIMES") == null) return error.SkipZigTest; + const io = std.testing.io; + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, std.testing.allocator, .limited(4 << 20)); + defer std.testing.allocator.free(bytes); + const syntax = @import("syntax.zig"); + syntax.start(std.testing.allocator); + defer syntax.stop(); + const tp = nowNs(); + const tree = syntax.parseTree(path, bytes); + const tq = nowNs(); + if (tree) |t| syntax.freeTree(t); + std.debug.print("parse alone {d} us\n", .{(tq - tp) / 1000}); + const t0 = nowNs(); + const d = try syntax.contextDeclarations(std.testing.allocator, path, bytes); + const t1 = nowNs(); + std.testing.allocator.free(d); + const a = try syntax.analyzeSource(std.testing.allocator, path, bytes, true, true); + const t2 = nowNs(); + std.testing.allocator.free(a.declarations); + std.testing.allocator.free(a.colors); + std.debug.print("decls {d} us ({d}), analysis with colours {d} us\n", .{ (t1 - t0) / 1000, d.len, (t2 - t1) / 1000 }); +} diff --git a/src/Query.zig b/src/Query.zig new file mode 100644 index 00000000..fbce95b2 --- /dev/null +++ b/src/Query.zig @@ -0,0 +1,2155 @@ +//! The query pane: the one pane search is. A +Search attached under the +//! pane that asked (its owner, layout.zig "Attached panes"), born at a +//! fixed height, whose body's line 1 is the query, editable text, and +//! whose rows below are made live from a source, read-only while live. +//! Line 1's first word names the source: `/pat` the owner's text (smart- +//! case regex), `Find pat` the files under its directory, `Grep pat` the +//! lines of those files, `Recent pat`, `Panes pat`, `Symbols pat` (the +//! owner's declarations), `All pat` (every open pane's text), and the +//! language server's `Refs`, `Def`, `Impl`, `Diagnostics`. Names are +//! matched fuzzy (Names.zig), text by regex. Editing the word changes +//! the source. +//! +//! The rows look like a Callstack's: the hit line with the match tinted +//! under a gutter line number, under the declaration it is in (when the +//! owner's parse exists: never made here on the loop), under its file +//! (Grep) or under `@pN name (count)` (All). They are addresses, all text: +//! B3 on one looks, B2 on line 1 runs it again. Wherever a row points into +//! an open pane's text, that pane's places (Places.zig) show the set: +//! tints, rail ticks, the current one selected. A row pointing at a file +//! no pane shows is shown in the +Preview attached under this pane; Enter +//! promotes the preview to the file's pane where it stands. +//! +//! Nothing moves while you type: the pane never closes, resizes or +//! rewrites line 1 on its own; zero hits is a state (`0` in the tag). +//! Enter lands on the current hit and freezes the rows into ordinary text; +//! Esc while typing puts every view back and closes the pane (or brings a +//! reused pane's frozen rows back); Del closes it. One per owner, reused +//! (SearchPane reuse|new). +const Query = @This(); + +const std = @import("std"); +const pardes = @import("pardes.zig"); +const panes = @import("panes.zig"); +const config = @import("config.zig"); +const edit = @import("edit.zig"); +const exec = @import("exec.zig"); +const layout = @import("layout.zig"); +const locations = @import("locations.zig"); +const look = @import("look.zig"); +const modal = @import("modal.zig"); +const normal = @import("normal.zig"); +const syntax = @import("syntax.zig"); +const tagline = @import("tagline.zig"); +const filesystem = @import("fs.zig"); +const colors = @import("colors.zig"); +const memory = @import("memory.zig"); +const Names = @import("Names.zig"); +const Places = @import("Places.zig"); +const Surface = @import("surface.zig").Surface; +const Pardes = pardes.Pardes; +const Pane = panes.Pane; +const File = panes.File; +const Output = panes.Output; +const Key = pardes.Key; +const hit = pardes.hit; + +pub const Source = enum { text, find, grep, recent, panes, symbols, all, refs, defs, impls, diagnostics }; + +/// Line 1's words, each the source it names. `/` is vim's spelling, no +/// space after it; the others take one. +pub const words = [_]struct { word: []const u8, source: Source }{ + .{ .word = "Find", .source = .find }, + .{ .word = "Grep", .source = .grep }, + .{ .word = "Recent", .source = .recent }, + .{ .word = "Panes", .source = .panes }, + .{ .word = "Symbols", .source = .symbols }, + .{ .word = "All", .source = .all }, + .{ .word = "Refs", .source = .refs }, + .{ .word = "Def", .source = .defs }, + .{ .word = "Impl", .source = .impls }, + .{ .word = "Diagnostics", .source = .diagnostics }, +}; + +/// What a line 1 asks: its source and what follows its word. Null when it +/// starts with no word this knows (the user rewrote it): the rows say so. +pub fn parse(line: []const u8) ?struct { source: Source, pat: []const u8 } { + if (line.len > 0 and line[0] == '/') return .{ .source = .text, .pat = line[1..] }; + for (words) |w| { + if (std.mem.startsWith(u8, line, w.word) and (line.len == w.word.len or line[w.word.len] == ' ')) + return .{ .source = w.source, .pat = std.mem.trim(u8, line[w.word.len..], " \t") }; + } + return null; +} + +/// The word line 1 starts with for `source`, as typed after it. +pub fn wordOf(source: Source) []const u8 { + if (source == .text) return "/"; + for (words) |w| if (w.source == source) return w.word; + unreachable; +} + +/// A source whose rows can point at files no pane shows: its group is +/// made with a +Preview from the start, so nothing moves later. +fn previews(source: Source) bool { + return switch (source) { + .find, .grep, .recent, .refs, .defs, .impls, .diagnostics => true, + .text, .panes, .symbols, .all => false, + }; +} + +/// The most rows of hits a frozen list keeps: the rest are counted, and +/// said in a row. +pub const max_rows = 2000; +/// While typed, the rows are a window of this many around the current +/// place: the pane shows a few, and a row is two allocations a refill. +pub const live_rows = 100; + +/// One row's model, row `i + 1` of the pane (line 1 is the query): a hit, +/// a header (a declaration, a file, a pane) or a note. Where a row points +/// is in its locations.Row (path, at); a hit in an open pane's text also +/// knows its places there, `hit` and the `n` of them on its line. +pub const Item = struct { + kind: enum { hit, header, note }, + /// The pane whose text it is in (by serial), 0 when it is a file's. + serial: u32 = 0, + hit: usize = 0, + n: usize = 0, + /// A Panes row's pane, a Symbols row's line: Names.Cand.ref. + ref: u32 = 0, +}; + +/// A line a Grep found: its path and code in `found_bytes`. +pub const Found = struct { path: u32, path_len: u16, line: u32, col: u32, end: u32, code: u32, code_len: u32 }; + +/// The pane it answers for, by serial. +owner: u32, +/// Line 1 as the rows were last made for (gpa). +asked: []u8 = &.{}, +source: Source = .text, +/// Enter answered it: its rows are ordinary text from here, nothing remade. +frozen: bool = false, +items: std.ArrayList(Item) = .empty, +/// The current item, which Enter lands on and the places show. +current: ?usize = null, +/// The tag's `k/N`: how many places or names the rows are of, and where +/// the current one is among them (1-based; 0, none); `more` while counting. +total: usize = 0, +k: usize = 0, +more: bool = false, +/// What the rows were made of: the places' or names' generation and the +/// owner's text, so that a frame with nothing new makes nothing. +made_gen: u64 = std.math.maxInt(u64), +made_rev: u32 = 0, +/// The owner's revision seen last tick: rows follow an edit of the owner +/// once it has stood a frame (the rows refresh on idle frames). +seen_rev: u32 = 0, +/// The body cursor's row as last seen: B1, j or k on a row makes it current. +seen_row: i32 = 0, +/// The places a `/`'s rows are a window of: [lo, hi) of its owner's hits. +window: struct { lo: usize = 0, hi: usize = 0 } = .{}, +/// Ticks the rows waited while the places are still being found: they are +/// made every third, the frame's time going to the finding. +waited: u8 = 0, +names: Names = .{}, +/// A Grep's lines, found a slice a frame (Query.grepSlice). +found: std.ArrayList(Found) = .empty, +found_bytes: std.ArrayList(u8) = .empty, +grep_next: usize = 0, +grep_gen: u32 = 0, +/// The language server's rows for Refs, Def, Impl, Diagnostics, as it gave +/// them (`path:line:col text`, gpa), filtered by what follows the word. +lsp_rows: []u8 = &.{}, +/// The +Preview under this pane, by serial; 0, none. +preview: u32 = 0, +/// A reused pane's frozen rows when a new query began in it: Esc brings +/// them back. +saved: ?Saved = null, + +pub const Saved = struct { + content: []u8, + rows: []locations.Row, + asked: []u8, + source: Source, + items: []Item, + current: ?usize, + total: usize, + k: usize, +}; + +pub fn deinit(q: *Query, gpa: std.mem.Allocator) void { + gpa.free(q.asked); + q.items.deinit(gpa); + q.names.deinit(gpa); + q.found.deinit(gpa); + q.found_bytes.deinit(gpa); + gpa.free(q.lsp_rows); + if (q.saved) |s| freeSaved(gpa, s); + q.* = undefined; +} + +fn freeSaved(gpa: std.mem.Allocator, s: Saved) void { + gpa.free(s.content); + locations.freeRows(gpa, s.rows); + gpa.free(s.asked); + gpa.free(s.items); +} + +/// The query pane `pane` is, if it is one. +pub fn of(pane: *Pane) ?*Query { + return pane.query; +} + +/// The owner's query pane (attached to it, or left where it was by +/// SearchPane new): the one a later search from it reuses. +pub fn ofOwner(p: *Pardes, owner_serial: u32) ?usize { + var found: ?usize = null; + for (p.panes, 0..) |slot, i| { + const pane = slot orelse continue; + const q = pane.query orelse continue; + if (q.owner != owner_serial) continue; + // the attached one first: an unattached one is a kept result + if (pane.attached_to == owner_serial) return i; + found = found orelse i; + } + return found; +} + +fn lineOne(content: []const u8) []const u8 { + return content[0 .. std.mem.indexOfScalar(u8, content, '\n') orelse content.len]; +} + +// ---- opening ---- + +/// A search from pane `from`: its owner's query pane, made under the owner +/// (with a +Preview when `source` can need one) or reused, line 1 the +/// source's word and `arg`. With `focus` the keyboard goes to line 1's end +/// in insert mode, as to a prompt; without (`*`), it stays where it is. +pub fn open(p: *Pardes, from: usize, source: Source, arg: []const u8, focus: bool) void { + const asker = p.panes[from] orelse return; + // Asked from a query pane (`/` in it, its own SPC f g): its own line 1; + // from a +Preview, its query pane's. + var owner_id = from; + if (asker.query) |q| owner_id = p.paneBySerial(q.owner) orelse from else if (isPreview(p, asker)) |qid| { + owner_id = p.paneBySerial(p.panes[qid].?.query.?.owner) orelse from; + } + const owner = p.panes[owner_id] orelse return; + if (asker.query != null and arg.len == 0 and asker.query.?.source == source and !asker.query.?.frozen) { + // Back to typing the query it has. + if (focus) toLineOne(p, from); + return; + } + const line = std.mem.concat(p.scratch.allocator(), u8, &.{ wordOf(source), if (source == .text) "" else " ", arg }) catch return; + var id: usize = undefined; + const existing = ofOwner(p, owner.serial); + if (existing != null and (p.settings.search_pane == .reuse or existing.? == from)) { + id = existing.?; + const rp = p.panes[id].?; + const q = rp.query.?; + // Its frozen rows, kept for an Esc to bring back. + if (q.frozen and q.saved == null) q.saved = save(p, rp, q) catch null; + q.frozen = false; + const f = &rp.file.?; + const new = std.mem.concat(p.gpa, u8, &.{ line, "\n" }) catch return; + File.setContent(p, f, new); + q.reset(p); + if (rp.collapsed) layout.toggleCollapse(p, id); + } else { + if (existing) |old| { + // SearchPane new: the last one stays where it is, a result of + // its own; its places are the new one's to feed. + p.panes[old].?.attached_to = null; + } + id = create(p, owner_id, line, source) orelse return; + } + // Every view as the search found it, for Esc to put back. + owner.places.remember(p, owner); + // Before the first key: a names source lists every candidate at once. + produce(p, id, false); + // What a 9P exec reads back: the pane it filled (ninep/ctl.zig). + p.fs.refilled = p.panes[id].?.serial; + if (focus) toLineOne(p, id) else p.active = from; +} + +/// A new query pane under pane `owner_id`, `rows` of the owner's rows (the +/// SearchRows setting), its +Preview under it when `source` can need one. +fn create(p: *Pardes, owner_id: usize, line: []const u8, source: Source) ?usize { + const owner = p.panes[owner_id] orelse return null; + const free = p.freeSlot() orelse { + p.reportError(owner_id, "search", error.NoPaneSlots); + return null; + }; + const dir = if (p.exec_header) p.sessionDir() else Pardes.paneDir(owner); + const content = std.mem.concat(p.gpa, u8, &.{ line, "\n" }) catch return null; + const np = Output.open(p, free, dir, .search, "", content) catch |err| { + p.gpa.free(content); + p.reportError(owner_id, "search", err); + return null; + }; + const q = p.gpa.create(Query) catch { + p.reportError(owner_id, "search", error.OutOfMemory); + return null; + }; + q.* = .{ .owner = owner.serial }; + np.query = q; + const body: u16 = 1 + p.settings.search_rows; + const tag = @max(pardes.BOX_H, np.tag_rows); + const with_preview = previews(source); + // The preview, made right after, takes its own rows from the owner. + const want = tag + body; + if (p.settings.search_place == .column) { + // The finder column (phase 6): until it exists, under the owner. + if (!layout.attach(p, owner_id, free, want)) exec.placeNew(p, owner_id, owner_id, free, .doc); + } else if (!layout.attach(p, owner_id, free, want)) { + // An owner too short to give a query pane its rows: placed as any + // new pane is, the one place a search moves another pane. + exec.placeNew(p, owner_id, owner_id, free, .doc); + } + if (with_preview) _ = makePreview(p, free); + return free; +} + +/// The keyboard to the end of line 1 of query pane `id`, in insert mode. +pub fn toLineOne(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + tagline.exitHeader(p); + p.active = id; + if (layout.findPane(p, id)) |at| p.setActiveColumn(at.col); + rp.focus = .body; + const t = &rp.body; + if (t.mode == .insert) edit.exitInsert(p, t); + t.cur_row = 0; + t.cur_col = @intCast(lineOne(rp.file.?.content).len); + t.vsel.active = false; + t.nsel = 0; + t.cur_pinned = true; + rp.query.?.seen_row = 0; + edit.enterInsert(p, t, .line_end, 1); + showCurrent(rp); +} + +/// The rows' state for a new question: nothing found yet. +fn reset(q: *Query, p: *Pardes) void { + q.items.clearRetainingCapacity(); + q.current = null; + q.total = 0; + q.k = 0; + q.more = false; + q.made_gen = std.math.maxInt(u64); + p.gpa.free(q.asked); + q.asked = &.{}; +} + +fn save(p: *Pardes, rp: *Pane, q: *Query) !Saved { + const f = &rp.file.?; + const content = try p.gpa.dupe(u8, f.content); + errdefer p.gpa.free(content); + const rows = try p.gpa.alloc(locations.Row, f.location_rows.len); + var made: usize = 0; + errdefer { + for (rows[0..made]) |r| { + p.gpa.free(r.path); + p.gpa.free(r.colors); + } + p.gpa.free(rows); + } + for (f.location_rows, 0..) |r, i| { + rows[i] = r; + rows[i].path = try p.gpa.dupe(u8, r.path); + rows[i].colors = p.gpa.dupe(u8, r.colors) catch |err| { + p.gpa.free(rows[i].path); + return err; + }; + made += 1; + } + const asked = try p.gpa.dupe(u8, q.asked); + errdefer p.gpa.free(asked); + return .{ .content = content, .rows = rows, .asked = asked, .source = q.source, .items = try p.gpa.dupe(Item, q.items.items), .current = q.current, .total = q.total, .k = q.k }; +} + +// ---- making the rows ---- + +/// After every step: each live query pane whose line 1 changed, or whose +/// source has something new, has its rows made again. A walk takes a slice +/// on a tick. Nothing here is synchronous with an edit of the owner: its +/// places shift (Places.shift) and the rows follow once it stands a frame. +pub fn produceAll(p: *Pardes, tick: bool) void { + for (p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + if (pane.query == null) continue; + produce(p, id, tick); + } +} + +/// The frames a query pane still owes (a walk, scoring): nextWake's. +pub fn busy(p: *const Pardes) bool { + for (p.panes) |slot| { + const pane = slot orelse continue; + const q = pane.query orelse continue; + if (q.frozen) continue; + if (q.names.busy() or (q.source == .grep and q.grep_next < q.names.cands.items.len) or q.made_rev != q.seen_rev) return true; + } + return false; +} + +fn produce(p: *Pardes, id: usize, tick: bool) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + const f = if (rp.file) |*file| file else return; + const line = lineOne(f.content); + const changed = !std.mem.eql(u8, line, q.asked); + if (q.frozen and !changed) return; + if (q.frozen) { + // Line 1 of a frozen pane edited: it is a live query again. + if (q.saved) |s| freeSaved(p.gpa, s); + q.saved = null; + q.frozen = false; + } + const owner_id = p.paneBySerial(q.owner); + const asked = parse(line); + if (changed) { + const was = q.source; + const new_asked = p.gpa.dupe(u8, line) catch return; + p.gpa.free(q.asked); + q.asked = new_asked; + q.made_gen = std.math.maxInt(u64); + if (asked) |a| { + if (a.source != was or q.names.cands.items.len == 0) startSource(p, id, q, a.source, owner_id); + q.source = a.source; + } + // The places this fed are another question's now. + if (asked == null or asked.?.source != .text) clearPlaces(p, q, rp.serial, owner_id, asked); + } + const a = asked orelse return noteRows(p, id, " line 1 asks: /text, Find, Grep, Recent, Panes, Symbols, All, Refs, Def, Impl or Diagnostics, then what to find\n"); + // A row clicked or stepped onto (B1, j, k): current, and shown. + if (rp.body.cur_row != q.seen_row) { + q.seen_row = rp.body.cur_row; + if (rp.body.cur_row > 0 and rp.body.cur_row <= q.items.items.len) { + const i: usize = @intCast(rp.body.cur_row - 1); + if (q.items.items[i].kind == .hit) setCurrent(p, id, i, true); + } + } + switch (a.source) { + .text => { + const oid = owner_id orelse return noteRows(p, id, " the pane this searched is gone: Del, or / in another\n"); + const owner = p.panes[oid].?; + const of_ = owner.file orelse return noteRows(p, id, " a terminal's text is not searched here yet: / in a file\n"); + const set = &owner.places; + if (changed) { + if (a.pat.len == 0) { + if (set.from == rp.serial) set.clear(p.gpa); + set.restore(p, owner); + } else set.search(p, owner, .typed, rp.serial, a.pat, false, set.origin(owner), p.active == id); + } + // The owner edited: its places shifted at once; the rows follow + // once its text has stood a frame. + if (!changed and of_.revision != q.made_rev) { + if (!tick or of_.revision != q.seen_rev) { + q.seen_rev = of_.revision; + return; + } + } + q.seen_rev = of_.revision; + const gen: u64 = (@as(u64, set.hits_gen) << 32) | of_.revision; + if (gen == q.made_gen and !changed) return showPlacesCurrent(p, id); + if (a.pat.len > 0 and set.from != rp.serial) return; + if (!changed and !set.complete() and q.made_gen != std.math.maxInt(u64) and q.waited < 2) { + q.waited += 1; + return showPlacesCurrent(p, id); + } + q.waited = 0; + q.made_gen = gen; + q.made_rev = of_.revision; + makeTextRows(p, id, oid, false) catch |err| p.reportError(id, "search", err); + }, + .all => { + if (changed) for (p.panes) |slot| { + const tp = slot orelse continue; + if (!searchable(tp)) continue; + if (a.pat.len == 0) { + if (tp.places.from == rp.serial) tp.places.clear(p.gpa); + continue; + } + tp.places.search(p, tp, .list, rp.serial, a.pat, false, null, false); + }; + var gen: u64 = 0; + for (p.panes) |slot| if (slot) |tp| if (tp.places.from == rp.serial) { + gen +%= tp.places.hits_gen +% (@as(u64, tp.serial) << 20); + }; + if (gen == q.made_gen and !changed) return; + if (!changed and !tick) return; + q.made_gen = gen; + makeAllRows(p, id) catch |err| p.reportError(id, "search", err); + }, + .find, .recent, .panes, .symbols => { + if (tick) q.names.walkSlice(p.gpa); + if (changed) q.names.typed(p.gpa, a.pat) else if (q.names.busy()) q.names.rescore(p.gpa); + if (q.names.gen == q.made_gen and !changed) return; + q.made_gen = q.names.gen; + makeNameRows(p, id, a.pat) catch |err| p.reportError(id, "search", err); + }, + .grep => { + if (changed) { + q.found.clearRetainingCapacity(); + q.found_bytes.clearRetainingCapacity(); + q.grep_next = 0; + q.grep_gen +%= 1; + } + if (a.pat.len == 0) { + if (changed) makeGrepRows(p, id) catch {}; + return; + } + if (tick or changed) { + q.names.walkSlice(p.gpa); + grepSlice(p, q, rp, a.pat); + } + const gen: u64 = (@as(u64, q.grep_gen) << 32) | q.found.items.len; + if (gen == q.made_gen and !changed and !(q.grep_next >= q.names.cands.items.len and q.more)) return; + q.made_gen = gen; + makeGrepRows(p, id) catch |err| p.reportError(id, "search", err); + if (changed or q.current == null) feedGrepPlaces(p, q, rp.serial, a.pat); + }, + .refs, .defs, .impls, .diagnostics => { + if (changed and q.lsp_rows.len == 0) { + // Typed, not answered: asked of the language server at the + // owner's cursor; its answer fills these rows (fillList). + // An answer opening the pane is no typing. + if (p.active != id) return; + if (owner_id) |oid| p.lspRequest(oid, switch (a.source) { + .refs => .references, + .defs => .definition, + .impls => .implementation, + else => .diagnostics, + }, ""); + return noteRows(p, id, " asked of the language server...\n"); + } + if (!changed) return; + makeListRows(p, id, a.pat) catch |err| p.reportError(id, "search", err); + }, + } +} + +/// Whether pane `tp`'s text is one All searches: a file's or a list's, +/// not a query pane's nor a preview's. +fn searchable(tp: *const Pane) bool { + const f = tp.file orelse return false; + if (tp.query != null) return false; + if (f.output) |o| if (o.from == .preview) return false; + return true; +} + +/// A source begun: its candidates gathered (names), its walk started. +fn startSource(p: *Pardes, id: usize, q: *Query, source: Source, owner_id: ?usize) void { + const rp = p.panes[id].?; + q.names.reset(); + q.found.clearRetainingCapacity(); + q.found_bytes.clearRetainingCapacity(); + q.grep_next = 0; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const gpa = p.gpa; + switch (source) { + .find, .grep => q.names.startWalk(gpa, dir) catch |err| p.reportError(id, "search", err), + .recent => { + var out: std.Io.Writer.Allocating = .init(gpa); + defer out.deinit(); + Output.recentText(p, &out.writer, true) catch {}; + var lines = std.mem.splitScalar(u8, out.written(), '\n'); + while (lines.next()) |ln| { + if (ln.len == 0) continue; + const rel = Names.relative(ln, dir); + const path_end = std.mem.indexOfAny(u8, rel, ": ") orelse rel.len; + q.names.add(gpa, rel, 0, path_end, Names.baseOf(rel[0..path_end]), 0) catch break; + } + }, + .panes => for (p.panes) |slot| { + const other = slot orelse continue; + if (other == rp or other.query != null) continue; + var buf: [4096 + 32]u8 = undefined; + const what: []const u8 = if (other.file) |f| f.path else if (other.command) |c| c else other.cwdSlice(); + const row = std.fmt.bufPrint(&buf, config.pane_addr ++ "{d} {s}", .{ other.serial, Names.relative(what, dir) }) catch continue; + const key_at = std.mem.indexOfScalar(u8, row, ' ').? + 1; + const ln = row[0 .. std.mem.indexOfAny(u8, row, "\r\n") orelse row.len]; + q.names.add(gpa, ln, key_at, ln.len -| key_at, Names.baseOf(ln[@min(key_at, ln.len)..]), other.serial) catch break; + }, + .symbols => { + const oid = owner_id orelse return; + const owner = p.panes[oid].?; + const f = if (owner.file) |*file| file else return; + const decls = ownerDecls(p, f, true) orelse return; + for (decls) |d| { + const header = f.content[d.start_byte..@min(d.header_end_byte, f.content.len)]; + const first = std.mem.trim(u8, header[0 .. std.mem.indexOfScalar(u8, header, '\n') orelse header.len], " \t\r"); + var buf: [256 + 16]u8 = undefined; + const row = std.fmt.bufPrint(&buf, "{d: >6} {s}", .{ d.start_line + 1, first[0..@min(first.len, 240)] }) catch continue; + q.names.add(gpa, row, 8, row.len - 8, 0, @intCast(d.start_line + 1)) catch break; + } + }, + else => {}, + } +} + +/// The owner's declarations, from a parse that already exists: its sticky +/// headers' (TreeContext) at this revision, or the locations cache's. None +/// is made here, on the loop, unless `small` and the text is small: a +/// tree-sitter parse of a 1.2 MB file is seconds in a Debug build. +/// ponytail: no grouping for a big file until the disk engine's worker +/// parses it (phase 4). +fn ownerDecls(p: *Pardes, f: *File.State, small: bool) ?[]const syntax.ContextDeclaration { + if (f.context_revision) |rev| if (rev == f.revision and f.context_declarations.len > 0) return f.context_declarations; + const cache = &p.locations_cache; + for (cache.entries[0..cache.len]) |entry| { + if (entry.declarations_ready and std.mem.eql(u8, entry.path, f.path) and std.mem.eql(u8, entry.source, f.content)) return entry.analysis.declarations; + } + if (!small or f.content.len > small_parse_bytes or !syntax.supportsPath(f.path)) return null; + var got = p.locations_cache.get(p.tree_sitter_gpa, f.path, f.content, true, false) catch return null; + if (got.owned) { + got.deinit(p.tree_sitter_gpa); + return null; + } + return got.analysis.declarations; +} + +/// A text this small is parsed on the loop for its declarations when a +/// Symbols query asks (about 40 ms in a Debug build). +const small_parse_bytes = 64 << 10; + +/// The rows as `note` says, and nothing else: no hits. +fn noteRows(p: *Pardes, id: usize, note: []const u8) void { + const rp = p.panes[id].?; + const q = rp.query.?; + q.items.clearRetainingCapacity(); + q.items.append(p.gpa, .{ .kind = .note }) catch return; + q.current = null; + q.total = 0; + q.k = 0; + q.more = false; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + writeRow(p, &out, &rows, note[0 .. note.len - 1], .{ .kind = .context, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0 }) catch return; + setRows(p, rp, &out, &rows); +} + +/// One row: its text and its metadata, the path copied. +fn writeRow(p: *Pardes, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), text: []const u8, meta: locations.Row) !void { + try out.appendSlice(p.gpa, text); + try out.append(p.gpa, '\n'); + var m = meta; + m.path = try p.gpa.dupe(u8, meta.path); + errdefer p.gpa.free(m.path); + // Coloured whole (zeros where nothing coloured it): the pane's syntax + // pass then parses no fragment of it, per refill. + const code = text[@min(meta.code_start, text.len)..]; + m.colors = if (meta.colors.len >= code.len) try p.gpa.dupe(u8, meta.colors[0..code.len]) else blk: { + const c = try p.gpa.alloc(u8, code.len); + @memset(c, 0); + @memcpy(c[0..meta.colors.len], meta.colors); + break :blk c; + }; + rows.append(p.gpa, m) catch |err| { + p.gpa.free(m.path); + p.gpa.free(m.colors); + return err; + }; +} + +/// The rows made into the pane: line 1 as it is (the user's), then `out`, +/// with `rows` their metadata. The keyboard's place is left where it was. +fn setRows(p: *Pardes, rp: *Pane, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row)) void { + defer locations.freeRowList(p.gpa, rows); + const f = &rp.file.?; + const line = lineOne(f.content); + const content = std.mem.concat(p.gpa, u8, &.{ line, "\n", out.items }) catch return; + const meta = p.gpa.alloc(locations.Row, rows.items.len + 1) catch { + p.gpa.free(content); + return; + }; + meta[0] = .{ .kind = .context, .path = p.gpa.dupe(u8, "") catch &.{}, .at = .{}, .location_end = 0, .code_start = 0 }; + @memcpy(meta[1..], rows.items); + rows.clearRetainingCapacity(); + const kept_row = rp.body.cur_row; + const kept_col = rp.body.cur_col; + if (std.mem.eql(u8, content, f.content)) { + // Same text: the metadata alone, no undo step, no syntax pass. + p.gpa.free(content); + if (locations.equalRows(f.location_rows, meta)) { + locations.freeRows(p.gpa, meta); + } else { + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = meta; + f.syntax_dirty = true; + } + } else { + File.setContent(p, f, content); + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = meta; + f.saved_revision = f.revision; + } + gpa_free_pager(p, f); + // The cursor stays where it was typing; on a row that went, the last. + const last: i32 = @intCast(File.nlines(p.gpa, f) -| 1); + rp.body.cur_row = @min(kept_row, last); + rp.body.cur_col = if (rp.body.cur_row == kept_row) kept_col else 0; + if (rp.body.cur_row == 0 and rp.body.cur_col > line.len) rp.body.cur_col = @intCast(line.len); + rp.query.?.seen_row = rp.body.cur_row; +} + +fn gpa_free_pager(p: *Pardes, f: *File.State) void { + if (f.pager_spans.len == 0) return; + p.gpa.free(f.pager_spans); + f.pager_spans = &.{}; +} + +/// The gutter a file of `nlines` lines numbers its rows in: two spaces, +/// the number right-aligned, two spaces. +fn gutterWidth(nlines: usize) usize { + var digits: usize = 1; + var n = nlines; + while (n >= 10) : (n /= 10) digits += 1; + return 2 + @max(3, digits) + 2; +} + +fn writeHitRow(p: *Pardes, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), width: usize, path: []const u8, line_no: usize, whole: []const u8, col: usize, end: usize, shade: []const u8) !void { + var lead: usize = 0; + while (lead < whole.len and (whole[lead] == ' ' or whole[lead] == '\t')) lead += 1; + const code = std.mem.trimEnd(u8, whole[lead..], "\r"); + var buf: [4096 + 32]u8 = undefined; + var num: [24]u8 = undefined; + const number = std.fmt.bufPrint(&num, "{d}", .{line_no}) catch ""; + const pad = width -| 2 -| number.len; + if (pad + number.len + 2 + code.len > buf.len) return; + @memset(buf[0..pad], ' '); + @memcpy(buf[pad..][0..number.len], number); + @memcpy(buf[pad + number.len ..][0..2], " "); + @memcpy(buf[pad + number.len + 2 ..][0..code.len], code); + const text = buf[0 .. pad + number.len + 2 + code.len]; + const gutter = pad + number.len + 2; + try writeRow(p, out, rows, text, .{ + .kind = .match, + .source_column = lead, + .path = @constCast(path), + .at = .{ .line = line_no, .col = col + 1, .end_line = line_no, .end_col = @max(col + 1, end) }, + .location_end = gutter, + .code_start = gutter, + .colors = @constCast(if (shade.len >= lead) shade[lead..][0..@min(shade.len - lead, code.len)] else &.{}), + }); +} + +/// The path a row of pane `tp`'s text says: its file's, or `@pN` for a +/// text that is no file (a list, a scratch). +fn addressOf(arena: std.mem.Allocator, tp: *const Pane) []const u8 { + const f = tp.file orelse return ""; + if (f.output == null and !std.mem.startsWith(u8, std.fs.path.basename(f.path), "+")) return f.path; + return std.fmt.allocPrint(arena, config.pane_addr ++ "{d}", .{tp.serial}) catch ""; +} + +/// Rows from pane `tp`'s places: one a line with any (two on a line are +/// one row: everywhere's bug), the declaration they are in over them when +/// its parse exists, from place `from` on, `budget` rows at most. The +/// place it stopped before. +fn writePlacesRows(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), tp: *Pane, from: usize, budget: *usize) !usize { + const f = &tp.file.?; + const set = &tp.places; + const hits = set.hits.items; + const index = try File.lineIndex(p.gpa, f); + const width = gutterWidth(index.len); + const path = addressOf(p.scratch.allocator(), tp); + const decls = ownerDecls(p, f, false) orelse &.{}; + var decl_now: ?usize = null; + var i: usize = @min(from, hits.len); + // the line of the first, found in the index + var line: usize = if (i < hits.len) blk: { + var lo: usize = 0; + var hi = index.len; + while (lo < hi) { + const mid = lo + (hi - lo) / 2; + if (index[mid] <= hits[i].start) lo = mid + 1 else hi = mid; + } + break :blk lo -| 1; + } else 0; + // a window begins at a line's first place + while (i > 0 and hits[i - 1].start >= index[line]) i -= 1; + while (i < hits.len) { + while (line + 1 < index.len and index[line + 1] <= hits[i].start) line += 1; + // the places on this line + var n: usize = 1; + const ls = index[line]; + const le = if (line + 1 < index.len) index[line + 1] - 1 else f.content.len; + while (i + n < hits.len and hits[i + n].start <= le) n += 1; + if (budget.* == 0) { + q.more = true; + break; + } + budget.* -= 1; + // the innermost declaration around it, its first line once + var inner: ?usize = null; + for (decls, 0..) |d, di| { + if (d.start_line > line) break; + if (d.end_line < line) continue; + inner = di; + } + if (inner != decl_now) { + decl_now = inner; + if (inner) |di| if (decls[di].start_line != line) { + const head_ls = index[decls[di].start_line]; + const head_le = if (decls[di].start_line + 1 < index.len) index[decls[di].start_line + 1] - 1 else f.content.len; + const head = std.mem.trim(u8, f.content[head_ls..head_le], " \t\r"); + var hb: [600]u8 = undefined; + const text = std.fmt.bufPrint(&hb, " {s}", .{head[0..@min(head.len, 560)]}) catch ""; + try q.items.append(p.gpa, .{ .kind = .header, .serial = tp.serial }); + try writeRow(p, out, rows, text, .{ .kind = .context, .declaration = true, .path = @constCast(path), .at = .{ .line = decls[di].start_line + 1 }, .location_end = 0, .code_start = 0 }); + }; + } + const shade: []const u8 = if (f.highlights.len > 0 and ls >= f.highlight_start and le <= f.highlight_start + f.highlights.len) f.highlights[ls - f.highlight_start .. le - f.highlight_start] else &.{}; + try q.items.append(p.gpa, .{ .kind = .hit, .serial = tp.serial, .hit = i, .n = n }); + try writeHitRow(p, out, rows, width, path, line + 1, f.content[ls..le], hits[i].start - ls, @min(hits[i].end, le) - ls, shade); + i += n; + } + return i; +} + +/// The rows of a `/`: while typed, a window of `live_rows` around the +/// current place; `full` (frozen), the whole list up to `max_rows`. +fn makeTextRows(p: *Pardes, id: usize, oid: usize, full: bool) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + const owner = p.panes[oid].?; + const set = &owner.places; + q.items.clearRetainingCapacity(); + q.more = false; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var budget: usize = if (full) max_rows else live_rows; + const at = set.current orelse (if (set.seek) |s| Places.firstFrom(set.hits.items, s) else 0); + const from = if (full) 0 else at -| live_rows / 2; + q.window = .{ .lo = from, .hi = from }; + if (set.started and set.from == rp.serial) { + if (from > 0) { + var hb: [64]u8 = undefined; + try noteRow(p, q, &out, &rows, std.fmt.bufPrint(&hb, " ... {d} places before these", .{from}) catch " ..."); + } + q.window.hi = try writePlacesRows(p, q, &out, &rows, owner, from, &budget); + q.window.lo = @min(from, q.window.hi); + } + if (q.more) try noteRow(p, q, &out, &rows, " ... and more: the count says how many"); + setRows(p, rp, &out, &rows); + showPlacesCurrent(p, id); +} + +fn noteRow(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.ArrayList(locations.Row), text: []const u8) !void { + try q.items.append(p.gpa, .{ .kind = .note }); + try writeRow(p, out, rows, text, .{ .kind = .context, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0 }); +} + +/// The current row from the places of the pane its rows are in, the count +/// with them: for `/`, the owner's. +fn showPlacesCurrent(p: *Pardes, id: usize) void { + const rp = p.panes[id].?; + const q = rp.query.?; + const owner = p.panes[p.paneBySerial(q.owner) orelse return].?; + const set = &owner.places; + q.total = if (set.from == rp.serial) set.hits.items.len else 0; + q.more = q.more or (set.from == rp.serial and !set.complete()); + q.k = if (set.current) |c| c + 1 else 0; + if (set.from != rp.serial) q.k = 0; + q.current = null; + // By line, not by the rows' place indices: the rows may lag the places + // a tick while they are still being found. + if (set.current) |c| if (c < set.hits.items.len) { + const at = lineOfOffset(p, &owner.file.?, set.hits.items[c].start) + 1; + const rows = rp.file.?.location_rows; + for (q.items.items, 0..) |it, i| { + if (it.kind != .hit or it.serial != owner.serial or i + 1 >= rows.len) continue; + if (rows[i + 1].at.line == at) { + q.current = i; + break; + } + } + }; + // Stepped out of the window the live rows are: made again around it. + if (q.current == null and set.current != null and !q.frozen and set.from == rp.serial) q.made_gen = std.math.maxInt(u64); + showCurrent(rp); +} + +/// Every open pane's rows for All, grouped under `@pN name (count)` in +/// the order of the panes' serials (everywhere's other bug: it went by +/// column). +fn makeAllRows(p: *Pardes, id: usize) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + q.items.clearRetainingCapacity(); + q.more = false; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var order: [pardes.MAX_PANES]usize = undefined; + var n: usize = 0; + for (p.panes, 0..) |slot, i| if (slot) |tp| if (tp.places.from == rp.serial and tp.places.started) { + order[n] = i; + n += 1; + }; + std.mem.sort(usize, order[0..n], p, struct { + fn lt(pp: *Pardes, a: usize, b: usize) bool { + return pp.panes[a].?.serial < pp.panes[b].?.serial; + } + }.lt); + var budget: usize = max_rows; + q.total = 0; + for (order[0..n]) |tid| { + const tp = p.panes[tid].?; + const set = &tp.places; + if (!set.shows(tp) or set.hits.items.len == 0) { + q.more = q.more or !set.complete(); + continue; + } + q.total += set.hits.items.len; + q.more = q.more or !set.complete(); + var hb: [600]u8 = undefined; + const name = if (tp.file) |f| Names.relative(f.path, std.fs.path.dirname(rp.file.?.path) orelse "") else ""; + const head = std.fmt.bufPrint(&hb, config.pane_addr ++ "{d} {s} ({d})", .{ tp.serial, name[0..@min(name.len, 500)], set.hits.items.len }) catch ""; + try q.items.append(p.gpa, .{ .kind = .header, .serial = tp.serial }); + try writeRow(p, &out, &rows, head, .{ .kind = .context, .declaration = true, .path = @constCast(addressOf(p.scratch.allocator(), tp)), .at = .{}, .location_end = 0, .code_start = 0 }); + _ = try writePlacesRows(p, q, &out, &rows, tp, 0, &budget); + } + if (budget == 0) try noteRow(p, q, &out, &rows, " ... and more: the count says how many"); + setRows(p, rp, &out, &rows); + // The current one: the first hit row, until a step moves it. + if (q.current == null or q.current.? >= q.items.items.len) q.current = firstHit(q); + countCurrent(q); + showCurrent(rp); +} + +fn firstHit(q: *const Query) ?usize { + for (q.items.items, 0..) |it, i| if (it.kind == .hit) return i; + return null; +} + +/// `k` from the current row: the hits on the rows before it, and its own. +fn countCurrent(q: *Query) void { + q.k = 0; + const c = q.current orelse return; + for (q.items.items[0..c]) |it| q.k += if (it.kind == .hit) @max(1, it.n) else 0; + q.k += 1; +} + +/// The names the query matches, best first, `Names.max_rows` of them: each +/// a row as its source has it, the matched bytes tinted. +fn makeNameRows(p: *Pardes, id: usize, pat: []const u8) !void { + _ = pat; + const rp = p.panes[id].?; + const q = rp.query.?; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const was_current: ?u32 = if (q.current) |c| (if (c < q.items.items.len) q.items.items[c].ref else null) else null; + _ = was_current; + q.items.clearRetainingCapacity(); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var spans: std.ArrayList(pardes.pager.Span) = .empty; + errdefer spans.deinit(p.gpa); + const chrome = p.bodyChrome(); + const tint: pardes.CellStyle = .{ .fg = .{ .rgb = chrome.search_fg }, .bg = .{ .rgb = chrome.search_bg }, .bold = true }; + const shown = @min(q.names.hits.items.len, Names.max_rows); + var marks: [Names.max_query * 4]u16 = undefined; + const base = lineOne(rp.file.?.content).len + 1; + for (0..shown) |i| { + var nmarks: usize = 0; + const row = q.names.row(i, &marks, &nmarks); + const cand = q.names.cands.items[q.names.hits.items[i].cand]; + const at = base + out.items.len; + // Where it points: a path (Find, Recent), a pane (Panes), a line + // of the owner (Symbols). + var meta: locations.Row = .{ .kind = .match, .path = &.{}, .at = .{}, .location_end = 0, .code_start = 0, .mark_occurrence = false }; + var pathbuf: [4096 + 32]u8 = undefined; + switch (q.source) { + .find => meta.path = @constCast(std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), row }) catch row), + .recent => { + const t = look.parsePathLine(row); + meta.path = @constCast(if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch t.path); + meta.at = t.at; + }, + .panes => meta.path = @constCast(std.fmt.bufPrint(&pathbuf, config.pane_addr ++ "{d}", .{cand.ref}) catch ""), + .symbols => { + const owner = p.panes[p.paneBySerial(q.owner) orelse 0]; + meta.path = @constCast(if (owner) |o| addressOf(p.scratch.allocator(), o) else ""); + meta.at = .{ .line = cand.ref }; + }, + else => {}, + } + try q.items.append(p.gpa, .{ .kind = .hit, .ref = cand.ref }); + try writeRow(p, &out, &rows, row, meta); + var k: usize = 0; + while (k < nmarks) { + var e = k + 1; + while (e < nmarks and marks[e] == marks[e - 1] + 1) e += 1; + try spans.append(p.gpa, .{ .start = @intCast(at + marks[k]), .end = @intCast(at + marks[e - 1] + 1), .style = tint }); + k = e; + } + } + if (q.names.hits.items.len > shown) try noteRow(p, q, &out, &rows, " ... and more: type more of the name"); + setRows(p, rp, &out, &rows); + const f = &rp.file.?; + f.pager_spans = spans.toOwnedSlice(p.gpa) catch &.{}; + q.total = q.names.hits.items.len; + q.more = q.names.busy(); + // The best is current until a step or a click moves it. + q.current = if (shown > 0) 0 else null; + countCurrent(q); + showCurrent(rp); + showTarget(p, id); +} + +/// A slice of a Grep: the files the walk has found so far read and +/// searched, about 4 ms of them a frame, each line holding the pattern +/// (a literal, smart case: a capital makes it exact) kept. +/// ponytail: on the loop, a file a step; the disk engine's worker (phase +/// 4) takes this over. +fn grepSlice(p: *Pardes, q: *Query, rp: *Pane, pat: []const u8) void { + const started = Places.nowNs(); + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const fold = for (pat) |c| { + if (std.ascii.isUpper(c)) break false; + } else true; + var low_buf: [256]u8 = undefined; + const needle = if (fold) std.ascii.lowerString(low_buf[0..@min(pat.len, low_buf.len)], pat[0..@min(pat.len, low_buf.len)]) else pat; + while (q.grep_next < q.names.cands.items.len) { + if (q.found.items.len >= grep_cap) break; + const c = q.names.cands.items[q.grep_next]; + q.grep_next += 1; + const rel = q.names.bytes.items[c.start..][0..c.len]; + var pathbuf: [4096 + 8]u8 = undefined; + const path = std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), rel }) catch continue; + const bytes = blk: { + pardes.turn.yield(); + defer pardes.turn.back(); + break :blk filesystem.read(p, path) catch continue; + }; + defer p.gpa.free(bytes); + if (std.mem.indexOfScalar(u8, bytes[0..@min(bytes.len, 8000)], 0) != null) continue; + var line_no: u32 = 1; + var ls: usize = 0; + while (ls <= bytes.len) { + const le = std.mem.indexOfScalarPos(u8, bytes, ls, '\n') orelse bytes.len; + const ln = bytes[ls..le]; + const at = if (fold) std.ascii.findIgnoreCase(ln, needle) else std.mem.indexOf(u8, ln, needle); + if (at) |col| { + const path_at: u32 = @intCast(q.found_bytes.items.len); + q.found_bytes.appendSlice(p.gpa, rel) catch return; + const code_at: u32 = @intCast(q.found_bytes.items.len); + const code = ln[0..@min(ln.len, 400)]; + q.found_bytes.appendSlice(p.gpa, code) catch return; + q.found.append(p.gpa, .{ .path = path_at, .path_len = @intCast(rel.len), .line = line_no, .col = @intCast(col), .end = @intCast(col + needle.len), .code = code_at, .code_len = @intCast(code.len) }) catch return; + if (q.found.items.len >= grep_cap) break; + } + if (le == bytes.len) break; + ls = le + 1; + line_no += 1; + } + if (started != 0 and Places.nowNs() - started > Places.frame_ns) break; + } +} + +/// A Grep keeps this many lines: the rest wait (the disk engine's `More`). +pub const grep_cap = 2000; + +fn makeGrepRows(p: *Pardes, id: usize) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + q.items.clearRetainingCapacity(); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + var last_path: []const u8 = ""; + var pathbuf: [4096 + 8]u8 = undefined; + for (q.found.items, 0..) |fd, i| { + const rel = q.found_bytes.items[fd.path..][0..fd.path_len]; + const path = std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), rel }) catch continue; + if (!std.mem.eql(u8, rel, last_path)) { + last_path = rel; + try q.items.append(p.gpa, .{ .kind = .header }); + try writeRow(p, &out, &rows, rel, .{ .kind = .context, .path = @constCast(path), .at = .{}, .location_end = 0, .code_start = 0 }); + } + const code = q.found_bytes.items[fd.code..][0..fd.code_len]; + try q.items.append(p.gpa, .{ .kind = .hit, .hit = i, .n = 1 }); + try writeHitRow(p, &out, &rows, 9, path, fd.line, code, fd.col, fd.end, &.{}); + } + const walking = q.names.walking() or q.grep_next < q.names.cands.items.len; + if (q.found.items.len >= grep_cap) try noteRow(p, q, &out, &rows, " ... stopped at 2000 lines: type more of it"); + setRows(p, rp, &out, &rows); + q.total = q.found.items.len; + q.more = walking and q.found.items.len < grep_cap; + if (q.current == null or q.current.? >= q.items.items.len) q.current = firstHit(q); + countCurrent(q); + showCurrent(rp); +} + +/// A Grep's hits in each open file are that pane's places: its tints, +/// ticks and n/N. +fn feedGrepPlaces(p: *Pardes, q: *Query, serial: u32, pat: []const u8) void { + _ = q; + for (p.panes) |slot| { + const tp = slot orelse continue; + const f = tp.file orelse continue; + if (f.output != null or tp.query != null) continue; + tp.places.search(p, tp, .list, serial, pat, true, null, false); + } +} + +/// The language server's answer for an owner's Refs, Def, Impl or +/// Diagnostics, into its query pane (made or reused) with line 1 the word: +/// what follows the word filters the rows; the places in the owner's text +/// are its places. `rows` are `path:line:col text`, as the server's +/// answer is written (lsp_client). +pub fn fillList(p: *Pardes, owner_id: usize, source: Source, rows: []const u8) void { + const owner = p.panes[owner_id] orelse return; + var id = ofOwner(p, owner.serial); + if (id == null or p.panes[id.?].?.query.?.source != source) { + open(p, owner_id, source, "", false); + id = ofOwner(p, owner.serial); + } + const qid = id orelse return; + const rp = p.panes[qid].?; + const q = rp.query.?; + const copy = p.gpa.dupe(u8, rows) catch return; + p.gpa.free(q.lsp_rows); + q.lsp_rows = copy; + const line = lineOne(rp.file.?.content); + const a = parse(line) orelse return; + makeListRows(p, qid, a.pat) catch |err| p.reportError(qid, "search", err); + toLineOne(p, qid); +} + +fn makeListRows(p: *Pardes, id: usize, pat: []const u8) !void { + const rp = p.panes[id].?; + const q = rp.query.?; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + q.items.clearRetainingCapacity(); + var out: std.ArrayList(u8) = .empty; + defer out.deinit(p.gpa); + var rows: std.ArrayList(locations.Row) = .empty; + const owner_id = p.paneBySerial(q.owner); + const owner_path: []const u8 = if (owner_id) |oid| (if (p.panes[oid].?.file) |f| f.path else "") else ""; + var feed: std.ArrayList(Places.Hit) = .empty; + defer feed.deinit(p.gpa); + // In order: by path, then place, as a list of places reads. + var sorted: std.ArrayList([]const u8) = .empty; + defer sorted.deinit(p.gpa); + var split = std.mem.splitScalar(u8, q.lsp_rows, '\n'); + while (split.next()) |ln| if (ln.len > 0) try sorted.append(p.gpa, ln); + std.mem.sort([]const u8, sorted.items, {}, struct { + fn lt(_: void, a: []const u8, b: []const u8) bool { + const ta = look.parsePathLine(a); + const tb = look.parsePathLine(b); + const order = std.mem.order(u8, ta.path, tb.path); + if (order != .eq) return order == .lt; + if (ta.at.line != tb.at.line) return ta.at.line < tb.at.line; + return ta.at.col < tb.at.col; + } + }.lt); + var last_path: []const u8 = ""; + var pathbuf: [4096 + 8]u8 = undefined; + var n: usize = 0; + for (sorted.items) |ln| { + if (ln.len == 0) continue; + if (pat.len > 0 and std.ascii.findIgnoreCase(ln, pat) == null) continue; + const t = look.parsePathLine(ln); + if (t.at.line == 0) continue; + const path = if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch continue; + if (!std.mem.eql(u8, t.path, last_path)) { + last_path = t.path; + try q.items.append(p.gpa, .{ .kind = .header }); + try writeRow(p, &out, &rows, Names.relative(t.path, dir), .{ .kind = .context, .path = @constCast(path), .at = .{}, .location_end = 0, .code_start = 0 }); + } + const rest = std.mem.trimStart(u8, ln[@min(t.end, ln.len)..], " \t:"); + const col0 = t.at.col -| 1; + try q.items.append(p.gpa, .{ .kind = .hit, .n = 1 }); + // The row's text: the line in the owner when it is the owner's, + // else as the server said it. + var code: []const u8 = rest; + var col = col0; + var end = if (t.at.end_col > 0 and t.at.end_line == t.at.line) t.at.end_col else col0 + 1; + if (owner_id) |oid| if (std.mem.eql(u8, path, owner_path)) { + const owner_f = &p.panes[oid].?.file.?; + if (t.at.line <= File.nlines(p.gpa, owner_f)) { + const ls = File.lineStart(p.gpa, owner_f, t.at.line - 1); + const nx = File.lineStart(p.gpa, owner_f, t.at.line); + const le = if (nx > ls and owner_f.content[nx - 1] == '\n') nx - 1 else nx; + code = owner_f.content[ls..le]; + col = @min(col0, code.len); + end = @min(@max(end, col + 1), code.len); + feed.append(p.gpa, .{ .start = ls + col, .end = ls + @max(end, col + 1) }) catch {}; + } + } else { + col = 0; + end = 0; + }; + try writeHitRow(p, &out, &rows, 9, path, t.at.line, code, col, end, &.{}); + n += 1; + } + if (n == 0) try noteRow(p, q, &out, &rows, " nothing"); + setRows(p, rp, &out, &rows); + q.total = n; + q.more = false; + q.current = firstHit(q); + if (owner_id) |oid| { + const owner = p.panes[oid].?; + // Current: the first place after where it was asked (the answer + // may come after the cursor moved), shown in the owner. + const asked_at: usize = if (p.lsp_last) |last| (if (last.serial == owner.serial) last.offset else owner.places.origin(owner)) else owner.places.origin(owner); + owner.places.feed(p, owner, rp.serial, feed.items, null); + const hits = owner.places.hits.items; + var next: ?usize = null; + for (hits, 0..) |h, i| if (h.start > asked_at) { + next = i; + break; + }; + if (next == null and hits.len > 0) next = 0; + if (next) |hi| { + owner.places.goTo(owner, hi, false); + for (q.items.items, 0..) |it, i| if (it.kind == .hit and i + 1 < rp.file.?.location_rows.len) { + const meta = rp.file.?.location_rows[i + 1]; + if (!std.mem.eql(u8, meta.path, owner_path)) continue; + const ls = File.lineStart(p.gpa, &owner.file.?, meta.at.line -| 1); + if (ls + meta.at.col -| 1 == hits[hi].start) { + q.current = i; + break; + } + }; + } + } + countCurrent(q); + showCurrent(rp); +} + +/// The places query `serial` fed in panes other than the owner, cleared +/// (a new source or pattern makes its own); the owner's too when the new +/// line is no `/`. +fn clearPlaces(p: *Pardes, q: *Query, serial: u32, owner_id: ?usize, asked: anytype) void { + _ = q; + _ = asked; + for (p.panes, 0..) |slot, i| { + const tp = slot orelse continue; + if (tp.places.from != serial) continue; + if (owner_id != null and owner_id.? == i) tp.places.restore(p, tp); + tp.places.clear(p.gpa); + } +} + +// ---- the current row ---- + +/// The current row drawn as the visited row is (a line selection), while +/// the keyboard is on line 1 or elsewhere; on the rows, the cursor itself +/// is current. Scrolled into view, line 1 kept when it can be. +fn showCurrent(rp: *Pane) void { + const q = rp.query orelse return; + if (rp.body.cur_row != 0 and rp.focus == .body) return; + const c = q.current orelse { + rp.body.msel.active = false; + return; + }; + const r: i32 = @intCast(c + 1); + rp.body.msel = .{ .active = true, .r0 = r, .r1 = r }; + const off = rp.scroll(); + const shown = off + @as(i32, rp.rows) - 1; + if (r > shown) rp.scrollBy(r - shown) else if (r < off) rp.scrollBy(r - off); +} + +/// The line (0-based) of byte `at` of `f`'s text. +fn lineOfOffset(p: *Pardes, f: *File.State, at: usize) usize { + const index = File.lineIndex(p.gpa, f) catch return 0; + var lo: usize = 0; + var hi = index.len; + while (lo < hi) { + const mid = lo + (hi - lo) / 2; + if (index[mid] <= at) lo = mid + 1 else hi = mid; + } + return lo -| 1; +} + +/// The first of pane `tp`'s places on line `line` (1-based), if any. +fn placeOnLine(p: *Pardes, tp: *Pane, line: usize) ?usize { + const f = &tp.file.?; + if (line == 0 or line > File.nlines(p.gpa, f)) return null; + const ls = File.lineStart(p.gpa, f, line - 1); + const next = File.lineStart(p.gpa, f, line); + const hits = tp.places.hits.items; + const i = Places.firstFrom(hits, ls); + if (i < hits.len and (hits[i].start < next or (next == ls))) return i; + return null; +} + +/// Item `i` current, and shown where it points (`show`). +fn setCurrent(p: *Pardes, id: usize, i: usize, show: bool) void { + const rp = p.panes[id].?; + const q = rp.query.?; + q.current = i; + const it = q.items.items[i]; + const rows = rp.file.?.location_rows; + if (it.serial != 0 and i + 1 < rows.len) if (p.paneBySerial(it.serial)) |tid| { + const tp = p.panes[tid].?; + if (placeOnLine(p, tp, rows[i + 1].at.line)) |hi| { + tp.places.current = hi; + tp.places.gen +%= 1; + if (tp.places.from == rp.serial and tp.serial == q.owner) q.k = hi + 1 else countCurrent(q); + } else countCurrent(q); + } else countCurrent(q) else countCurrent(q); + showCurrent(rp); + if (show) showTarget(p, id); +} + +/// Step the current row `delta` hits on, round the end silently: Ctrl-n, +/// Ctrl-p, Down and Up on line 1, n and N in the pane. +pub fn step(p: *Pardes, id: usize, delta: i32) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + // A `/`: the owner's places step, the rows follow them. + if (q.source == .text) if (p.paneBySerial(q.owner)) |oid| { + const owner = p.panes[oid].?; + if (owner.places.from == rp.serial) { + const keyboard = p.active; + owner.places.step(p, owner, delta > 0, 1, false); + p.active = keyboard; + showPlacesCurrent(p, id); + return; + } + }; + const items = q.items.items; + if (items.len == 0) return; + var i: usize = q.current orelse (if (delta > 0) items.len - 1 else 0); + for (0..items.len) |_| { + if (delta > 0) i = if (i + 1 >= items.len) 0 else i + 1 else i = if (i == 0) items.len - 1 else i - 1; + if (items[i].kind == .hit) break; + } else return; + setCurrent(p, id, i, true); +} + +/// Where the current row points, shown with the keyboard left where it is: +/// a place in an open pane's text selected there (its places' current), +/// in view; a file an open pane shows, its line there; any other file in +/// the +Preview under this pane. Every pane it moves remembers its view +/// first, for Esc. +fn showTarget(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + const c = q.current orelse return; + const f = &rp.file.?; + if (c + 1 >= f.location_rows.len) return; + const it = q.items.items[c]; + const meta = f.location_rows[c + 1]; + const keyboard = p.active; + defer p.active = keyboard; + if (it.serial != 0) { + const tid = p.paneBySerial(it.serial) orelse return; + const tp = p.panes[tid].?; + if (tp.places.snap.len == 0) tp.places.remember(p, tp); + if (placeOnLine(p, tp, meta.at.line)) |hi| tp.places.goTo(tp, hi, false); + return; + } + if (q.source == .symbols) { + const oid = p.paneBySerial(q.owner) orelse return; + look.focusPaneLine(p, oid, .{ .line = it.ref }, .center); + return; + } + if (q.source == .panes) return; + if (meta.path.len == 0) return; + // A file open in a pane: shown there. + for (p.panes, 0..) |slot, i| { + const tp = slot orelse continue; + const tf = tp.file orelse continue; + if (tf.output != null or !std.mem.eql(u8, tf.path, meta.path)) continue; + if (tp.places.snap.len == 0) tp.places.remember(p, tp); + const line0 = meta.at.line -| 1; + const visible = line0 >= tf.scroll and line0 < tf.scroll + tp.rows; + if (meta.at.line > 0) look.focusPaneLine(p, i, meta.at, if (visible) .keep else .center); + return; + } + displayPreview(p, id, meta.path, meta.at); +} + +// ---- the +Preview ---- + +/// The +Preview under query pane `qid`, if it has one: by serial. +fn previewOf(p: *Pardes, qid: usize) ?usize { + const q = p.panes[qid].?.query.?; + if (q.preview == 0) return null; + return p.paneBySerial(q.preview) orelse { + q.preview = 0; + return null; + }; +} + +/// Whether `pane` is a query pane's +Preview: that query pane's slot. +pub fn isPreview(p: *Pardes, pane: *const Pane) ?usize { + const f = pane.file orelse return null; + const o = f.output orelse return null; + if (o.from != .preview) return null; + for (p.panes, 0..) |slot, i| if (slot) |qp| if (qp.query) |q| if (q.preview == pane.serial) return i; + return null; +} + +/// A +Preview made under query pane `qid`, out of its rows alone. +fn makePreview(p: *Pardes, qid: usize) ?usize { + const rp = p.panes[qid].?; + const free = p.freeSlot() orelse return null; + const dir = std.fs.path.dirname(rp.file.?.path) orelse "/"; + const content = p.gpa.dupe(u8, "") catch return null; + const np = Output.open(p, free, dir, .preview, "", content) catch { + p.gpa.free(content); + return null; + }; + layout.compute(p); + const rows = @max(pardes.BOX_H, np.tag_rows) + p.settings.search_rows; + // Out of the group's root, the text that asked: the query pane keeps + // the rows it was typed into with (made later, for a reused pane). + if (!layout.attachFrom(p, qid, free, rows, layout.groupRoot(p, qid))) { + p.removePane(free, qid) catch {}; + return null; + } + rp.query.?.preview = np.serial; + return free; +} + +/// File `path` at `at` in the +Preview: its text read (once a file: a +/// file open in a pane would be shown there instead), the place centred +/// and selected. Made when the pane has none and its owner has the rows. +fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void { + const id = previewOf(p, qid) orelse makePreview(p, qid) orelse return; + const pane = p.panes[id].?; + const f = &pane.file.?; + if (!std.mem.eql(u8, f.path, path)) { + if (exec.kindOf(path)) |kind| if (kind != .file) return; + const bytes = blk: { + pardes.turn.yield(); + defer pardes.turn.back(); + break :blk filesystem.read(p, path) catch return; + }; + if (std.mem.indexOfScalar(u8, bytes[0..@min(bytes.len, 8000)], 0) != null) { + p.gpa.free(bytes); + return; + } + const owned_path = p.gpa.dupe(u8, path) catch { + p.gpa.free(bytes); + return; + }; + p.gpa.free(f.path); + f.path = owned_path; + File.setContent(p, f, bytes); + f.saved_revision = f.revision; + f.scroll = 0; + f.syntax_dirty = true; + pane.hscroll = 0; + p.sync(); + } + look.clearNavigationSelection(p, pane); + if (at.line == 0 or at.line > File.nlines(p.gpa, f)) { + f.scroll = 0; + f.syntax_dirty = true; + pane.body.cur_row = 0; + pane.body.cur_col = 0; + pane.body.cur_pinned = true; + return; + } + look.focusPaneLine(p, id, at, .center); + if (at.end_line == 0 or at.end_col <= at.col) + pane.body.msel = .{ .active = true, .r0 = @intCast(at.line - 1), .r1 = @intCast(at.line - 1) }; +} + +/// The +Preview becomes the file's pane where it stands: same slot, same +/// serial, same rect, its scroll and selection as the preview left them. +/// It is a file pane from here: an empty undo history, the Recent entry, +/// the watch, a file's tag; and a pane of its own, no longer attached (it +/// stays when its query pane goes). +fn promote(p: *Pardes, qid: usize, id: usize) void { + const pane = p.panes[id] orelse return; + const f = &pane.file.?; + f.output = null; + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = null; + f.saved_revision = f.revision; + f.saved_hash = null; + f.saved_len = null; + f.disk_gone = false; + f.syntax_dirty = true; + pane.attached_to = null; + if (Pardes.recentKeeps(f.path)) p.recent.opened(p.recentGpa(), f.path); + if (filesystem.localPath(f.path) != null) p.emit(.{ .watch = .{ .pane = @intCast(id), .on = true } }); + pardes.ctlfs.events.noteLog(p, .rename, pane); + p.panes[qid].?.query.?.preview = 0; +} + +// ---- Enter, Esc ---- + +/// Enter on line 1 (or on a row, `row`): the keyboard to the current hit +/// in its pane (the +Preview promoted to the file's pane when it shows +/// it), a `/` into the register, and the rows frozen into ordinary text. +pub fn land(p: *Pardes, id: usize, row: ?usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + if (row) |r| if (r < q.items.items.len and q.items.items[r].kind == .hit) setCurrent(p, id, r, true); + const t = &rp.body; + if (t.mode == .insert) edit.exitInsert(p, t); + freeze(p, id); + const owner_id = p.paneBySerial(q.owner); + if (q.source == .text) { + const oid = owner_id orelse return; + const owner = p.panes[oid].?; + const set = &owner.places; + // The whole list now, once, every place found: a result from here. + if (set.started and set.from == rp.serial) { + set.fill(p, owner, std.math.maxInt(usize), @import("regexp.zig").Regex.budget); + makeTextRows(p, id, oid, true) catch {}; + } + if (set.started and set.from == rp.serial) { + if (set.literal) { + var escaped: std.ArrayList(u8) = .empty; + normal.appendSearchLiteral(&escaped, p.scratch.allocator(), set.pattern) catch {}; + p.registers.put(p.gpa, '/', escaped.items, 0, 1, true); + } else p.registers.put(p.gpa, '/', set.pattern, 0, 1, true); + p.registers.last_search = '/'; + set.provenance = .search; + } + p.jump_force = true; + p.active = oid; + return; + } + const c = q.current orelse { + if (owner_id) |oid| p.active = oid; + return; + }; + const f = &rp.file.?; + const it = q.items.items[c]; + const meta = f.location_rows[c + 1]; + p.jump_force = true; + if (it.serial != 0) { + if (p.paneBySerial(it.serial)) |tid| { + p.active = tid; + if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col); + } + return; + } + switch (q.source) { + .symbols => if (owner_id) |oid| { + look.focusPaneLine(p, oid, .{ .line = it.ref }, .center); + return; + }, + .panes => if (p.paneBySerial(it.ref)) |tid| { + p.active = tid; + if (layout.findPane(p, tid)) |at| p.setActiveColumn(at.col); + return; + }, + else => {}, + } + // The preview shows it: promoted where it stands. + if (previewOf(p, id)) |pid| if (std.mem.eql(u8, p.panes[pid].?.file.?.path, meta.path)) { + promote(p, id, pid); + p.active = pid; + if (q.source == .grep) { + const a = parse(q.asked) orelse return; + const pp = p.panes[pid].?; + pp.places.search(p, pp, .list, rp.serial, a.pat, true, null, false); + } + return; + }; + var buf: [4096 + 64]u8 = undefined; + const address = if (meta.at.line > 0) + std.fmt.bufPrint(&buf, "{s}:{d}:{d}", .{ meta.path, meta.at.line, meta.at.col }) catch meta.path + else + meta.path; + look.lookAt(p, id, address); +} + +/// The rows frozen: ordinary text from here, Save works on them; the +/// places they fed stay, while the pane lives; every view stays where the +/// search left it; the preview, of no more use, goes. +fn freeze(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + q.frozen = true; + if (q.saved) |s| freeSaved(p.gpa, s); + q.saved = null; + for (p.panes) |slot| if (slot) |tp| if (tp.places.from == rp.serial or tp.serial == q.owner) tp.places.forget(p.gpa); + if (previewOf(p, id)) |pid| { + const pv = p.panes[pid].?; + // A preview showing the current row is promoted by `land`: one + // showing another file goes. + _ = pv; + } +} + +/// Esc on line 1 while typing: every view as the search found it, the +/// places it fed gone, and the pane closed (nothing was answered); a +/// reused pane's frozen rows come back instead, and their places. +pub fn cancel(p: *Pardes, id: usize) void { + const rp = p.panes[id] orelse return; + const q = rp.query orelse return; + const t = &rp.body; + if (t.mode == .insert) edit.exitInsert(p, t); + const owner_id = p.paneBySerial(q.owner); + for (p.panes) |slot| if (slot) |tp| { + if (tp.places.from != rp.serial and tp.serial != q.owner) continue; + tp.places.restore(p, tp); + tp.places.forget(p.gpa); + if (tp.places.from == rp.serial) tp.places.clear(p.gpa); + }; + if (q.saved) |s| { + q.saved = null; + // A preview made for the query Esc took back has no use: its rows + // go to the text whose rows they were. + if (previewOf(p, id)) |pid| { + p.panes[pid].?.attached_to = null; + p.removePane(pid, owner_id) catch {}; + q.preview = 0; + } + const f = &rp.file.?; + File.setContent(p, f, s.content); + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = s.rows; + p.gpa.free(q.asked); + q.asked = s.asked; + q.source = s.source; + q.items.clearRetainingCapacity(); + q.items.appendSlice(p.gpa, s.items) catch {}; + p.gpa.free(s.items); + q.current = s.current; + q.total = s.total; + q.k = s.k; + q.frozen = true; + rp.body.cur_row = 0; + rp.body.cur_col = 0; + showCurrent(rp); + // Its places again, as Enter left them. + if (q.source == .text) if (owner_id) |oid| if (parse(q.asked)) |a| { + const owner = p.panes[oid].?; + owner.places.search(p, owner, .search, rp.serial, a.pat, false, null, false); + }; + if (owner_id) |oid| p.active = oid; + return; + } + if (owner_id) |oid| { + p.removePane(id, oid) catch {}; + p.active = oid; + if (layout.findPane(p, oid)) |at| p.setActiveColumn(at.col); + } else p.removePane(id, null) catch {}; +} + +/// The pane going (Del, its owner's Del): the places it fed go with it. +pub fn release(p: *Pardes, pane: *Pane) void { + for (p.panes) |slot| if (slot) |tp| if (tp.places.from == pane.serial) { + tp.places.forget(p.gpa); + tp.places.clear(p.gpa); + }; +} + +// ---- keys, the mouse, edits ---- + +/// The keys a query pane answers itself, before its text has them. On +/// line 1, typing: Enter lands, Esc cancels, Ctrl-n, Ctrl-p, Down and Up +/// step the current row. In normal mode: Enter on a hit row lands on it, +/// n and N step. Anything else is ordinary text editing (line 1) or is +/// refused (the rows, while live: clampEdit). Tab stays the exec chord. +pub fn key(p: *Pardes, id: usize, k: Key) bool { + const rp = p.panes[id] orelse return false; + const q = rp.query orelse return false; + if (rp.focus != .body) return false; + const t = &rp.body; + if (q.frozen) return false; + if (t.mode == .normal) { + if (t.normal.prefix != .none or k.ctrl or k.alt or t.normal.count != 0) return false; + if (k.cp == 'n' or k.cp == 'N') { + step(p, id, if (k.cp == 'n') 1 else -1); + return true; + } + if (hit(k, config.look_key) and t.cur_row > 0) { + land(p, id, @intCast(t.cur_row - 1)); + return true; + } + return false; + } + if (t.cur_row != 0 or t.mode != .insert or t.reg_wait) return false; + if (hit(k, config.escape)) { + cancel(p, id); + return true; + } + if (k.cp == Key.enter and !k.ctrl and !k.alt and !k.shift) { + land(p, id, null); + return true; + } + const down = (k.cp == Key.down and !k.ctrl and !k.alt) or (k.ctrl and !k.alt and k.cp == 'n'); + const up = (k.cp == Key.up and !k.ctrl and !k.alt) or (k.ctrl and !k.alt and k.cp == 'p'); + if (down or up) { + step(p, id, if (down) 1 else -1); + return true; + } + return false; +} + +/// An edit of a live query pane's text (edit.setEditTextSpan): inside line +/// 1, as typed; one from line 1 into the rows, cut at line 1's end (and a +/// newline put in it, a blank); one wholly in the rows refused, as a tag's +/// prefix refuses one. Null: refused. Lifted from queryline. +pub fn clampEdit(p: *Pardes, t: *panes.Text, old: []const u8, new: []u8) ?[]u8 { + const end = std.mem.indexOfScalar(u8, old, '\n') orelse old.len; + const span = File.spanOf(old, new); + const old_to = old.len - span.tail; + const put = new[span.head .. new.len - span.tail]; + const rows_same = old_to <= end and std.mem.indexOfScalar(u8, put, '\n') == null; + if (rows_same) return new; + if (span.head > end or (span.head == end and old_to > end and put.len == 0 and end < old.len)) { + t.refused = true; + if (t.pane()) |pane| if (p.paneIdOf(pane)) |id| + p.setMessage(id, "the rows are line 1's: edit the query (Enter keeps them as text)"); + return null; + } + // From inside line 1 into the rows: what it put in, flat, and what is + // left of line 1 after it; the rows as they were. + const kept = if (old_to < end) old[old_to..end] else ""; + const out = std.mem.concat(p.gpa, u8, &.{ old[0..span.head], put, kept, old[end..] }) catch return null; + for (out[0 .. span.head + put.len + kept.len]) |*c| if (c.* == '\n') { + c.* = ' '; + }; + return out; +} + +/// B3 on a row's gutter (its line number): the row's address, as a +Diff +/// line's prefix is its place (exec.operandAt). Null off a gutter. +pub fn rowAddress(pane: *const Pane, row: usize, col: usize, buf: []u8) ?[]const u8 { + if (pane.query == null) return null; + const f = pane.file orelse return null; + if (row == 0 or row >= f.location_rows.len) return null; + const meta = f.location_rows[row]; + if (meta.kind != .match or meta.path.len == 0 or meta.location_end == 0 or col >= meta.location_end) return null; + if (meta.at.line == 0) return std.fmt.bufPrint(buf, "{s}", .{meta.path}) catch null; + return std.fmt.bufPrint(buf, "{s}:{d}:{d}", .{ meta.path, meta.at.line, meta.at.col }) catch null; +} + +/// The tag's start for a query pane: its name and where it is, `+Search +/// 3/27`, `0` with nothing found, `+` while it still counts. +pub fn tagPrefix(q: *const Query, arena: std.mem.Allocator, path: []const u8) ![]const u8 { + const name = std.fs.path.basename(path); + const more = if (q.more and !q.frozen) "+" else ""; + if (q.total == 0) return std.fmt.allocPrint(arena, "{s} 0{s}", .{ name, more }); + if (q.k == 0) return std.fmt.allocPrint(arena, "{s} {d}{s}", .{ name, q.total, more }); + return std.fmt.allocPrint(arena, "{s} {d}/{d}{s}", .{ name, q.k, q.total, more }); +} + +/// The other places on a hit row's line tinted, from the pane its rows are +/// in (the first is the row's own mark, Output.decorateRow): the current +/// one strongest, as in that pane's text. +pub fn paint(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: u16) void { + const q = pane.query orelse return; + const f = if (pane.file) |*file| file else return; + const th = p.theme(); + const strong = p.chromeTheme().search_bg; + const quiet = colors.mix(th.bg orelse th.tag_bg, strong); + var vr: i32 = 0; + var last: i32 = -1; + while (vr < body_h) : (vr += 1) { + const row = pane.wrapAt(vr).line; + if (row == last or row < 1) continue; + last = row; + const i: usize = @intCast(row - 1); + if (i >= q.items.items.len or @as(usize, @intCast(row)) >= f.location_rows.len) continue; + const it = q.items.items[i]; + if (it.kind != .hit or it.serial == 0) continue; + const tid = p.paneBySerial(it.serial) orelse continue; + const tp = p.panes[tid].?; + const set = &tp.places; + if (!set.shows(tp)) continue; + const tf = &tp.file.?; + const meta = f.location_rows[@intCast(row)]; + // Its line's places as they are now, found by the line: the rows + // may be a tick behind the places. + if (meta.at.line == 0 or meta.at.line > File.nlines(p.gpa, tf)) continue; + const ls = File.lineStart(p.gpa, tf, meta.at.line - 1); + const next = File.lineStart(p.gpa, tf, meta.at.line); + const line = modal.lineSlice(f.content, @intCast(row)); + var hi = Places.firstFrom(set.hits.items, ls); + while (hi < set.hits.items.len and set.hits.items[hi].start < next) : (hi += 1) { + const h = set.hits.items[hi]; + if (h.start < ls + meta.source_column) continue; + const a = meta.code_start + (h.start - ls - meta.source_column); + const b = @min(line.len, meta.code_start + (@min(h.end, next) - ls - meta.source_column)); + if (b <= a or a >= line.len) continue; + const current = set.current != null and set.current.? == hi; + File.paintWordSelection(p, s, pane, r, row, @intCast(a), @intCast(b), if (current) strong else quiet); + } + } +} + +// ---- tests ---- + +fn typeKeys(p: *Pardes, text: []const u8) void { + for (text) |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); +} + +fn queryPane(p: *Pardes) ?usize { + for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.query != null) return i; + return null; +} + +test "parse: line 1's first word names the source" { + try std.testing.expectEqual(Source.text, parse("/alpha").?.source); + try std.testing.expectEqualStrings("alpha", parse("/alpha").?.pat); + try std.testing.expectEqual(Source.find, parse("Find lay").?.source); + try std.testing.expectEqualStrings("lay", parse("Find lay").?.pat); + try std.testing.expectEqual(Source.grep, parse("Grep").?.source); + try std.testing.expectEqual(Source.all, parse("All x y").?.source); + try std.testing.expectEqualStrings("x y", parse("All x y").?.pat); + try std.testing.expectEqual(Source.refs, parse("Refs").?.source); + try std.testing.expect(parse("Findx") == null); + try std.testing.expect(parse("grep x") == null); + try std.testing.expect(parse("") == null); +} + +test "a / query: keystroke by keystroke, the owner shows the set, rows from its own rows alone, zero hits a state, Esc puts all back" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha one\nbeta\nalphabet\ngamma alpha\nalpha two\ndelta\n"); + p.newScratchBelow(0); + const below = p.col_panes[0][1]; + p.active = 0; + layout.compute(p); + const before = p.rects; + // cursor on line 3 (row 2) + pane.body.cur_row = 2; + pane.body.cur_col = 0; + typeKeys(p, "/"); + const qid = queryPane(p).?; + const qp = p.panes[qid].?; + try std.testing.expectEqual(@as(?usize, 0), layout.ownerOf(p, qid)); + try std.testing.expectEqual(qid, p.active); + try std.testing.expectEqualDeep(before[below], p.rects[below]); + const born = p.rects[qid]; + try std.testing.expectEqualStrings("/", lineOne(qp.file.?.content)); + // keystroke 1 + typeKeys(p, "a"); + const q = qp.query.?; + try std.testing.expectEqual(Source.text, q.source); + try std.testing.expect(pane.places.started and pane.places.from == qp.serial); + try std.testing.expect(q.total > 0); + try std.testing.expectEqualDeep(born, p.rects[qid]); + // keystroke 2 .. `alph`: four places on four lines (rows), the + // current the first at or after the cursor (line 3's alphabet) + typeKeys(p, "lph"); + try std.testing.expectEqual(@as(usize, 4), q.total); + try std.testing.expectEqual(@as(usize, 2), q.k); + try std.testing.expectEqual(@as(?usize, 1), pane.places.current); + const sel = pane.body.primaryRange(pane.file.?.content, 0); + try std.testing.expectEqual(@as(usize, 15), @min(sel.anchor, sel.head)); + try std.testing.expectEqualDeep(born, p.rects[qid]); + try std.testing.expectEqualDeep(before[below], p.rects[below]); + try std.testing.expectEqual(qid, p.active); + // Ctrl-n steps, the owner follows + p.update(.{ .key = .{ .cp = 'n', .ctrl = true } }); + try std.testing.expectEqual(@as(usize, 3), q.k); + // drawn: rows, tints, ticks + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + try std.testing.expect(p.surface.nrail_ticks > 0); + // zero hits: a state, the pane stays where it was, line 1 as typed + typeKeys(p, "zz"); + try std.testing.expectEqual(@as(usize, 0), q.total); + try std.testing.expect(p.panes[qid] != null); + try std.testing.expectEqualStrings("/alphzz", lineOne(qp.file.?.content)); + try std.testing.expectEqualDeep(born, p.rects[qid]); + const tag = try tagline.pathPrefix(p, p.scratch.allocator(), qp); + try std.testing.expectEqualStrings("+Search 0", tag); + // Esc: the pane gone, its rows back to the owner, the owner as it was + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.panes[qid] == null); + try std.testing.expectEqual(@as(usize, 0), p.active); + layout.compute(p); + try std.testing.expectEqualDeep(before[0], p.rects[0]); + try std.testing.expectEqualDeep(before[below], p.rects[below]); + try std.testing.expect(!pane.places.started); + try std.testing.expectEqual(@as(i32, 2), pane.body.cur_row); +} + +test "a / query: Enter lands and freezes, the register filled, n and N step silently, a later / reuses the pane and Esc brings the frozen rows back" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("alpha one\nbeta\nalphabet\ngamma alpha\nalpha two\ndelta\n"); + typeKeys(p, "/alpha"); + const qid = queryPane(p).?; + const qp = p.panes[qid].?; + const q = qp.query.?; + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(q.frozen); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqualStrings("alpha", p.registers.value('/', 0).?); + try std.testing.expectEqual(Places.Provenance.search, pane.places.provenance); + const frozen = try std.testing.allocator.dupe(u8, qp.file.?.content); + defer std.testing.allocator.free(frozen); + // the rows: one a line (gamma alpha has one), a gutter number each + try std.testing.expect(std.mem.indexOf(u8, frozen, " 1 alpha one\n") != null); + // n and N in the owner step the same set, round the end silently + const logged = p.messages.len; + try std.testing.expectEqual(@as(?usize, 0), pane.places.current); + typeKeys(p, "nnn"); + try std.testing.expectEqual(@as(?usize, 3), pane.places.current); + typeKeys(p, "n"); + try std.testing.expectEqual(@as(?usize, 0), pane.places.current); + try std.testing.expect(pane.places.wrapped); + try std.testing.expectEqual(logged, p.messages.len); + typeKeys(p, "N"); + try std.testing.expectEqual(@as(?usize, 3), pane.places.current); + // a later `/` reuses the pane: line 1 fresh, the rows the new query's + typeKeys(p, "/"); + try std.testing.expectEqual(qid, queryPane(p).?); + try std.testing.expectEqual(qid, p.active); + try std.testing.expect(!q.frozen); + typeKeys(p, "beta"); + try std.testing.expectEqual(@as(usize, 1), q.total); + // Esc: the frozen rows of `/alpha` again, the owner's places with them + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.panes[qid] != null); + try std.testing.expect(q.frozen); + try std.testing.expectEqualStrings(frozen, qp.file.?.content); + try std.testing.expectEqualStrings("alpha", pane.places.pattern); + // Del closes it, its places with it + exec.runBuiltin(p, .Del, qid, "", null); + try std.testing.expect(p.panes[qid] == null); + try std.testing.expect(!pane.places.started); +} + +/// A test's file pane in `tmp`, named `name`, holding `text`. +fn testFileIn(p: *Pardes, tmp: *std.testing.TmpDir, name: []const u8, text: []const u8) !*Pane { + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = text }); + var base_buf: [std.fs.max_path_bytes]u8 = undefined; + const dir = base_buf[0..try tmp.dir.realPath(std.testing.io, &base_buf)]; + const pane = try p.setTestFile(text); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try std.fs.path.join(p.gpa, &.{ dir, name }); + return pane; +} + +fn leader(p: *Pardes, keys: []const u8) void { + p.update(.{ .key = .{ .cp = ' ', .text = " " } }); + typeKeys(p, keys); +} + +fn settle(p: *Pardes) void { + var frames: usize = 0; + while (busy(p) and frames < 2000) : (frames += 1) p.update(.tick); + p.update(.tick); +} + +test "Find: names fuzzy per keystroke, the group born with its +Preview, nothing else moves, Enter promotes the preview in place" { + if (!filesystem.platform_has_fs) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(std.testing.io, "src"); + for ([_][]const u8{ "src/layout.zig", "src/look.zig", "notes.md" }) |name| + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = name, .data = "pub fn split() void {}\nconst x = 1;\n" }); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); + defer p.deinit(); + _ = try testFileIn(p, &tmp, "x.txt", "x\n"); + p.newScratchBelow(0); + const other = p.col_panes[0][1]; + try std.testing.expect(layout.splitColumn(p, other, other, false)); + p.active = 0; + layout.compute(p); + const before = p.rects; + leader(p, "ff"); + const qid = queryPane(p).?; + const q = p.panes[qid].?.query.?; + try std.testing.expectEqual(Source.find, q.source); + try std.testing.expectEqualStrings("Find ", lineOne(p.panes[qid].?.file.?.content)); + // the group: owner, query pane, +Preview, out of the owner's rows alone + const pv = previewOf(p, qid).?; + try std.testing.expectEqual(@as(usize, 0), layout.groupRoot(p, pv)); + try std.testing.expectEqualDeep(before[other], p.rects[other]); + try std.testing.expectEqual(before[0].h, p.rects[0].h + p.rects[qid].h + p.rects[pv].h); + settle(p); + // an empty query lists every name + try std.testing.expectEqual(@as(usize, 4), q.total); + const born = p.rects; + typeKeys(p, "lay"); + settle(p); + try std.testing.expectEqual(@as(usize, 1), q.total); + try std.testing.expectEqualDeep(born[qid], p.rects[qid]); + try std.testing.expectEqualDeep(born[pv], p.rects[pv]); + // the current one in the preview, never by the pointer + try std.testing.expect(std.mem.endsWith(u8, p.panes[pv].?.file.?.path, "src/layout.zig")); + try std.testing.expectEqual(qid, p.active); + const serial = p.panes[pv].?.serial; + const rect = p.rects[pv]; + p.update(.{ .key = .{ .cp = Key.enter } }); + // promoted where it stands: same slot, serial, rect; a file pane now + try std.testing.expectEqual(pv, p.active); + try std.testing.expectEqual(serial, p.panes[pv].?.serial); + try std.testing.expect(p.panes[pv].?.file.?.output == null); + try std.testing.expect(p.panes[pv].?.attached_to == null); + layout.compute(p); + try std.testing.expectEqualDeep(rect, p.rects[pv]); + try std.testing.expect(q.frozen); + try std.testing.expectEqualDeep(before[other], p.rects[other]); +} + +test "Grep: lines of the files under the owner's directory, under their file; All: every pane's, under @pN in serial order, a line once" { + if (!filesystem.platform_has_fs) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "b.zig", .data = "const needle = 1;\nconst hay = 2;\nneedle needle\n" }); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); + defer p.deinit(); + const a = try testFileIn(p, &tmp, "a.txt", "one needle\ntwo\n"); + leader(p, "fg"); + const qid = queryPane(p).?; + const q = p.panes[qid].?.query.?; + typeKeys(p, "needle"); + settle(p); + // a.txt's one, b.zig's three lines + try std.testing.expectEqual(@as(usize, 3), q.total); + const body = p.panes[qid].?.file.?.content; + try std.testing.expect(std.mem.indexOf(u8, body, "\nb.zig\n") != null); + // the open file's hits are its places + try std.testing.expect(a.places.started and a.places.hits.items.len == 1); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.panes[qid] == null); + try std.testing.expect(!a.places.started); + + // All: a second pane, both searched, grouped by serial + p.newScratchBelow(0); + const s = p.active; + const sf = &p.panes[s].?.file.?; + File.setContent(p, sf, try p.gpa.dupe(u8, "needle needle twice\n")); + p.active = 0; + leader(p, "/"); + const aid = queryPane(p).?; + const aq = p.panes[aid].?.query.?; + try std.testing.expectEqual(Source.all, aq.source); + typeKeys(p, "needle"); + settle(p); + try std.testing.expectEqual(@as(usize, 3), aq.total); + const all = p.panes[aid].?.file.?.content; + var hb: [32]u8 = undefined; + const first = std.mem.indexOf(u8, all, try std.fmt.bufPrint(&hb, config.pane_addr ++ "{d} ", .{a.serial})).?; + const second = std.mem.indexOf(u8, all, try std.fmt.bufPrint(&hb, config.pane_addr ++ "{d} ", .{p.panes[s].?.serial})).?; + try std.testing.expect(a.serial < p.panes[s].?.serial and first < second); + try std.testing.expect(second < std.mem.indexOf(u8, all, "twice").?); + // two places on one line are one row + try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, all, "twice")); +} + +test "zz query timings on the 1.2 MB stress file (QUERY_TIMES=)" { + const path_z = std.c.getenv("QUERY_TIMES") orelse return error.SkipZigTest; + const path = std.mem.span(path_z); + const io = std.testing.io; + const bytes = try std.Io.Dir.cwd().readFileAlloc(io, path, std.testing.allocator, .limited(8 << 20)); + defer std.testing.allocator.free(bytes); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 50 }); + defer p.deinit(); + const pane = try p.setTestFile(bytes); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, path); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + pane.body.cur_row = 15000; + pane.ensureCursorVisible(); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + const Clock = struct { + fn step(pp: *Pardes, fr: *std.heap.ArenaAllocator, ev: pardes.Event) !u64 { + const t0 = Places.nowNs(); + pp.update(ev); + _ = fr.reset(.retain_capacity); + _ = try pp.render(fr.allocator()); + return Places.nowNs() - t0; + } + }; + var report: std.ArrayList(u8) = .empty; + defer report.deinit(std.testing.allocator); + var base: u64 = 0; + for (0..10) |_| base += try Clock.step(p, &frame, .{ .key = .{ .cp = 'j', .text = "j" } }); + try report.print(std.testing.allocator, "a cursor move and its frame, no search: {d} us\n", .{base / 10 / 1000}); + const t_open = try Clock.step(p, &frame, .{ .key = .{ .cp = '/', .text = "/" } }); + try report.print(std.testing.allocator, "open / {d} us\n", .{t_open / 1000}); + for ("pane.v") |c| { + const t = try Clock.step(p, &frame, .{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + var ticks: usize = 0; + var worst: u64 = 0; + while (busy(p) or pane.places.busy(pane)) : (ticks += 1) { + if (ticks > 500) break; + worst = @max(worst, try Clock.step(p, &frame, .tick)); + } + const qid = queryPane(p).?; + try report.print(std.testing.allocator, "key '{c}': {d} us, then {d} ticks (worst {d} us), {d} places\n", .{ c, t / 1000, ticks, worst / 1000, p.panes[qid].?.query.?.total }); + } + // Enter: frozen; then edits in the owner with the pane open. + _ = try Clock.step(p, &frame, .{ .key = .{ .cp = Key.enter } }); + _ = try Clock.step(p, &frame, .{ .key = .{ .cp = 'i', .text = "i" } }); + var worst_edit: u64 = 0; + var sum: u64 = 0; + for (0..20) |_| { + const t = try Clock.step(p, &frame, .{ .key = .{ .cp = 'x', .text = "x" } }); + worst_edit = @max(worst_edit, t); + sum += t; + const t2 = try Clock.step(p, &frame, .tick); + worst_edit = @max(worst_edit, t2); + } + try report.print(std.testing.allocator, "edit in the owner (insert x, then a tick): mean {d} us, worst {d} us\n", .{ sum / 20 / 1000, worst_edit / 1000 }); + // The same edits with no query pane at all, for the editor's own cost. + p.update(.{ .key = .{ .cp = Key.escape } }); + exec.runBuiltin(p, .Del, queryPane(p).?, "", null); + p.update(.tick); + p.update(.{ .key = .{ .cp = 'i', .text = "i" } }); + sum = 0; + for (0..20) |_| sum += try Clock.step(p, &frame, .{ .key = .{ .cp = 'x', .text = "x" } }); + try report.print(std.testing.allocator, "the same edit, no search: mean {d} us\n", .{sum / 20 / 1000}); + std.debug.print("{s}", .{report.items}); +} + +test "* seeds line 1 and keeps the keyboard; SPC b b picks a pane, SPC s s a declaration; SearchPane new leaves the last where it is" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); + defer p.deinit(); + const pane = try p.setTestFile("const alpha = 1;\nfn beta() void {\n _ = alpha;\n}\nfn gamma() void {}\n"); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, "/tmp/x.zig"); + // `*` on `const`: line 1 `/\bconst\b`, the keyboard still in the text + typeKeys(p, "e*"); + const qid = queryPane(p).?; + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expect(std.mem.startsWith(u8, lineOne(p.panes[qid].?.file.?.content), "/")); + try std.testing.expect(pane.places.started); + typeKeys(p, "n"); + try std.testing.expectEqual(@as(?usize, 0), pane.places.current); + // SPC b b: the open panes by name; Enter goes to the marked one + p.newScratchBelow(0); + const other = p.active; + p.active = 0; + leader(p, "bb"); + const bid = queryPane(p).?; + try std.testing.expectEqual(bid, qid); + try std.testing.expectEqual(Source.panes, p.panes[bid].?.query.?.source); + try std.testing.expect(p.panes[bid].?.query.?.total >= 1); + // SPC s s: the declarations, fuzzy; Enter lands on the line + p.update(.{ .key = .{ .cp = Key.escape } }); + p.active = 0; + leader(p, "ss"); + const sid = queryPane(p).?; + try std.testing.expectEqual(Source.symbols, p.panes[sid].?.query.?.source); + // (context declarations span lines: a one-line fn is none of them) + typeKeys(p, "bet"); + try std.testing.expectEqual(@as(usize, 1), p.panes[sid].?.query.?.total); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(@as(usize, 0), p.active); + try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); + _ = other; + // SearchPane new: the frozen one stays, unattached; a new one under the owner + p.settings.search_pane = .new; + typeKeys(p, "/"); + const nid = queryPane2(p, sid).?; + try std.testing.expect(nid != sid); + try std.testing.expect(p.panes[sid].?.attached_to == null); + try std.testing.expectEqual(@as(?usize, 0), layout.ownerOf(p, nid)); +} + +fn queryPane2(p: *Pardes, not: usize) ?usize { + for (p.panes, 0..) |slot, i| if (slot) |pane| if (pane.query != null and i != not) return i; + return null; +} diff --git a/src/Text.zig b/src/Text.zig index cef76b3b..88630f83 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -182,7 +182,10 @@ pub fn primaryRange(t: *Text, text: []const u8, row0: i32) modal.Selection { const e = if (r1 + 1 >= modal.cursorLineCount(text)) text.len else modal.lineStartOffset(text, r1 + 1); return .{ .anchor = s, .head = @max(e, modal.nextGrapheme(text, c)) }; } - if (t.vsel.active) return cellRange(text, t.vsel.row - row0, t.vsel.col, t.cur_row - row0, t.cur_col); + // Both ends through the line index, as the cursor's: cellRange counts + // lines from the top for each, a pass over a big file per call (the + // places' settle and every insert-mode key asked it). + if (t.vsel.active) return cellOffRange(text, File.textOffset(t, text, .{ .row = @intCast(@max(0, t.vsel.row - row0)), .col = @intCast(@max(0, t.vsel.col)) }), c); return .{ .anchor = c, .head = modal.nextGrapheme(text, c) }; } diff --git a/src/body_layer.zig b/src/body_layer.zig index d44045a6..e50b7e3e 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -275,6 +275,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane panes.File.recolorSyntax(p, s, pane, f, r, tx, tw, body_h); panes.File.drawWrapMarkers(p, s, pane, r, tx, tw, body_h, pane_bg); pane.places.paint(p, s, pane, r, body_h); + panes.Query.paint(p, s, pane, r, body_h); } else if (pane.isTerminal() and p.settings.colors) { panes.terminal.recolorAnsi(p, s, pane, r, tx, tw, body_h, body); panes.File.recolorDiffOutput(p, s, pane, r, tx, tw, body_h, body); diff --git a/src/builtins.zig b/src/builtins.zig index 1ec33d88..7cdee9de 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -210,7 +210,7 @@ pub const registry = struct { .toggle, .transition, .scene, .dump_dir, .choice, .lift, .shader_animation, .motion, .shell => false, .theme, .font, .tagline_size, .window_opacity, .window_blur, .message_ms, .shader, .inactive_dim, .grip_width => true, // bare, it says the current value (exec.applySettingBuiltin) - .tab, .callstack_depth => false, + .tab, .callstack_depth, .search_rows => false, }; return declOr(b, "requires_arg", false, false); } @@ -1721,7 +1721,8 @@ pub const Find = struct { if (rows == 0) c.p.reportFailure(c.id, e_search_miss_find); return; } - c.p.startPrompt(c.pane, &c.pane.body, .{ .search = config.find_marker }); + // Bare (SPC f f): the query pane, line 1 `Find `, typed into. + panes.Query.open(c.p, c.id, .find, "", true); } }; @@ -1738,7 +1739,29 @@ pub const Grep = struct { if (rows == 0) c.p.reportFailure(c.id, e_search_miss_grep); return; } - c.p.startPrompt(c.pane, &c.pane.body, .{ .search = config.grep_marker }); + // Bare (SPC f g): the query pane, line 1 `Grep `, typed into. + panes.Query.open(c.p, c.id, .grep, "", true); + } +}; + +/// Search in a query pane under this pane, line 1 the argument (`Panes`, +/// `Symbols lay`, `All needle`, `/re`, any of its words); bare, `/`. +pub const Search = struct { + pub const takes_arg = true; + pub const quiet = true; + pub fn run(c: Ctx) void { + const line = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + const asked = panes.Query.parse(line) orelse panes.Query.parse(std.mem.concat(c.p.scratch.allocator(), u8, &.{ "/", line }) catch return).?; + panes.Query.open(c.p, c.id, asked.source, asked.pat, true); + } +}; + +/// Pick an open pane by its name in a query pane under this one (SPC b b). +pub const Panes = struct { + pub const takes_arg = true; + pub const quiet = true; + pub fn run(c: Ctx) void { + panes.Query.open(c.p, c.id, .panes, std.mem.trim(u8, c.arg orelse "", " \t\r\n"), true); } }; @@ -1866,9 +1889,13 @@ pub const Last = struct { /// List the files opened lately, closed ones too, each a place to open again. pub const Recent = struct { pub const scope: Scope = .session; + pub const takes_arg = true; pub const output: OutputTraits = .{ .name = config.recent_buffer, .steps = true, .locations = true }; pub fn run(c: Ctx) void { - panes.Output.openRecent(c.p, c.id) catch |err| c.p.reportError(c.id, "recent", err); + // From a pane: the query pane under it, line 1 `Recent `, typed + // into; from a header, which no pane owns, the +Recent list. + if (c.p.exec_header or c.p.panes[c.id] == null) return panes.Output.openRecent(c.p, c.id) catch |err| c.p.reportError(c.id, "recent", err); + panes.Query.open(c.p, c.id, .recent, std.mem.trim(u8, c.arg orelse "", " \t\r\n"), true); } }; diff --git a/src/config.zig b/src/config.zig index 06eec2d9..2fa4a55d 100644 --- a/src/config.zig +++ b/src/config.zig @@ -26,6 +26,26 @@ pub const leader_help: u8 = '?'; const undecided: []const u8 = ""; +/// Leader paths that run a builtin WITH an argument (the pick prototype's): +/// the query pane's sources that have no word of their own, `Search` and +/// line 1. `SPC s` is the session group (Dump, Restore, Attach), so the +/// declarations are `SPC s s`, a key from helix's. +pub const leader_args = [_]struct { path: []const u8, cmd: Builtin, arg: []const u8 }{ + .{ .path = "bb", .cmd = .Search, .arg = "Panes" }, + .{ .path = "ss", .cmd = .Search, .arg = "Symbols" }, + .{ .path = "/", .cmd = .Search, .arg = "All" }, +}; + +comptime { + @setEvalBranchQuota(20_000); + // A path here is a leaf: no builtin's path is it or runs past it, and + // none of it is a builtin's whole path. + for (leader_args) |la| for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |path| { + if (std.mem.startsWith(u8, path, la.path) or std.mem.startsWith(u8, la.path, path)) + @compileError("leader_args path collides with " ++ @tagName(b) ++ ": " ++ la.path); + }; +} + // null means word/chord-only. Every enabled builtin must explicitly choose a path. pub const leader_path = paths: { @setEvalBranchQuota(10_000); // a check per builtin, and they grow @@ -94,6 +114,11 @@ pub const leader_path = paths: { .Delcol = "cd", .Joincol = "cj", .Placement = "cp", + .SearchPlace = null, + .SearchPane = null, + .SearchRows = null, + .Search = null, + .Panes = null, .BootShell = null, .LookWord = null, .DirLook = null, @@ -517,6 +542,7 @@ pub const dump_config_buffer = "+DumpConfig"; pub const effect_code_buffer = "+EffectCode"; pub const jumps_buffer = "+Jumps"; pub const recent_buffer = "+Recent"; +pub const preview_buffer = "+Preview"; pub const unsaved_buffer = "+Unsaved"; pub const themes_buffer = "+Themes"; pub const fonts_buffer = "+Fonts"; @@ -846,6 +872,15 @@ pub const Runtime = struct { callstack_layout: CallstackLayout = .stacked, callstack_corners: CallstackCorners = .rounded, callstack_depth: u8 = @import("lsp/lsp.zig").callstack_default_depth, + /// Where a query pane goes (Query.zig): `attached`, under the pane that + /// asked, out of its rows alone; `column`, in the finder column. + search_place: SearchPlace = .attached, + /// A search from a pane that has a query pane: `reuse` it (its frozen + /// rows back on Esc), or open a `new` one, the last left where it is. + search_pane: SearchPane = .reuse, + /// The body rows a query pane is born with under its line 1 (and its + /// +Preview with): it never resizes itself after. + search_rows: u16 = 8, pub const ShaderAnimation = enum { off, on, always }; pub const Placement = enum { acme, pardes }; @@ -858,8 +893,10 @@ pub const Runtime = struct { pub const JumpScope = enum { file, all }; pub const CallstackLayout = enum { @"inline", stacked }; pub const CallstackCorners = @import("lsp/lsp.zig").CallstackCorners; + pub const SearchPlace = enum { attached, column }; + pub const SearchPane = enum { reuse, new }; /// A setting that is one of a few words, each an enum field of Runtime. - pub const Choice = enum { placement, boot_shell, look_word, dir_look, diff_look, pager, term_images, jump_scope, callstack_layout, callstack_corners }; + pub const Choice = enum { placement, boot_shell, look_word, dir_look, diff_look, pager, term_images, jump_scope, callstack_layout, callstack_corners, search_place, search_pane }; /// shadow: a soft drop shadow. rim: a light hairline along the top of /// the focused pane's tag rows. auto: a shadow on a light page; on a @@ -1048,6 +1085,7 @@ pub const Runtime = struct { grip_width, tab, callstack_depth, + search_rows, transition: animation.Transition, scene: Scene, /// A Shadertoy file into the post chain or out of it; `off` empties @@ -1137,6 +1175,9 @@ pub const Runtime = struct { .{ .word = "CallstackCorners", .action = .{ .choice = .callstack_corners }, .doc = "Callstack tree corners: rounded (the default) or square; bare, it switches styles. Applies to the next Callstack query." }, .{ .word = "CallstackDepth", .action = .callstack_depth, .doc = "Caller levels collected by Callstack, 1 through 64; default 8. Bare, it says the current limit." }, .{ .word = "Tab", .action = .tab, .doc = "A tab's width in cells, 1 through 16, in every pane; bare, it says the width." }, + .{ .word = "SearchPlace", .action = .{ .choice = .search_place }, .doc = "Where a query pane goes: attached, under the pane that asked, out of its rows alone, or column, in the finder column." }, + .{ .word = "SearchPane", .action = .{ .choice = .search_pane }, .doc = "A search from a pane that has a query pane: reuse it, or open a new one and leave the last where it is." }, + .{ .word = "SearchRows", .action = .search_rows, .doc = "The rows a query pane is born with under its line 1, 1 through 100; default 8. It never resizes itself." }, }; pub fn find(name: []const u8) ?Setting { @@ -1311,6 +1352,7 @@ pub const Runtime = struct { .grip_width => state.grip_width = number(u16, argument, " \t\r\n%", 50, 300) orelse return false, .callstack_depth => state.callstack_depth = number(u8, argument, " \t\r\n", 1, @import("lsp/lsp.zig").callstack_max_depth) orelse return false, .tab => state.tab = number(u16, argument, " \t\r\n", 1, 16) orelse return false, + .search_rows => state.search_rows = number(u16, argument, " \t\r\n", 1, 100) orelse return false, .theme, .font => return false, } return true; @@ -1348,6 +1390,7 @@ pub const Runtime = struct { .grip_width => "50-300 (a percentage)", .tab => "1-16 (cells)", .callstack_depth => "1-64 (levels)", + .search_rows => "1-100 (rows)", .tagline_size => std.fmt.comptimePrint("{d}-{d} (a percentage)", .{ tagline_percent_min, tagline_percent_max }), .message_ms => std.fmt.comptimePrint("0-{d} (milliseconds)", .{message_ms_max}), .shell => "a path of at most 255 bytes; bare, $SHELL, else /bin/sh", @@ -1490,6 +1533,7 @@ pub const Runtime = struct { .inactive_dim => try out.print("{s} {d}\n", .{ setting.word, state.inactive_dim }), .callstack_depth => try out.print("{s} {d}\n", .{ setting.word, state.callstack_depth }), .tab => try out.print("{s} {d}\n", .{ setting.word, state.tab }), + .search_rows => try out.print("{s} {d}\n", .{ setting.word, state.search_rows }), .grip_width => try out.print("{s} {d}\n", .{ setting.word, state.grip_width }), }; if (context.locations.len > 0) try out.print("LocationsConfig {s}\n", .{context.locations}); @@ -1773,6 +1817,8 @@ pub const Runtime = struct { .jump_scope => "all", .callstack_layout => "inline", .callstack_corners => "square", + .search_place => "column", + .search_pane => "new", }, .lift => "rim", .motion => "playful", @@ -1780,6 +1826,7 @@ pub const Runtime = struct { .grip_width => "200", .callstack_depth => "16", .tab => "8", + .search_rows => "12", else => null, }; try std.testing.expect(apply(&state, setting, argument)); @@ -1853,6 +1900,8 @@ pub const Runtime = struct { .jump_scope => "JumpScope all\n", .callstack_layout => "CallstackLayout inline\n", .callstack_corners => "CallstackCorners square\n", + .search_place => "SearchPlace column\n", + .search_pane => "SearchPane new\n", }, .lift => "Lift rim\n", .motion => "Motion playful\n", @@ -1860,6 +1909,7 @@ pub const Runtime = struct { .grip_width => "GripWidth 200\n", .callstack_depth => "CallstackDepth 16\n", .tab => "Tab 8\n", + .search_rows => "SearchRows 12\n", .theme, .font => unreachable, }; try std.testing.expect(std.mem.indexOf(u8, report, expected) != null); @@ -2212,6 +2262,7 @@ const doc_typ = struct { if (n == 0) return leader.len == 1 and leader[0].cp == ' '; for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |p| if (std.mem.eql(u8, p, path[0..n])) return true; + for (leader_args) |la| if (std.mem.eql(u8, la.path, path[0..n])) return true; return false; } toks.reset(); @@ -2308,6 +2359,7 @@ const doc_tutor = struct { fn path(keys: []const u8) bool { for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |p| if (std.mem.startsWith(u8, p, keys)) return true; + for (leader_args) |la| if (std.mem.startsWith(u8, la.path, keys)) return true; return false; } diff --git a/src/edit.zig b/src/edit.zig index c9477c29..a06f5f2d 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -568,6 +568,26 @@ fn setEditTextSpan(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor, sp return; } const pane = t.pane() orelse return retireEditText(p, new); + // A live query pane's rows are its line 1's (Query.zig): an edit there + // is refused, as a tag's prefix refuses one, and one from line 1 into + // them is cut at its end. The rows' metadata stays theirs across an + // edit of the line, which moves no row. + if (pane.file) |*f| if (pane.query) |q| if (!q.frozen) { + const kept = panes.Query.clampEdit(p, t, f.content, new) orelse return retireEditText(p, new); + if (kept.ptr != new.ptr) retireEditText(p, new); + const end = modal.positionAt(kept, kept.len - panes.File.spanOf(f.content, kept).tail); + t.last_edit = .{ .row = @intCast(end.row), .col = @intCast(end.col) }; + const rows = f.location_rows; + const spans = f.pager_spans; + f.location_rows = &.{}; + f.pager_spans = &.{}; + panes.File.setContentSpan(p, f, kept, null); + if (f.location_rows.len > 0) @import("locations.zig").freeRows(p.gpa, f.location_rows); + p.gpa.free(f.pager_spans); + f.location_rows = rows; + f.pager_spans = spans; + return; + }; // what changed ended where the texts agree again from their ends const old: []const u8, const row0: i32 = if (pane.file) |f| .{ f.content, 0 } else if (pane.ovl) |o| .{ o.text, o.row } else .{ "", 0 }; // ponytail: O(file), for the edits that do not say what they changed diff --git a/src/exec.zig b/src/exec.zig index a9c11049..2bc1a3e5 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -194,6 +194,20 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l // the look is of the address it names (look.diffAddress), a regular // look from there. A hunk line's code is words, looked at as ever: // the code's, the prefix never one of them. + // A query pane's row pointed at on its gutter (its line number): the + // look is of the row's address (Query.rowAddress), as a +Diff line's + // prefix is its place; the row's code is words, looked at as ever. + if (for_look and pane.query != null and clicked.r0 >= pane.tag_rows and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1 and row >= 0 and col >= 0) gutter: { + var address_buf: [4096 + 32]u8 = undefined; + const address = panes.Query.rowAddress(pane, @intCast(row), @intCast(col), &address_buf) orelse break :gutter; + const meta = pane.file.?.location_rows[@intCast(row)]; + result.text = p.scratch.allocator().dupe(u8, address) catch break :gutter; + result.file_word = .{ .row = row, .lo = 0, .hi = @intCast(meta.location_end) }; + const expanded = fileWordCells(pane, clicked, row, 0, @intCast(meta.location_end)) orelse return result; + result.preview = expanded; + result.expanded = expanded; + return result; + } var word_from: usize = 0; if (for_look and clicked.r0 >= pane.tag_rows and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1 and row >= 0) diff: { var address_buf: [4096 + 32]u8 = undefined; @@ -1118,6 +1132,12 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] } else if (!p.settings.apply(setting, arg)) { p.reportFailure(p.active, "CallstackDepth: takes " ++ comptime config.Runtime.takes(.callstack_depth).?); }, + .search_rows => if (arg == null) { + var said: [40]u8 = undefined; + return p.setMessage(p.active, std.fmt.bufPrint(&said, "SearchRows {d}", .{p.settings.search_rows}) catch "SearchRows"); + } else if (!p.settings.apply(setting, arg)) { + p.reportFailure(p.active, "SearchRows: takes " ++ comptime config.Runtime.takes(.search_rows).?); + }, // Bare, it says the width, as acme's Tab does. .tab => if (arg == null) { var said: [32]u8 = undefined; diff --git a/src/fs.zig b/src/fs.zig index e809eda5..cb813262 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1119,7 +1119,7 @@ const find_max_steps = 100_000; /// One root's Find or Grep rows at most: its hits, each a path and a line. pub const search_root_output_bytes = find_max_hits * (4096 + 320); -const find_skip = [_][]const u8{ +pub const find_skip = [_][]const u8{ ".git", ".jj", "target", "node_modules", ".venv", "__pycache__", ".zig-cache", "zig-out", }; diff --git a/src/layout.zig b/src/layout.zig index f0689b10..dac0aa7e 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -1016,21 +1016,31 @@ pub fn keepGroups(p: *Pardes) void { /// False, `id` in no column, when the owner has not the rows for its tag /// and the attachment's minimum. pub fn attach(p: *Pardes, owner: usize, id: usize, rows: u16) bool { + return attachFrom(p, owner, id, rows, owner); +} + +/// attach, the rows given by `giver`: the owner itself or a pane of its +/// group (a +Preview added under a query pane later takes the text's rows, +/// so the query pane, typed into, keeps its own). +pub fn attachFrom(p: *Pardes, owner: usize, id: usize, rows: u16, giver: usize) bool { const o = p.panes[owner] orelse return false; + const g = p.panes[giver] orelse return false; const nw = p.panes[id] orelse return false; if (o.collapsed) toggleCollapse(p, owner); + if (g.collapsed) toggleCollapse(p, giver); compute(p); const f = findPane(p, owner) orelse return false; + if (giver != owner and groupRoot(p, owner) != groupRoot(p, giver)) return false; // Its tag wraps at the column's width: measured there. p.rects[id].w = p.col_w[f.col]; - const oh = p.rects[owner].h; + const oh = p.rects[giver].h; const least = minRows(p, id); if (oh < least + BOX_H) return false; - const owner_keeps = if (oh >= least + minRows(p, owner)) minRows(p, owner) else BOX_H; - const give = std.math.clamp(rows, least, oh - owner_keeps); + const giver_keeps = if (oh >= least + minRows(p, giver)) minRows(p, giver) else BOX_H; + const give = std.math.clamp(rows, least, oh - giver_keeps); snapColWeights(p, f.col); insert(p, f.col, groupEnd(p, f.col, f.idx), id); - o.vweight = @floatFromInt(oh - give); + g.vweight = @floatFromInt(oh - give); nw.vweight = @floatFromInt(give); nw.attached_to = o.serial; compute(p); diff --git a/src/look.zig b/src/look.zig index 2d97cb9f..eed3dbd9 100644 --- a/src/look.zig +++ b/src/look.zig @@ -1719,6 +1719,8 @@ pub fn reopenAt(p: *Pardes, from: usize, path: []const u8, at: Spot) void { /// Whether `pane` is the +Recent or the Jumplist list, whose rows are /// remembered places: a look at one clamps to the file as it is now. fn isRecentList(pane: *const Pane) bool { + // A query pane over the recent files: its rows are remembered places. + if (pane.query) |q| if (q.source == .recent) return true; const f = pane.file orelse return false; const o = f.output orelse return false; return std.meta.eql(o.from, panes.Output.Origin{ .cmd = .Recent }) or std.meta.eql(o.from, panes.Output.Origin{ .cmd = .Jumplist }); diff --git a/src/mouse.zig b/src/mouse.zig index ec5560d0..3400afbe 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -1083,6 +1083,15 @@ pub fn dispatchPointerBuiltin( // nothing, as acme's look3 and execute return on an empty expansion. const operand = text orelse return; if (gesture) |g| if (reportGesture(p, id, cmd, operand, g.on_tag, g.operand, arg)) return; + // B2 anywhere on a query pane's line 1 is the line: run again, whatever + // word of it was clicked (Query.zig). + if (gesture) |g| if (!g.on_tag and g.operand.row == 0 and cmd == config.exec_cmd) if (p.panes[id]) |pane| if (pane.query) |q| { + p.gpa.free(q.asked); + q.asked = &.{}; + q.frozen = false; + panes.Query.produceAll(p, false); + return; + }; // A middle click on a body is the exec a bound REPL may take. exec.runBuiltinFrom(p, cmd, id, "", exec.withArg(p, operand, arg), gesture != null and !gesture.?.on_tag); } diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index f9bec775..45336a1e 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -89,6 +89,8 @@ pub fn run(p: *Pardes, id: usize, exec: bool, text: []const u8, in_tag: bool) vo const after = Serials.snapshot(p); var created = false; for (after.list[0..after.len]) |serial| if (std.mem.indexOfScalar(u32, before.list[0..before.len], serial) == null) { + // A query pane's +Preview is its query pane's: that answers. + if (p.paneBySerial(serial)) |made| if (p.panes[made].?.file) |f| if (f.output) |o| if (o.from == .preview) continue; // A look that made a +Search pane (LookWord list, a terminal) // answers it: that is where the places it found are. noteResult(p, serial); @@ -555,6 +557,7 @@ fn checkBuiltin(p: *Pardes, req: Req, line: []const u8, scope: builtins.Scope) ? // Bare, it says the width, as from a pane's exec. .tab => arg.len == 0 or (std.fmt.parseInt(u16, arg, 10) catch 0) -% 1 < 16, .callstack_depth => arg.len == 0 or (std.fmt.parseInt(u8, arg, 10) catch 0) -% 1 < pardes.lsp.callstack_max_depth, + .search_rows => arg.len == 0 or (std.fmt.parseInt(u16, arg, 10) catch 0) -% 1 < 100, else => probe: { var probe = p.settings; break :probe probe.apply(setting, if (arg.len > 0) arg else null); @@ -664,6 +667,7 @@ pub fn writeSettingsOf(p: *Pardes, s: *const config.Runtime, w: *std.Io.Writer) .inactive_dim => try w.print("{s} {d}\n", .{ word, s.inactive_dim }), .grip_width => try w.print("{s} {d}\n", .{ word, s.grip_width }), .callstack_depth => try w.print("{s} {d}\n", .{ word, s.callstack_depth }), + .search_rows => try w.print("{s} {d}\n", .{ word, s.search_rows }), .tab => try w.print("{s} {d}\n", .{ word, s.tab }), } } @@ -3890,8 +3894,10 @@ test "Recent's row for a file still open is where its dot is now, not where it l pane.body.cur_col = 2; try testing.expectEqual(Status.ok, wr(p, root_exec, "Recent\n").reply.status); const rows = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; - var want: [4300]u8 = undefined; - try testing.expect(std.mem.indexOf(u8, rows.file.?.content, try std.fmt.bufPrint(&want, "{s}/a.txt:2:3 open\n", .{dir})) != null); + // A query pane under the file (line 1 `Recent `), its rows said from + // its directory. + try testing.expect(std.mem.startsWith(u8, rows.file.?.content, "Recent \n")); + try testing.expect(std.mem.indexOf(u8, rows.file.?.content, "\na.txt:2:3 open\n") != null); } test "a closed file is found again: Recent and /recent list it closed, a look at its row reopens it at its dot, and a jump back does too" { @@ -3924,7 +3930,8 @@ test "a closed file is found again: Recent and /recent list it closed, a look at // Recent lists it, closed, at its dot; a look at the row opens it there. try testing.expectEqual(Status.ok, wr(p, root_exec, "Recent\n").reply.status); const rows = p.panes[p.paneBySerial(try std.fmt.parseInt(u32, std.mem.trimEnd(u8, rd(p, root_exec, 0, 64).bytes, "\n"), 10)).?].?; - const at = std.mem.indexOf(u8, rows.file.?.content, try std.fmt.bufPrint(&want, "{s}:3:", .{a})).?; + // Its query pane's rows are said from its directory, a.txt's. + const at = std.mem.indexOf(u8, rows.file.?.content, "\na.txt:3:").? + 1; const row = rows.file.?.content[at..std.mem.indexOfScalarPos(u8, rows.file.?.content, at, '\n').?]; try testing.expect(std.mem.endsWith(u8, row, " (closed)")); try testing.expectEqual(Status.ok, wr(p, Node.of(rows.serial, .look), try std.fmt.bufPrint(&line, "{s}\n", .{row[0 .. row.len - " (closed)".len]})).reply.status); @@ -3939,6 +3946,9 @@ test "a closed file is found again: Recent and /recent list it closed, a look at var closed_entry = false; for (p.jumps[0..p.njumps]) |j| closed_entry = closed_entry or j.serial == 0; try testing.expect(closed_entry); + // Every entry in order (JumpScope all): which file has the focus after + // a Del is the layout's to choose, and Back keeps to it first. + p.settings.jump_scope = .all; var tries: usize = 0; while (tries < p.njumps) : (tries += 1) { p.jumpBy(-1); diff --git a/src/normal.zig b/src/normal.zig index 808ac886..ebace536 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -930,7 +930,12 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void .body, .input => tagline.enterTag(p, pane), }, .pipe_selection => |how| return p.startPrompt(pane, t, .{ .pipe = how }), - .search => return p.startPrompt(pane, &pane.body, .{ .search = config.search_marker }), + // `/` in a text is its query pane's line 1 (Query.zig); a + // terminal's still asks on the notice band. + .search => if (pane.file != null and t.what == .body) + panes.Query.open(p, p.active, .text, "", true) + else + return p.startPrompt(pane, &pane.body, .{ .search = config.search_marker }), // In a file's text, n and N step its places while they answer for // the register (Places.answersN); else helix's search of the register. .search_step => |step| if (t.what == .body and pane.file != null and pane.places.answersN(p, pane)) @@ -939,12 +944,13 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void return searchStep(p, t, text, step.direction, step.count), .search_selection => |boundary| { searchSelection(p, t, text, boundary); - // The pattern's places: the selection is already on one of them. - if (t.what == .body and pane.file != null) { + // The pattern is line 1 of this text's query pane, made or + // reused, the keyboard staying here: n and N step its places. + if (t.what == .body and pane.file != null and !pane.hasPdf() and pane.query == null) { const name = if (p.register != 0) p.register else '/'; const pat = p.registers.value(name, 0) orelse return; - const r = pane.body.primaryRange(text, 0); - pane.places.search(p, pane, .search, 0, pat, false, @min(r.anchor, r.head), false); + panes.Query.open(p, p.active, .text, pat, false); + pane.places.provenance = .search; } }, .node => |walk| return nodeSelect(p, pane, t, walk), diff --git a/src/panes.zig b/src/panes.zig index 73794b91..e0eb3fec 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -108,6 +108,9 @@ pub const Pane = struct { /// gone, or a pane no longer right under its owner's group, leaves it /// an ordinary pane (layout.keepGroups). attached_to: ?u32 = null, + /// This pane is a query pane: its line 1 the query, its rows made live + /// from a source (Query.zig, gpa-owned). + query: ?*Query = null, cols: u16, rows: u16, greet: bool = false, @@ -463,6 +466,8 @@ pub const Pane = struct { if (f.mini != null) return .source; if (std.mem.endsWith(u8, f.path, ".diff") or std.mem.endsWith(u8, f.path, ".patch") or f.pager_diff) return .diff; if (f.output != null) { + // A +Preview is a file's text: coloured as the file. + if (f.output.?.from == .preview) return .source; const tr = Output.fileTraits(f.output); if (tr.locations) return .locations; if (!tr.saves) return .none; @@ -655,6 +660,8 @@ pub const Output = @import("Output.zig"); pub const Places = @import("Places.zig"); +pub const Query = @import("Query.zig"); + pub const Dir = @import("Dir.zig"); pub const mini = @import("mini.zig"); diff --git a/src/pardes.zig b/src/pardes.zig index c4011f7d..1b4e9920 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -486,6 +486,8 @@ test { _ = @import("animation.zig"); _ = @import("pager.zig"); _ = @import("Places.zig"); + _ = @import("Query.zig"); + _ = @import("Names.zig"); } pub const Builtin = builtins.registry.Builtin(); @@ -4402,6 +4404,9 @@ pub const Pardes = struct { jumps: [MAX_JUMPS]Loc = undefined, njumps: usize = 0, jcur: usize = 0, + /// The next place tracked is an entry of its own however near the last + /// (a query answered: Ctrl-o goes back to where it was asked). + jump_force: bool = false, look_src: [MAX_PANES]u32 = undefined, n_look_src: usize = 0, look_walk_owner: ?u32 = null, @@ -5049,6 +5054,8 @@ pub const Pardes = struct { // to it reopen it there. p.noteClosed(pane); panes.Output.dropUnsaved(p, pane); + // A query pane's places, in whatever panes it fed, go with it. + if (pane.query != null) panes.Query.release(p, pane); if (pane.file) |*file| panes.File.leaveTwins(p, file); const watched = (if (pane.file) |f| f.output == null else false) or pane.hasPdf(); for (p.panes, 0..) |slot, id| if (slot == pane) { @@ -5084,6 +5091,11 @@ pub const Pardes = struct { pane.input.deinit(p.gpa); pane.jump.deinit(p.gpa); pane.places.deinit(p.gpa); + if (pane.query) |q| { + q.deinit(p.gpa); + p.gpa.destroy(q); + pane.query = null; + } panes.terminal.deinitEmulator(pane, p.gpa); pane.clearCwd(); pane.fs.deinit(p.gpa); @@ -6121,6 +6133,8 @@ pub const Pardes = struct { // Each pane's places find a frame's more on a tick, and on any other // step the ones an edit or a scroll left unfound in the view. for (p.panes) |slot| if (slot) |pane| pane.places.settle(p, pane, ev == .tick); + // Each live query pane's rows, made from what changed this step. + panes.Query.produceAll(p, ev == .tick); _ = p.scratch.reset(.{ .retain_with_limit = memory.limits.scratch_kept }); p.sync(); p.fsReport(); @@ -6450,6 +6464,9 @@ pub const Pardes = struct { return; } if (t == &pane.body and pane.jump.items.len > 0) return normal.jumpKey(p, pane, t, key); + // A query pane's line 1 answers Enter, Esc and the stepping keys + // itself (Query.zig). + if (t == &pane.body and header == null and pane.query != null and panes.Query.key(p, p.active, key)) return; if (t.mode == .normal and p.macro.replaying == 0 and (hit(key, config.look_key) or hit(key, config.exec_key))) { // A header's words are the workspace's and column's commands, so // Enter runs them there, as the execute key does. @@ -6564,6 +6581,12 @@ pub const Pardes = struct { p.leader_keys[p.leader_n] = c; p.leader_n += 1; const pfx = p.leader_keys[0..p.leader_n]; + // A path that runs a builtin with its argument (the query pane's + // sources with no word of their own). + for (config.leader_args) |la| if (std.mem.eql(u8, la.path, pfx)) return exec.runBuiltin(p, la.cmd, p.active, "", la.arg); + for (config.leader_args) |la| if (std.mem.startsWith(u8, la.path, pfx)) { + p.leader_on = true; + }; // a path-less builtin is a row here too (it is the same index Help // reads), and SPC cannot reach one — so both scans skip it for (builtin_rows) |row| { @@ -7017,6 +7040,21 @@ pub const Pardes = struct { return; } + // The lists of places: into the asking text's query pane (made or + // reused), line 1 their word, the places in that text its places. + const listed: ?panes.Query.Source = switch (w.kind) { + .references => .refs, + .definition => .defs, + .implementation => .impls, + .diagnostics => .diagnostics, + else => null, + }; + if (listed) |source| if (pane.file != null and pane.query == null and !p.exec_header) { + p.fs.refilled = null; + panes.Query.fillList(p, w.pane, source, rows); + p.fs.lsp_result = if (panes.Query.ofOwner(p, pane.serial)) |qid| p.panes[qid].?.serial else null; + return; + }; const dir = if (pane.file) |f| panes.Dir.ofName(f.path) else pane.cwdSlice(); // A Callstack page that stops short ends in its marker: said as a // row naming the word that shows the next page, and kept. @@ -7285,6 +7323,11 @@ pub const Pardes = struct { p.jcur = @min(cur, w -| 1); const pane = p.panes[p.active] orelse return; + // A query being typed moves the owner's selection to show, never a + // jump; its pane is no place to come back to either. + if (pane.query) |q| if (!q.frozen) return; + const force = p.jump_force; + p.jump_force = false; const now: Loc = .{ .pane = @intCast(p.active), .serial = pane.serial, @@ -7292,14 +7335,14 @@ pub const Pardes = struct { .col = if (pane.pdfPage() != null) 0 else if (pane.body.cur_pinned) @intCast(@max(0, pane.body.cur_col) + 1) else 0, .path_hash = if (recentDot(pane)) |d| std.hash.Wyhash.hash(0, d.path) else 0, }; - if (p.njumps > 0 and p.samePlace(p.jumps[p.jcur], now)) { + if (!force and p.njumps > 0 and p.samePlace(p.jumps[p.jcur], now)) { p.jumps[p.jcur] = now; // same visit; the entry IS where you are return; } // a new jump made from the middle of the list drops everything ahead of // it, the way vim's does: the future you did not take is not history. if (p.njumps > 0) p.njumps = p.jcur + 1; - if (p.njumps >= 2 and p.samePlace(p.jumps[p.njumps - 2], now)) { + if (!force and p.njumps >= 2 and p.samePlace(p.jumps[p.njumps - 2], now)) { p.jumps[p.njumps - 2] = p.jumps[p.njumps - 1]; p.jumps[p.njumps - 1] = now; p.jcur = p.njumps - 1; @@ -7588,6 +7631,7 @@ pub const Pardes = struct { if (p.chrome_animation.isActive() or p.presentation.animating()) return next; // Places still to find resume on the next frame. for (p.panes) |slot| if (slot) |pane| if (pane.places.busy(pane)) return next; + if (panes.Query.busy(p)) return next; var frames: ?u64 = null; if (p.look_hover_wait) |waiting| { const delay = config.look_preview_delay_frames orelse return next; @@ -8003,11 +8047,13 @@ test "a prompt is typed on its own line in the notice band and leaves the tag ro const tag_before = try std.testing.allocator.dupe(Cell, p.surface.tag_layers[0].cells); defer std.testing.allocator.free(tag_before); - p.update(.{ .key = .{ .cp = '/' } }); + // `s` keeps a prompt on the band (a text's `/` is its query pane's + // line 1 now, Query.zig). + p.update(.{ .key = .{ .cp = 's' } }); p.update(.{ .key = .{ .cp = 't', .text = "tw" } }); p.update(.{ .key = .{ .cp = Key.left } }); try std.testing.expect(pane.prompt == .search and pane.focus == .body); - try std.testing.expectEqualStrings(config.search_marker ++ "tw", pane.promptText().?); + try std.testing.expectEqualStrings(config.select_marker ++ "tw", pane.promptText().?); _ = frame.reset(.retain_capacity); _ = try p.render(frame.allocator()); // The tagline is exactly what it was: nothing of the prompt is in it. diff --git a/src/tagline.zig b/src/tagline.zig index e668419d..89152a3a 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -35,6 +35,10 @@ pub const diff_view_tail = withFileCommands(" " ++ config.diff_view_builtins_str pub const terminal_pane_tail = " " ++ config.terminal_pane_builtins_str; pub const command_pane_tail = " " ++ config.command_pane_builtins_str; pub const dir_pane_tail = " " ++ config.dir_pane_builtins_str; +/// A query pane's while its rows are made (Query.zig), and once Enter froze +/// them into text a Save keeps; Unattach leaves it where it stands. +pub const query_live_tail = " Del"; +pub const query_frozen_tail = " Save Unattach Del"; /// A file with changes it has not saved. pub fn dirty(pane: *const panes.Pane) bool { const f = pane.file orelse return false; @@ -135,6 +139,9 @@ pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]co var idbuf: [48]u8 = undefined; return std.fmt.allocPrint(arena, "{s} {s}", .{ (try shownDir(arena, pane)), exec.replId(&idbuf, pane) }); } + // A query pane: its name and where it is among its hits, `+Search + // 3/27` (Query.zig): its owner is right above it. + if (pane.query) |q| if (pane.file) |f| if (pane.prompt != .name) return panes.Query.tagPrefix(q, arena, f.path); // Unsaved text shows on the grip, as acme's modbutton does, not as a // mark in the text: the prefix is the name alone. if (pane.file) |f| return if (pane.prompt == .name) pane.input.own orelse f.path else f.path; @@ -174,6 +181,7 @@ pub fn curTail(pane: *Pane) []const u8 { pub fn defaultTail(pane: *const Pane) []const u8 { if (comptime pdf_enabled) if (pane.pdf != null) return pdf_pane_tail; + if (pane.query) |q| return if (q.frozen) query_frozen_tail else query_live_tail; if (pane.file) |file| if (file.listing != null) return dir_pane_tail; if (pane.file) |file| if (file.pager) return if (file.pager_diff) pager_diff_pane_tail else pager_pane_tail; if (pane.file != null and pane.colorAlgo() == .diff) return diff_pane_tail; diff --git a/test/output.zig b/test/output.zig index 523e8129..8ba2f357 100644 --- a/test/output.zig +++ b/test/output.zig @@ -185,7 +185,7 @@ test "ranked choices and prose retain their supplied order" { } } -test "reference Look selects the next sorted row from the captured request and keeps navigation there" { +test "references fill the asking text's query pane: sorted under their files, the next after where it was asked current, the owner's places the refs in it" { if (!pardes.lsp.supports.contains(.references)) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -194,53 +194,38 @@ test "reference Look selects the next sorted row from the captured request and k try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "z.zig", .data = "z\n" }); var path_buf: [256]u8 = undefined; const path = try std.fmt.bufPrint(&path_buf, ".zig-cache/tmp/{s}/m.zig", .{tmp.sub_path}); - const p = try Pardes.init(std.testing.allocator, .{ .file = path, .cols = 80, .rows = 24 }); + const p = try Pardes.init(std.testing.allocator, .{ .file = path, .cols = 80, .rows = 40 }); defer p.deinit(); - p.locations_config.layout = .@"inline"; const source = p.panes[0].?; const response = "m.zig:5:5-8 later\nz.zig:1:1 last-file\nm.zig:1:7-10 earlier\nm.zig:3:5-8 current\na.zig:1:1 first-file\nm.zig:4:5-8 next\n"; - const sorted = "a.zig:1:1 first-file\nm.zig:1:7-10 earlier\nm.zig:3:5-8 current\nm.zig:4:5-8 next\nm.zig:5:5-8 later\nz.zig:1:1 last-file\n"; source.body.cur_row = 2; source.body.cur_col = 4; p.lspRequest(0, .references, ""); const request = p.lsp_wait.?.id; + // the cursor moves before the answer: it is placed by where it was asked source.body.cur_row = 4; p.lspResponse(request, response); - const rid = source.search_pane orelse return error.MissingResults; - const results = p.panes[rid].?; - try expectResultRows(sorted, &results.file.?); - try std.testing.expectEqual(@as(usize, 0), p.active); + const qid = panes.Query.ofOwner(p, source.serial) orelse return error.MissingResults; + const results = p.panes[qid].?; + const content = results.file.?.content; + try std.testing.expect(std.mem.startsWith(u8, content, "Refs \n")); + // under their files, in order + const a_at = std.mem.indexOf(u8, content, "\na.zig\n").?; + const m_at = std.mem.indexOf(u8, content, "\nm.zig\n").?; + const z_at = std.mem.indexOf(u8, content, "\nz.zig\n").?; + try std.testing.expect(a_at < m_at and m_at < z_at); + // the owner's places are its four refs; the current the one after line 3 + try std.testing.expectEqual(@as(usize, 4), source.places.hits.items.len); + try std.testing.expectEqual(@as(?usize, 2), source.places.current); try std.testing.expectEqual(@as(i32, 3), source.body.cur_row); - try std.testing.expect(source.body.vsel.active); - try std.testing.expectEqual(@as(i32, 4), @min(source.body.cur_col, source.body.vsel.col)); - try std.testing.expectEqual(@as(i32, 7), @max(source.body.cur_col, source.body.vsel.col)); - try std.testing.expectEqual(@as(i32, 3), results.body.cur_row); - try std.testing.expectEqual(@as(usize, 3), source.search_row.?); - try std.testing.expectEqual(results.serial, p.look_walk_owner.?); - try std.testing.expectEqual(@as(i32, 3), results.look_at.?.row); - const available = p.freeSlot(); - lookKey(p, 'n'); - try std.testing.expectEqual(rid, p.active); - try std.testing.expectEqual(@as(i32, 4), results.body.cur_row); - try std.testing.expectEqual(available, p.freeSlot()); - lookKey(p, 'N'); - try std.testing.expectEqual(@as(i32, 3), results.body.cur_row); - + try std.testing.expectEqual(@as(usize, 6), results.query.?.total); + // n in the owner steps them, round the end without a word p.active = 0; - source.body.cur_row = 4; - source.body.cur_col = 4; - p.lspRequest(0, .references, ""); - p.lspResponse(p.lsp_wait.?.id, response); - try std.testing.expect(std.mem.endsWith(u8, p.panes[p.active].?.file.?.path, "/z.zig")); - try std.testing.expectEqual(@as(i32, 5), results.body.cur_row); - try std.testing.expectEqual(@as(usize, 5), source.search_row.?); - const last = p.active; - p.lspRequest(last, .references, ""); - p.lspResponse(p.lsp_wait.?.id, response); - try std.testing.expect(std.mem.endsWith(u8, p.panes[p.active].?.file.?.path, "/a.zig")); - const wrapped = p.panes[p.panes[last].?.search_pane.?].?; - try std.testing.expectEqual(@as(i32, 0), wrapped.body.cur_row); - try std.testing.expectEqual(wrapped.serial, p.look_walk_owner.?); + p.update(.{ .key = .{ .cp = 'n' } }); + try std.testing.expectEqual(@as(?usize, 3), source.places.current); + p.update(.{ .key = .{ .cp = 'n' } }); + try std.testing.expectEqual(@as(?usize, 0), source.places.current); + try std.testing.expectEqual(@as(usize, 0), p.active); } test "location sorting leaves mixed prose alone and preserves newline shape" { -- cgit v1.3 From f3b5bd10ceb4c4db7263739770d5e4bdb879ba75 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 14:16:32 -0300 Subject: Search converge 7/6: a script's Grep or Find that misses opens nothing, a dumped query pane restores as plain text; fs.py's Recent and canary to the query pane --- src/File.zig | 5 ++++- src/Query.zig | 18 ++++++++++++++++++ src/builtins.zig | 18 +++++++++++------- src/ninep/ctl.zig | 9 +++++++++ test/fs.py | 13 ++++++++----- 5 files changed, 50 insertions(+), 13 deletions(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index f633cad0..24dc9318 100644 --- a/src/File.zig +++ b/src/File.zig @@ -244,7 +244,10 @@ pub fn dumpPane( .collapsed = pane.collapsed, .file = .{ .tree_context = file.tree_context, - .location_rows = try dumpLocationRows(arena, file.location_rows), + // A query pane's rows are its own (line 1 the query, gutter + // numbers), not location rows Restore reads: it comes back as + // plain text. + .location_rows = if (pane.query != null) &.{} else try dumpLocationRows(arena, file.location_rows), .path = file.path, .content_b64 = if (from_disk) "" else try dump.encodeBytes(arena, file.content), .dirty = dirty, diff --git a/src/Query.zig b/src/Query.zig index 6374ce42..a871b71e 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -1998,6 +1998,24 @@ test "a / query: keystroke by keystroke, the owner shows the set, rows from its try std.testing.expectEqual(@as(i32, 2), pane.body.cur_row); } +test "a dump holding a query pane, live or frozen, restores, the pane as plain text" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); + defer p.deinit(); + _ = try p.setTestFile("alpha one\nbeta\nalphabet\n"); + typeKeys(p, "/alpha"); + for (0..2) |_| { + const qid = queryPane(p).?; + try pardes.dump.dumpState(p); + const restored = try pardes.dump.initFromDump(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }, p.dump_out.?); + defer restored.deinit(); + const back = restored.panes[qid].?; + try std.testing.expect(back.query == null); + try std.testing.expectEqual(@as(usize, 0), back.file.?.location_rows.len); + try std.testing.expect(std.mem.startsWith(u8, back.file.?.content, "/alpha\n")); + p.update(.{ .key = .{ .cp = Key.enter } }); + } +} + test "a / query: Enter lands and freezes, the register filled, n and N step silently, a later / reuses the pane and Esc brings the frozen rows back" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 100, .rows = 40 }); defer p.deinit(); diff --git a/src/builtins.zig b/src/builtins.zig index cda962de..d2f215d7 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1720,8 +1720,9 @@ pub const Find = struct { // (SPC f f) typed into; with a word (B2, a script) listed, the // keyboard left where it was, a script told of a miss. const pat = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + const had = panes.Query.ofOwner(c.p, c.pane.serial) != null; panes.Query.open(c.p, c.id, .find, pat, pat.len == 0); - if (pat.len > 0) missed(c, e_search_miss_find); + if (pat.len > 0) missed(c, e_search_miss_find, had); } }; @@ -1733,19 +1734,22 @@ pub const Grep = struct { pub const output: OutputTraits = .{ .name = config.search_buffer, .steps = true, .locations = true }; pub fn run(c: Ctx) void { const pat = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + const had = panes.Query.ofOwner(c.p, c.pane.serial) != null; panes.Query.open(c.p, c.id, .grep, pat, pat.len == 0); - if (pat.len > 0) missed(c, e_search_miss_grep); + if (pat.len > 0) missed(c, e_search_miss_grep, had); } }; /// A script's Find or Grep (a 9P write runs it to its end before it -/// answers) that found nothing fails as one: the query pane stays, its -/// count 0, and the write hears `not found`. -fn missed(c: Ctx, text: []const u8) void { +/// answers) that found nothing fails as one, opening nothing: a query pane +/// it made goes as an Esc takes it, one it reused stays, its count 0; the +/// write hears `not found`. +fn missed(c: Ctx, text: []const u8, reused: bool) void { if (!c.p.fs.serving) return; const qid = panes.Query.ofOwner(c.p, c.pane.serial) orelse return; - const q = c.p.panes[qid].?.query.?; - if (q.total == 0) c.p.reportFailure(c.id, text); + if (c.p.panes[qid].?.query.?.total != 0) return; + if (!reused) panes.Query.cancel(c.p, qid); + c.p.reportFailure(c.id, text); } /// Search in a query pane under this pane, line 1 the argument (`Panes`, diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 635e03a6..258ea1ee 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -3069,6 +3069,15 @@ test "a script's Grep and Find fill the pane's one query pane, a row a line unde var after: usize = 0; for (p.panes) |slot| after += @intFromBool(slot != null); try testing.expectEqual(count, after); + // With no query pane under it, a miss leaves none: the one it made goes. + _ = wr(p, Node.of(found.serial, .ctl), "Del\n"); + var closed: usize = 0; + for (p.panes) |slot| closed += @intFromBool(slot != null); + try testing.expectEqual(E.NOENT, wr(p, Node.of(serialOf(p), .exec), "Find zzqqnomatchzz\n").errno()); + var left: usize = 0; + for (p.panes) |slot| left += @intFromBool(slot != null); + try testing.expectEqual(closed, left); + try testing.expect(panes.Query.ofOwner(p, serialOf(p)) == null); } test "Unmount of a name not mounted says no such mount, which a mount reads as ENOENT" { diff --git a/test/fs.py b/test/fs.py index 97af9e6b..841dd32a 100644 --- a/test/fs.py +++ b/test/fs.py @@ -715,10 +715,13 @@ def recent_survives_restart(binary): with session(binary, root, 'recent2') as (client, _): listed = client.read('/recent').decode() assert f'closed {kept}\n' in listed, listed - # Recent shows it, and a look at its row opens it again. + # Recent fills a query pane with it, its row relative to the + # pane's directory, and a look at the row opens it again. client.write('/pane/1/exec', b'Recent\n') rows = int(client.read('/pane/1/exec').split()[-1]) - row = next(r for r in client.read(f'/pane/{rows}/body').decode().splitlines() if r.startswith(f'{kept}:')) + body = client.read(f'/pane/{rows}/body').decode() + assert body.startswith('Recent '), body + row = next(r for r in body.splitlines() if r.startswith('kept.txt:')) client.write(f'/pane/{rows}/look', (row.split(' ')[0] + '\n').encode()) assert f'open {kept}\n' in client.read('/recent').decode() @@ -759,11 +762,11 @@ def workflow_canary(binary): assert client.read(f'/pane/{a}/body') == b'alpha one\nshared word\n' assert f'new {a} {root}/a.txt\n' in log() and f'new {b} {root}/b.txt\n' in log() - # Grep and Find: a hit opens its +Search, rows and all; a miss - # fails ENOENT, opening nothing. + # Grep and Find: a hit fills its query pane, line 1 the query and + # the lines under each file's name; a miss fails ENOENT. grep = made_by(a, b'Grep shared\n') rows = client.read(f'/pane/{grep}/body').decode() - assert 'a.txt:2' in rows and 'b.txt:2' in rows, rows + assert rows == 'Grep shared\na.txt\n 2 shared word\nb.txt\n 2 shared word\n', rows client.remove(f'/pane/{grep}') execute_refused(client, a, 'Grep zzqqnomatch', 'Grep: text not found') found = made_by(a, b'Find b.txt\n') -- cgit v1.3 From ce6ba3d8a9e1f5c1e31892639049317f6a27b1bc Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 13:59:21 -0300 Subject: 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 --- src/File.zig | 55 ++++- src/Tables.zig | 641 +++++++++++++++++++++++++++++++++++++++++++++++++++++ src/Text.zig | 26 ++- src/body_layer.zig | 22 +- src/edit.zig | 11 +- src/syntax.zig | 69 ++++++ 6 files changed, 813 insertions(+), 11 deletions(-) create mode 100644 src/Tables.zig (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index 24dc9318..ddf91af3 100644 --- a/src/File.zig +++ b/src/File.zig @@ -17,6 +17,7 @@ const dump = @import("dump.zig"); const limits = @import("memory.zig").limits; const locations = @import("locations.zig"); const Colors = @import("colors.zig"); +const Tables = @import("Tables.zig"); const Pane = panes.Pane; const Output = panes.Output; const Mini = panes.mini; @@ -201,6 +202,9 @@ pub const State = struct { /// helix's object_selections: what Alt-o grew from, for Alt-i to go back /// to; gpa-owned ranges and the primary's index. node_history: std.ArrayList(NodeStep) = .empty, + /// A markdown text's pipe tables, laid out in their rows (Tables.zig): + /// found again on the first body drawn after an edit. + tables: Tables = .{}, history: *History, /// Zerox's group: the panes on one buffer share `content`, `history` /// and (while it is the one index) `line_starts`, each with its own @@ -577,20 +581,41 @@ test "indexed source rows match uncached scans across content changes" { } } +/// The pads `row` is laid out with in this pane: a row of a markdown +/// table (Tables.zig) of its text as it is now, when the table fits the +/// width a wrapping body has (a wider one is shown as its source, wrapped); +/// else none. Every mapping between a file row's bytes and its cells goes +/// through here, so the drawn row, the caret and a click cannot disagree. +pub fn rowPads(pane: *const Pane, row: i32, out: *[Tables.max_pads]Tables.Pad) []const Tables.Pad { + const f = if (pane.file) |*file| file else return &.{}; + if (row < 0 or f.tables.list.items.len == 0 or !f.tables.current(f)) return &.{}; + const table = f.tables.find(@intCast(row)) orelse return &.{}; + const width = wrapWidth(pane, pane.body_wrapped); + if (width > 0 and table.width > width) return &.{}; + return f.tables.padsOf(table, sourceLine(pane, row), out); +} + pub fn displayOffset(pane: *const Pane, row: i32, from_raw: i32, to_raw: i32) i32 { const line_text = sourceLine(pane, row); const from: usize = @intCast(@max(0, from_raw)); const to: usize = @intCast(@max(0, to_raw)); - return lineDisplayOffset(line_text, from, to); + var buf: [Tables.max_pads]Tables.Pad = undefined; + return lineDisplayOffset(line_text, from, to) + Tables.between(rowPads(pane, row, &buf), from, to); } pub fn displayEndOffset(pane: *const Pane, row: i32, from_raw: i32, at_raw: i32) i32 { const line_text = sourceLine(pane, row); - return lineDisplayEndOffset(line_text, @intCast(@max(0, from_raw)), @intCast(@max(0, at_raw))); + const from: usize = @intCast(@max(0, from_raw)); + const at: usize = @intCast(@max(0, at_raw)); + var buf: [Tables.max_pads]Tables.Pad = undefined; + return lineDisplayEndOffset(line_text, from, at) + Tables.between(rowPads(pane, row, &buf), from, at); } pub fn byteAtRowDisplay(pane: *const Pane, row: i32, from_raw: i32, display_col: i32) i32 { const line_text = sourceLine(pane, row); + var buf: [Tables.max_pads]Tables.Pad = undefined; + const pads = rowPads(pane, row, &buf); + if (pads.len > 0) return @intCast(Tables.byteAt(line_text, pads, @intCast(@max(0, from_raw)), @intCast(@max(0, display_col)))); return @intCast(byteAtDisplayFrom(line_text, @intCast(@max(0, from_raw)), @intCast(@max(0, display_col)))); } @@ -1130,6 +1155,7 @@ pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { if (file.node_tree) |tree| syntax.freeTree(tree); for (file.node_history.items) |step| p.gpa.free(step.ranges); file.node_history.deinit(p.gpa); + file.tables.deinit(p.gpa); if (ntwins > 0) return; file.history.destroy(p.gpa); } @@ -1768,6 +1794,7 @@ pub fn visualRow(line: []const u8, col: usize, width: usize) VisualRow { pub fn bodyText(arena: std.mem.Allocator, pane: *Pane, f: *State, wrap: bool) ![]const u8 { const width = wrapWidth(pane, wrap); pane.body_wrapped = width > 0; + f.tables.ensure(pane.gpa, f); prepareContextRows(pane, f); pane.wrap_n = 0; @@ -1834,7 +1861,20 @@ fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) written += prefix.len; if (dst) |out| @memcpy(out[written..][0..guide.len], guide); written += guide.len; - const shown = text[cut..end]; + // A table row's pads are blanks before their bytes: the row + // drawn as the column functions above measure it. + var pad_buf: [Tables.max_pads]Tables.Pad = undefined; + var from = cut; + for (rowPads(pane, @intCast(row), &pad_buf)) |table_pad| { + if (table_pad.at <= cut) continue; + if (table_pad.at > end) break; + if (dst) |out| @memcpy(out[written..][0 .. table_pad.at - from], text[from..table_pad.at]); + written += table_pad.at - from; + if (dst) |out| @memset(out[written..][0..table_pad.cells], ' '); + written += table_pad.cells; + from = table_pad.at; + } + const shown = text[from..end]; if (dst) |out| @memcpy(out[written..][0..shown.len], shown); written += shown.len; } @@ -2029,7 +2069,16 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. s.at(tx + @as(u16, @intCast(prefix_width + col)), body_y + vr).style.fg = .{ .rgb = p.bodyChrome().diagnostic_info }; } var screen_c: usize = pad; + var table_buf: [Tables.max_pads]Tables.Pad = undefined; + const table_pads = rowPads(pane, @intCast(row_index), &table_buf); + var table_at: usize = 0; while (hs + c < limit and prefix_width + screen_c < tw) { + while (table_at < table_pads.len and table_pads[table_at].at < hs + c) table_at += 1; + if (table_at < table_pads.len and table_pads[table_at].at == hs + c and hs + c > hs) { + screen_c += table_pads[table_at].cells; + table_at += 1; + if (prefix_width + screen_c >= tw) break; + } const grapheme_end = @min(limit, modal.nextGrapheme(line, hs + c)); const cells = graphemeDisplayWidth(line[hs + c .. grapheme_end]); const idx = base + hs + c; 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)); +} diff --git a/src/Text.zig b/src/Text.zig index 88630f83..b57c953a 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -514,17 +514,33 @@ pub fn findMove(t: *Text, text: []const u8, range: modal.Selection, ch: u21, fwd setRange(t, text, 0, res, false); } +/// The file pane whose text `text` is, when `t` is its body: its rows are +/// measured through their table pads (File.rowPads), so j and k keep the +/// column a table shows, not the one its source has. +fn filePane(t: *Text, text: []const u8) ?*const Pane { + if (t.what != .body) return null; + const fp = t.pane() orelse return null; + const f = if (fp.file) |*file| file else return null; + return if (f.content.ptr == text.ptr and f.content.len == text.len) fp else null; +} + /// j/k and friends: sticky goal column, clamped onto short lines' newline pub fn verticalMove(t: *Text, text: []const u8, range: modal.Selection, down: bool, cnt: usize) void { const cur = modal.selectionCursor(text, range); const pos = File.textPosition(t, text, cur); + const shown = filePane(t, text); const goal: usize = if (t.sticky_col >= 0) @intCast(t.sticky_col) + else if (shown) |fp| + @intCast(@max(0, File.displayOffset(fp, @intCast(pos.row), 0, @intCast(pos.col)))) else File.rawDisplayCol(File.textLine(t, text, pos.row), pos.col); const last_row = File.textLineCount(t, text) - 1; const nline = if (down) @min(pos.row + @max(1, cnt), last_row) else pos.row -| @max(1, cnt); - const target_col = File.rawAtDisplay(File.textLine(t, text, nline), goal); + const target_col: usize = if (shown) |fp| + @intCast(File.byteAtRowDisplay(fp, @intCast(nline), 0, @intCast(@min(goal, std.math.maxInt(i32))))) + else + File.rawAtDisplay(File.textLine(t, text, nline), goal); const target = File.textOffset(t, text, .{ .row = nline, .col = target_col }); // extend mode never walks onto the empty trailing line (helix) if (t.select and target == text.len and text.len > 0 and text[text.len - 1] == '\n') return; @@ -546,8 +562,11 @@ pub fn visualMove( var row = pos.row; var line = modal.lineSlice(text, row); var vrow = File.visualRow(line, pos.col, width); + const shown = filePane(t, text); const goal: usize = if (t.sticky_col >= 0) @intCast(t.sticky_col) + else if (shown) |fp| + @intCast(@max(0, File.displayOffset(fp, @intCast(row), @intCast(vrow.start), @intCast(pos.col)))) else File.rawDisplayCol(line[vrow.start..vrow.end], pos.col -| vrow.start); var steps = @max(1, cnt); @@ -574,7 +593,10 @@ pub fn visualMove( } // The newline slot is a real cursor position, but the first byte of the // NEXT visual row is not: landing there would read as two rows moved. - var target_col = vrow.start + File.rawAtDisplay(line[vrow.start..vrow.end], goal); + var target_col: usize = if (shown) |fp| + @intCast(File.byteAtRowDisplay(fp, @intCast(row), @intCast(vrow.start), @intCast(@min(goal, std.math.maxInt(i32))))) + else + vrow.start + File.rawAtDisplay(line[vrow.start..vrow.end], goal); if (vrow.end < line.len and target_col >= vrow.end) target_col = modal.graphemeStart(line, vrow.end - 1); const target = File.textOffset(t, text, .{ .row = row, .col = target_col }); diff --git a/src/body_layer.zig b/src/body_layer.zig index e50b7e3e..90622e52 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -73,7 +73,9 @@ fn pastView(pane: *Pane, body: []const u8, line: i32, row: i32, at: i32, col: i3 const from: usize = @intCast(@max(0, at)); const to: usize = @intCast(@max(0, col)); if (from >= text.len) return to >= from +| tw; - return to >= from + panes.File.byteAtDisplay(text[from..], tw) and to < text.len; + // A file row's last shown byte counts its table pads (File.rowPads). + const shown: usize = if (pane.file != null) @intCast(panes.File.byteAtRowDisplay(pane, line, at, tw)) else from + panes.File.byteAtDisplay(text[from..], tw); + return to >= shown and to < text.len; } fn paintSourceSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: []const Pane.PointerRow, bg: [3]u8, fg: ?[3]u8) void { @@ -95,8 +97,15 @@ fn paintSourceSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: []c const lo = @max(start, row.lo); const hi = @min(end, row.hi); if (lo >= hi) continue; - const col = prefix + source.pad + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], lo - start))); - const last = @min(width, if (row.to_edge and hi == end) @as(i32, width) else prefix + source.pad + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], hi - start)))); + // A file row through its pads (File.rowPads), as it is drawn. + const col = prefix + source.pad + if (pane.file != null) + panes.File.displayOffset(pane, source.line, @intCast(start), @intCast(lo)) + else + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], lo - start))); + const last = @min(width, if (row.to_edge and hi == end) @as(i32, width) else prefix + source.pad + if (pane.file != null) + panes.File.displayOffset(pane, source.line, @intCast(start), @intCast(hi)) + else + @as(i32, @intCast(panes.File.rawDisplayCol(line[start..], hi - start)))); if (col < last) s.tint(tx + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(visible)), @intCast(last - col), bg, fg); } } @@ -361,7 +370,12 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane // The byte past the row's last column, walked from its first: // bounded by the view, not the line. // A line that ends inside the view has no column past it. - const shown_to = if (row_at >= row_text.len) row_text.len else row_at + panes.File.byteAtDisplay(row_text[row_at..], tw); + const shown_to = if (row_at >= row_text.len) + row_text.len + else if (pane.file != null) + @as(usize, @intCast(panes.File.byteAtRowDisplay(pane, w.line, w.at, tw))) + else + row_at + panes.File.byteAtDisplay(row_text[row_at..], tw); const past_view = if (shown_to >= row_text.len) std.math.maxInt(usize) else shown_to; // A row that ends before the selection starts has none of it. if (w.line == bnd.lo_row and @as(usize, @intCast(@max(0, bnd.lo_col))) >= past_view) continue; diff --git a/src/edit.zig b/src/edit.zig index a06f5f2d..74dd0d1d 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -250,8 +250,15 @@ pub fn capturePointerSelection(p: *Pardes, pane: *Pane, slot: usize) !void { if (raw) next = .{ .line = source.line + 1, .at = 0 }; const end = if (next.line == source.line) @min(line.len, @as(usize, @intCast(@max(0, next.at)))) else line.len; const start: usize = @intCast(@max(0, source.at)); - const lo = @min(end, panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, left - prefix - source.pad)))); - const at = @min(end, panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, right - prefix - source.pad)))); + // A file row through its table pads (File.rowPads), as it is drawn. + const lo: usize = @min(end, if (pane.file != null and !raw) + @as(usize, @intCast(panes.File.byteAtRowDisplay(pane, source.line, source.at, @max(0, left - prefix - source.pad)))) + else + panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, left - prefix - source.pad)))); + const at: usize = @min(end, if (pane.file != null and !raw) + @as(usize, @intCast(panes.File.byteAtRowDisplay(pane, source.line, source.at, @max(0, right - prefix - source.pad)))) + else + panes.File.byteAtDisplayFrom(line, start, @intCast(@max(0, right - prefix - source.pad)))); row.* = .{ .row = source.line, .lo = lo, diff --git a/src/syntax.zig b/src/syntax.zig index 81722ce5..aca2c3ff 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -2003,3 +2003,72 @@ test "syntax source analysis preserves declarations and injected colors" { try std.testing.expectEqual(@as(usize, 0), unsupported.declarations.len); try std.testing.expectEqual(@as(usize, 0), unsupported.colors.len); } + +test "tables are the pipe_tables tree-sitter finds" { + if (!enabled or !full_grammars) return; + start(std.testing.allocator); + defer stop(); + const Tables = @import("Tables.zig"); + const source = + "# Tables\n" ++ + "\n" ++ + "| a | b |\n" ++ + "|---|:-:|\n" ++ + "| 1 | 2 |\n" ++ + "no pipe row\n" ++ + "\n" ++ + "a | b\n" ++ + "--|--\n" ++ + "c | d\n" ++ + "# heading ends it\n" ++ + "| x |\n" ++ + "|---|\n" ++ + "\n" ++ + "```\n" ++ + "| in | fence |\n" ++ + "|----|-------|\n" ++ + "```\n" ++ + "\n" ++ + "| one | two |\n" ++ + "|-----|\n" ++ + "\n" ++ + " | indented | table |\n" ++ + " | -------- | ----- |\n" ++ + " | row | here |\n" ++ + "> quote ends\n" ++ + "\n" ++ + "| esc \\| aped | two |\n" ++ + "| --- | --- |\n" ++ + "- list ends\n"; + const selected = (try forLang("markdown")).?; + const tree = selected.parser.parseString(source, null) orelse return error.ParseFailed; + defer tree.destroy(); + // Every pipe_table node's lines, wherever it is in the tree. + var found: std.ArrayList([2]u32) = .empty; + defer found.deinit(std.testing.allocator); + var stack: std.ArrayList(ts.Node) = .empty; + defer stack.deinit(std.testing.allocator); + try stack.append(std.testing.allocator, tree.rootNode()); + while (stack.pop()) |node| { + if (std.mem.eql(u8, node.kind(), "pipe_table")) { + const end = node.endPoint(); + try found.append(std.testing.allocator, .{ node.startPoint().row, end.row + @intFromBool(end.column > 0) }); + continue; + } + var i = node.childCount(); + while (i > 0) : (i -= 1) if (node.child(i - 1)) |child| try stack.append(std.testing.allocator, child); + } + // The tables, the indented one and the escaped pipe's; not the fence's + // or the one whose delimiter has a cell too few. + try std.testing.expectEqual(@as(usize, 5), found.items.len); + var t: Tables = .{}; + defer t.deinit(std.testing.allocator); + try t.scan(std.testing.allocator, source); + var mine: std.ArrayList([2]u32) = .empty; + defer mine.deinit(std.testing.allocator); + for (t.list.items) |table| try mine.append(std.testing.allocator, .{ table.first, table.end }); + std.testing.expectEqualSlices([2]u32, found.items, mine.items) catch |e| { + std.debug.print("tree-sitter {any}\nTables {any}\n", .{ found.items, mine.items }); + return e; + }; +} -- cgit v1.3 From 8f5871340b87a0d5399967ccc7eac0d12dc10821 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 14:05:34 -0300 Subject: Tables 2/3: the look, a table's pipes drawn as rules, its delimiter row one rule with its colons kept, its header bold on the tag's ground (glyphs and colours on the cells there, nothing moved); the GUI draws light box-drawing rules edge to edge so they join across rows --- src/File.zig | 16 +++++--- src/Tables.zig | 118 ++++++++++++++++++++++++++++++++++++++++++++++++++++- src/body_layer.zig | 1 + src/gui/gui.zig | 72 +++++++++++++++++++++++++++++++- src/panes.zig | 1 + 5 files changed, 199 insertions(+), 9 deletions(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index ddf91af3..5db04443 100644 --- a/src/File.zig +++ b/src/File.zig @@ -587,12 +587,18 @@ test "indexed source rows match uncached scans across content changes" { /// else none. Every mapping between a file row's bytes and its cells goes /// through here, so the drawn row, the caret and a click cannot disagree. pub fn rowPads(pane: *const Pane, row: i32, out: *[Tables.max_pads]Tables.Pad) []const Tables.Pad { - const f = if (pane.file) |*file| file else return &.{}; - if (row < 0 or f.tables.list.items.len == 0 or !f.tables.current(f)) return &.{}; - const table = f.tables.find(@intCast(row)) orelse return &.{}; + const table = rowTable(pane, row) orelse return &.{}; + return pane.file.?.tables.padsOf(table, sourceLine(pane, row), out); +} + +/// The table `row` is laid out in, in this pane (`rowPads`). +pub fn rowTable(pane: *const Pane, row: i32) ?*const Tables.Table { + const f = if (pane.file) |*file| file else return null; + if (row < 0 or f.tables.list.items.len == 0 or !f.tables.current(f)) return null; + const table = f.tables.find(@intCast(row)) orelse return null; const width = wrapWidth(pane, pane.body_wrapped); - if (width > 0 and table.width > width) return &.{}; - return f.tables.padsOf(table, sourceLine(pane, row), out); + if (width > 0 and table.width > width) return null; + return table; } pub fn displayOffset(pane: *const Pane, row: i32, from_raw: i32, to_raw: i32) i32 { diff --git a/src/Tables.zig b/src/Tables.zig index ca4a4b57..8038dd65 100644 --- a/src/Tables.zig +++ b/src/Tables.zig @@ -31,7 +31,10 @@ const std = @import("std"); const panes = @import("panes.zig"); const pardes = @import("pardes.zig"); const colors = @import("colors.zig"); +const modal = @import("modal.zig"); const Surface = @import("surface.zig").Surface; +const Cell = @import("surface.zig").Cell; +const Color = @import("surface.zig").Color; const Pardes = pardes.Pardes; const Pane = panes.Pane; const File = panes.File; @@ -448,7 +451,7 @@ pub fn between(pads: []const Pad, from: usize, to: usize) i32 { /// 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 at = modal.graphemeStart(text, from_raw); var k: usize = 0; while (k < pads.len and pads[k].at <= at) k += 1; var used: usize = 0; @@ -458,7 +461,7 @@ pub fn byteAt(text: []const u8, pads: []const Pad, from_raw: usize, col: usize) k += 1; if (col < used) return at; } - const end = @import("modal.zig").nextGrapheme(text, at); + const end = modal.nextGrapheme(text, at); used += File.graphemeDisplayWidth(text[at..end]); if (col < used) return at; at = end; @@ -466,6 +469,101 @@ pub fn byteAt(text: []const u8, pads: []const Pad, from_raw: usize, col: usize) return text.len + (col - used); } +/// What a table's `|` and its delimiter row are drawn as: light box-drawing +/// rules, each one cell, as the glyph of the byte that is there. +const rule_v = "\u{2502}"; +const rule_h = "\u{2500}"; +const rule_cross = "\u{253c}"; +const rule_left = "\u{251c}"; +const rule_right = "\u{2524}"; + +fn glyph(cell: *Cell, g: []const u8) void { + cell.default = false; + @memcpy(cell.text[0..g.len], g); + cell.len = @intCast(g.len); +} + +/// A pane's table rows drawn as tables: every unescaped `|` a rule, the +/// delimiter row one rule across (its dashes, its blanks and its pads, its +/// `:` kept in the rule's colour, since they say the alignment), the header +/// row bold on the tag's ground, as compact context rows are. Only glyphs +/// and colours change, on the cells the row has: where each byte is and how +/// wide is fillBody's, so nothing is drawn over anything, B1 on a rule is +/// B1 on its `|`, and a selection's tint lies over the rules as over text. +pub fn paint(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void { + const f = if (pane.file) |*file| file else return; + if (f.tables.list.items.len == 0) return; + const th = p.theme(); + const tint = p.settings.colors; + const rule_fg: Color = .{ .rgb = th.border orelse th.lineno }; + const head_bg: Color = .{ .rgb = th.tag_bg }; + const prefix: usize = File.gutterWidth(pane); + const body_y = p.bodyTop(pane, r); + var vr: u16 = 0; + while (vr < body_h) : (vr += 1) { + const w = pane.wrapAt(vr); + const table = File.rowTable(pane, w.line) orelse continue; + const text = File.sourceLine(pane, w.line); + var buf: [max_pads]Pad = undefined; + const pads = f.tables.padsOf(table, text, &buf); + const pipes = Pipes.of(text); + const delimiter = w.line == table.first + 1; + const header = w.line == table.first; + const y = body_y + vr; + // The row's walk, as fillBody lays it out from its first shown byte. + var at = modal.graphemeStart(text, @min(@as(usize, @intCast(@max(0, w.at))), text.len)); + var col: usize = prefix + @as(usize, @intCast(w.pad)); + var k: usize = 0; + while (k < pads.len and pads[k].at <= at) k += 1; + var q: usize = 0; + while (q < pipes.n and pipes.at[q] < at) q += 1; + while (at < text.len and col < tw) { + if (k < pads.len and pads[k].at == at) { + for (0..pads[k].cells) |i| { + if (col + i >= tw) break; + const cell = s.at(tx + @as(u16, @intCast(col + i)), y); + if (delimiter) { + glyph(cell, rule_h); + if (tint) cell.style.fg = rule_fg; + } + if (header and tint) cell.style.bg = head_bg; + } + col += pads[k].cells; + k += 1; + if (col >= tw) break; + } + const end = modal.nextGrapheme(text, at); + const cells = File.graphemeDisplayWidth(text[at..end]); + const cell = s.at(tx + @as(u16, @intCast(col)), y); + const pipe = q < pipes.n and pipes.at[q] == at; + if (pipe) { + q += 1; + glyph(cell, if (!delimiter) + rule_v + else if (q == 1 and pipes.leading) + rule_left + else if (q == pipes.n and pipes.trailing) + rule_right + else + rule_cross); + if (tint) cell.style.fg = rule_fg; + cell.style.bold = false; + } else if (delimiter) { + if (text[at] == '-' or text[at] == ' ') glyph(cell, rule_h); + if (tint) cell.style.fg = rule_fg; + } else if (header) { + cell.default = false; + cell.style.bold = true; + } + if (header and tint) for (0..cells) |i| { + if (col + i < tw) s.at(tx + @as(u16, @intCast(col + i)), y).style.bg = head_bg; + }; + col += cells; + at = end; + } + } +} + // ---- tests ---- const testing = std.testing; @@ -578,6 +676,22 @@ test "tables: a markdown table is drawn aligned, its bytes in order, the caret a } } try testing.expectEqual(@as(u16, 1 + 7 + 1 + 5 + 1 + 17), pipe_x[3].? - text_x); + // The look: each `|` a rule; the delimiter row one rule across, its + // `:` kept; the header bold. The bytes under them are the source's. + const rule_y = body_y + 3; + var x = text_x; + while (x <= pipe_x[3].?) : (x += 1) { + const g = p.surface.at(x, rule_y).grapheme(); + try testing.expect(std.mem.eql(u8, g, rule_h) or std.mem.eql(u8, g, rule_cross) or + std.mem.eql(u8, g, rule_left) or std.mem.eql(u8, g, rule_right) or std.mem.eql(u8, g, ":")); + } + try testing.expectEqualStrings(rule_left, p.surface.at(pipe_x[0].?, rule_y).grapheme()); + try testing.expectEqualStrings(rule_cross, p.surface.at(pipe_x[1].?, rule_y).grapheme()); + try testing.expectEqualStrings(rule_right, p.surface.at(pipe_x[3].?, rule_y).grapheme()); + try testing.expectEqualStrings(rule_v, p.surface.at(pipe_x[2].?, body_y + 4).grapheme()); + try testing.expect(p.surface.at(text_x + 2, body_y + 2).style.bold); + try testing.expect(!p.surface.at(text_x + 2, body_y + 4).style.bold); + try testing.expectEqualStrings("| name | qty | note |", File.sourceLine(pane, 2)); // 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; diff --git a/src/body_layer.zig b/src/body_layer.zig index 90622e52..3684605f 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -282,6 +282,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane panes.File.drawGutter(p, s, pane, r, tx, tw, body_h, active); if (p.settings.colors and pane.colorAlgo() != .none) panes.File.recolorSyntax(p, s, pane, f, r, tx, tw, body_h); + panes.Tables.paint(p, s, pane, r, tx, tw, body_h); panes.File.drawWrapMarkers(p, s, pane, r, tx, tw, body_h, pane_bg); pane.places.paint(p, s, pane, r, body_h); panes.Query.paint(p, s, pane, r, body_h); diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 49a98f5b..d71f7047 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -105,9 +105,52 @@ const GlyphKey = packed struct(u64) { centered: bool = false, lead: u4 = 0, span: u4 = 1, - _: u2 = 0, + /// A light box-drawing rule (`ruleArms`), drawn edge to edge rather + /// than from the font; `glyph` is its codepoint. + rule: bool = false, + _: u1 = 0, }; +/// The light box-drawing rules drawn by hand, as Ghostty and kitty draw +/// them: a logical pixel thick through the cell's middle, out to its edges, +/// so a markdown table's `|` (Tables.zig) joins the rows above and below it +/// and its delimiter row is one line across, at any line height a font's +/// own glyph would leave gaps in. The arms each one has: left, right, up, down. +fn ruleArms(cp: u32) ?[4]bool { + return switch (cp) { + 0x2500 => .{ true, true, false, false }, // ─ + 0x2502 => .{ false, false, true, true }, // │ + 0x250c => .{ false, true, false, true }, // ┌ + 0x2510 => .{ true, false, false, true }, // ┐ + 0x2514 => .{ false, true, true, false }, // └ + 0x2518 => .{ true, false, true, false }, // ┘ + 0x251c => .{ false, true, true, true }, // ├ + 0x2524 => .{ true, false, true, true }, // ┤ + 0x252c => .{ true, true, false, true }, // ┬ + 0x2534 => .{ true, true, true, false }, // ┴ + 0x253c => .{ true, true, true, true }, // ┼ + else => null, + }; +} + +fn drawRule(out: [*]u8, stride: usize, width: usize, height: usize, arms: [4]bool) void { + if (width == 0 or height == 0) return; + const t: usize = @min(@max(1, @as(usize, @intFromFloat(dp(1)))), @min(width, height)); + const mx = (width - t) / 2; + const my = (height - t) / 2; + for (0..height) |y| @memset(out[y * stride ..][0..width], 0); + if (arms[0] or arms[1]) for (0..t) |k| { + const from: usize = if (arms[0]) 0 else mx; + const to: usize = if (arms[1]) width else mx + t; + @memset(out[(my + k) * stride + from ..][0 .. to - from], 255); + }; + if (arms[2] or arms[3]) { + const from: usize = if (arms[2]) 0 else my; + const to: usize = if (arms[3]) height else my + t; + for (from..to) |y| @memset(out[y * stride + mx ..][0..t], 255); + } +} + const GlyphDecoration = packed struct(u5) { bold: bool = false, underline: @FieldType(pardes.CellStyle, "ul") = .off, @@ -7314,6 +7357,8 @@ fn wordCell(cell: *const pardes.Cell) WordCell { /// cell tints its own slice. fn wordBreak(a: WordCell, b: WordCell, i: usize, cursor: ?usize) bool { if (a.cp == ' ' or b.cp == ' ') return true; + // A rule is drawn by hand (ruleArms), never a slice of a shaped word. + if (ruleArms(a.cp) != null or ruleArms(b.cp) != null) return true; if (cursor) |at| if (at == i or at == i + 1) return true; if (a.role != b.role or !std.meta.eql(a.decoration, b.decoration)) return true; return (a.cp == 'f' and (b.cp == 'i' or b.cp == 'l')) or (a.cp == 's' and b.cp == 't'); @@ -7334,6 +7379,8 @@ fn cellSlot(g: *Gui, line: []const pardes.Cell, at: usize, cursor: ?usize, role: var here = wordCell(&line[at]); // An underlined or struck-out space is a glyph of its own: it draws its line. if (here.cp == ' ' and !here.decoration.drawsBlank()) return g.space_slot; + if (ruleArms(here.cp) != null) + return cachedGlyph(g, .{ .face = 0, .glyph = here.cp, .role = role, .rule = true }) orelse g.space_slot; const gpa = g.glyphs.allocator; const cell_key: Words.CellKey = .{ .cp = @intCast(here.cp), .role = role, .decoration = here.decoration }; const known = words.cells.getOrPut(gpa, cell_key) catch return g.space_slot; @@ -7589,7 +7636,9 @@ fn cachedGlyph(g: *Gui, key: GlyphKey) ?Slot { const raster_w = if (key.centered) slot_w else cell_w * key.span; const raster_h = if (key.role == .tagline) g.tagline_height else g.cell_h; const bold = @intFromBool(key.decoration.bold); - if (key.centered) { + if (key.rule) { + drawRule(out, atlas_w, raster_w, raster_h, ruleArms(key.glyph).?); + } else if (key.centered) { _ = c.ui_font_raster_centered(face, px, key.glyph, bold, out, @intCast(atlas_w), @intCast(raster_w), @intCast(raster_h)); } else { _ = c.ui_font_raster(face, px, key.glyph, bold, out, @intCast(atlas_w), @intCast(raster_w), @intCast(raster_h), @intCast(cell_w * key.lead), @intCast(cell_w), baseline); @@ -7764,6 +7813,25 @@ fn decorateLine(out: [*]u8, stride: usize, width: usize, height: usize, baseline } } +test "a box-drawing rule reaches its cell's edges, and only its arms do" { + const stride = 12; + const width = 9; + const height = 15; + var mask: [stride * height]u8 = @splat(0xa5); + drawRule(&mask, stride, width, height, ruleArms(0x253c).?); + // ┼: ink on all four edges, none in the corners, nothing past the slot. + try std.testing.expectEqual(@as(u8, 255), mask[0 * stride + width / 2]); + try std.testing.expectEqual(@as(u8, 255), mask[(height - 1) * stride + width / 2]); + try std.testing.expectEqual(@as(u8, 255), mask[(height / 2) * stride]); + try std.testing.expectEqual(@as(u8, 255), mask[(height / 2) * stride + width - 1]); + try std.testing.expectEqual(@as(u8, 0), mask[0]); + for (0..height) |y| for (mask[y * stride + width ..][0 .. stride - width]) |guard| try std.testing.expectEqual(@as(u8, 0xa5), guard); + drawRule(&mask, stride, width, height, ruleArms(0x2502).?); + try std.testing.expectEqual(@as(u8, 0), mask[(height / 2) * stride]); + try std.testing.expectEqual(@as(u8, 255), mask[0 * stride + width / 2]); + try std.testing.expect(ruleArms('|') == null); +} + test "glyph decorations render spaces and stay inside their atlas slot" { const stride = 9; const width = 5; diff --git a/src/panes.zig b/src/panes.zig index 10e0d427..20618ccc 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -662,6 +662,7 @@ pub const File = @import("File.zig"); pub const Output = @import("Output.zig"); pub const Places = @import("Places.zig"); +pub const Tables = @import("Tables.zig"); pub const Query = @import("Query.zig"); -- cgit v1.3 From f4e295a0b61ae34e8abfd339eb1b6f658f8bf329 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 14:39:23 -0300 Subject: Tables 4/4: a delimiter cell's colons kept at its edges; a wide table shown as source in a wrapping pane, tested; docs/next-tables.md, the design as built, the numbers and the open questions --- docs/next-tables.md | 176 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/File.zig | 2 +- src/Tables.zig | 41 ++++++++++-- 3 files changed, 212 insertions(+), 7 deletions(-) create mode 100644 docs/next-tables.md (limited to 'src/File.zig') diff --git a/docs/next-tables.md b/docs/next-tables.md new file mode 100644 index 00000000..cc9e567c --- /dev/null +++ b/docs/next-tables.md @@ -0,0 +1,176 @@ +# Tables in markdown files, as built + +> Could we do special rendering for tables in markdown files? + +A GFM pipe table in a `.md` file is drawn as a table, in its own rows: every +column's `|` on one screen column whatever the source spacing, the `|` drawn +as rules, the delimiter row (`|:--|--:|`) drawn as one rule with its colons +kept, the header bold on the tag's ground. Every byte stays in its row as the +text it is: B1 selects it, B2/B3 take its words, the chords cut and paste it, +the caret sits on it, and nothing is drawn over anything. Editing a cell +re-aligns the table on the keystroke. + +## The one idea: a pad is a tab's extra cells + +The rows are not rewritten. A cell narrower than its column is given the +cells it lacks as **virtual width before one of its bytes** (a *pad*): before +the `|` that ends it (left), before its first byte (right), split (centred). +A pad is to its byte what a tab's extra cells are to the tab: drawn blank, +each of its cells maps back to that byte, and the caret before that byte is +drawn after the pad, against its glyph. So there is no parallel map: the +existing pane-aware column functions in `File.zig` add the pads, and so does +every walk that draws a file row. + +| where | what changed | +|---|---| +| `File.rowPads` / `rowTable` | the gate: a row of a table of the text as it is now, that fits the pane | +| `File.displayOffset`, `displayEndOffset`, `byteAtRowDisplay` | `+ Tables.between(pads)` / `Tables.byteAt` | +| `File.fillBody` | writes the pads as blanks into the body string (so `paneText`, `expandedSel`, the sweep text see the drawn row) | +| `File.recolorSyntax` | its screen walk steps over the pads | +| `body_layer` | pointer-selection tint and the view-edge checks through the pane-aware functions | +| `edit.capturePointerSelection` | a sweep's columns to bytes through `byteAtRowDisplay` | +| `Text.verticalMove` / `visualMove` | j/k keep the column the table shows (a body of a file pane only) | + +Everything else (mouse.zig, exec.zig's B2 cells, look.zig's cursor word, the +caret, multi-cursor tints, `gw` labels) already went through those three +functions and needed no change. That is the evidence the mapping is in one +place: the round-trip test clicks every cell of a row with pads of all three +kinds and checks the caret lands on the byte and is drawn where it is. + +## The look (`Tables.paint`) + +Glyphs and colours only, on the cells the row has, after the syntax colours: +`|` as `│`, the delimiter row as `├──┼──┤` (its `-`, blanks and pads as `─`, +its `:` in the rule colour), the header bold on `tag_bg` (the compact context +rows' ground: tables reuse a look the editor has). The rule colour is the +theme's `border`, else `lineno`. + +## Finding the tables + +tree-sitter-markdown here does expose `pipe_table` (header, delimiter row, +cells, alignments). I did not use the tree to find them: the highlighter +parses only the lines around the view (`refreshHighlights`, a fragment from +`scroll - slack`), which starts mid-table as soon as a long table is +scrolled, and a fence is only known from the top. So `Tables.zig` finds +tables by lines with the grammar's own rules (its scanner's +`PIPE_TABLE_START`: a header's cells counted by pipes, a `:?-+:?` delimiter +row of the same count with at least one pipe; rows until a blank line or a +block that interrupts a paragraph; escaped `\|`), and the grammar is the +**oracle in a test** (`tables are the pipe_tables tree-sitter finds`: five +tables including an indented one, a no-pipe continuation row and an escaped +pipe; the fenced one and the short-delimiter one not). + +## Cost (measured) + +`.scratch/stress-tables.md`: 2.7 MB, 54 508 lines, 2000 tables of 3-6 columns +and 10-30 rows, fences every 50 tables. Debug build, 160x50, each step +`update` + a full render, the same text as `.md` and as `.txt` +(`zz tables timings`, `TABLES_TIMES=`). + +| what | .md | .txt | +|---|---|---| +| a whole read of the tables (once, blocking, for comparison) | 127 ms | - | +| the first frame | 27 ms | 18 ms | +| frames until every table is read (4 ms a frame from the top) | 24 | - | +| `j` and its frame, in a table | 1.0 ms (worst 1.5) | 0.6 ms (0.9) | +| a letter typed in a cell and its frame | 3.2 ms (worst 8.5) | 2.0 ms (6.8) | + +The first version re-read the whole text on every edit: 119 ms a keystroke. +Two changes the numbers forced, both Places' patterns: + +- **An edit reflows**: the tables it did not touch shift by the lines it + added (`File.State.splice`), and only its block (blank line to blank line, + the touched tables taken in) is read again. A fence line in the edit, or + in what it replaced, reads everything (a fence changes every line after + it). A random 1500-edit test checks every result against a whole read; + more than 1000 took the short way. +- **Opening reads from the top a frame's budget at a time** (`Tables.frame_ns`, + `Pardes.nextWake` while `busy`): rows below the read point are drawn as + source until it gets there (a quarter second on this file). An edit past + the read point changes nothing read; one before it starts the read again. + +## GUI and tty + +Both draw the same grid: alignment, rules, header, the mapping are core. +What only the GUI does: the light box-drawing rules (`─│┌┐└┘├┤┬┴┼`) are drawn +by hand edge to edge (`gui.zig` `ruleArms`/`drawRule`, a `rule` bit in +`GlyphKey`, never a slice of a shaped word), so a table's `│` joins the rows +above and below at any line height and the delimiter row is one unbroken +line. In a terminal they are the terminal font's glyphs, which may leave gaps +between rows (the terminal's business). This applies to every box-drawing +cell in the GUI, terminal panes' TUIs too (as Ghostty and kitty do). + +Things only a GUI could do next, not done: pixel-thin rules between cells +rather than a cell-wide glyph (needs a cell decoration the surface does not +have); a half-cell inset so a rule does not take a whole column. + +## Rough + +- A table wider than a wrapping pane is shown as its source, wrapped (a + padded row must not wrap: wrapping is byte-fitted). `Wrap off` lays it out + again with hscroll. +- Inline markdown is not coloured inside cells: `syntax.inject` injects + `markdown_inline` into `inline` nodes, and `pipe_table_cell` is not one. +- A table in a blockquote or list item is not found (the line detector has + no container prefixes); tree-sitter finds it. +- Mixed leading pipes (`| a |` over `a |`) misalign by one cell; a leading + pipe's indentation is padded only when the pad is not at byte 0. +- Columns past 64 are not aligned. Zerox twins do not share the splice, so a + twin re-reads the whole text after an edit (sliced, so it still does not + hold a frame). +- The sweep-text fallback (`selectionText` without captured rows, a sweep + begun on the tag) reads the drawn row, so it would carry pad blanks; the + same is true of the callstack guide today. + +## Open questions, and my position on each + +1. **Hide redundant source spaces?** Position: no. Every byte stays visible; + only width is added, never taken. `| foo|` shows its two spaces. Hiding + bytes would make a click land on something you cannot see, which is the + constraint's spirit even if a space is "text". +2. **The glyph substitution: is drawing `|` as `│` drawing over text?** + Position: no; it is the byte's glyph, like a font ligature (which the GUI + already does), with the byte selectable, searchable, typed over. The + alternative, keeping `|` and only padding, is one constant away + (`rule_v`); I find the plain `|` reads as source, not as a table. +3. **Delimiter colons**: kept, in the rule colour, at the cell edges. The + alignment is visible anyway, but you edit them, so they must show. +4. **Rule colour**: `border` is faint on doom_one, especially the 1 px + horizontal rule. `lineno` or a mix toward `fg` would read better; a theme + field (`table_rule`) is the honest answer if you want it tunable. +5. **Wide tables**: source wrapped (now) versus clipped laid-out rows with + hscroll per table. Position: source; a clipped row hides text, and the + wrap is honest. A column could also be squeezed by wrapping a cell inside + it, but that is a virtual row, and virtual rows break the row = line + invariant everything here rests on. + +## Pushback + +- The NEXT brief says "check whether the grammar exposes pipe_table nodes and + use them if so". It does, and using them for detection would be worse here + (a view-local fragment parse starts mid-table; a whole-file parse is + ~seconds in Debug on the stress file, by converge's 4.8 s for 1.2 MB of + Zig). Using the grammar as the test oracle keeps its rules without its + cost. If a whole-file markdown tree ever exists (a worker parse, as + converge does for declarations), the detector could read it instead. +- Re-aligning live means a column widens under the caret as you type in its + widest cell, so the rest of the row moves right per keystroke. That is the + point of the feature, but it is motion in text you are not editing; a + `TableAlign off` setting may be wanted for heavy table editing. +- Making box-drawing rules procedural is a GUI-wide change (terminal TUIs + change look too). I think it is right (Ghostty, kitty, WezTerm all do it), + but it is a decision beyond tables. + +## Tests + +`zig build unit-test -Dplatform=gui -Dtest-filter="tables"`: +`tables: a pipe table's columns, alignments and pads, by line`; `...every +byte's cell maps back to it, and every pad cell to the byte after it`; `...is +drawn aligned, its bytes in order, the caret and a click on each byte's cell` +(also the look); `...typing in a cell re-aligns the table live, and j/k keep +the column shown`; `...an edit's tables, shifted and found again around it, +are the whole text's` (1500 random edits); `...a big text's tables are read +a frame's budget at a time`; `...wider than a wrapping pane is shown as its +source`; `tables are the pipe_tables tree-sitter finds` (syntax.zig); +`a box-drawing rule reaches its cell's edges` (gui.zig); `zz tables timings` +(skipped without `TABLES_TIMES`). No layout change, so no rects invariant. diff --git a/src/File.zig b/src/File.zig index 5db04443..cf44c69a 100644 --- a/src/File.zig +++ b/src/File.zig @@ -588,7 +588,7 @@ test "indexed source rows match uncached scans across content changes" { /// through here, so the drawn row, the caret and a click cannot disagree. pub fn rowPads(pane: *const Pane, row: i32, out: *[Tables.max_pads]Tables.Pad) []const Tables.Pad { const table = rowTable(pane, row) orelse return &.{}; - return pane.file.?.tables.padsOf(table, sourceLine(pane, row), out); + return pane.file.?.tables.padsOf(table, @intCast(row), sourceLine(pane, row), out); } /// The table `row` is laid out in, in this pane (`rowPads`). diff --git a/src/Tables.zig b/src/Tables.zig index 1dd296f7..2e65a716 100644 --- a/src/Tables.zig +++ b/src/Tables.zig @@ -594,7 +594,7 @@ fn add(t: *Tables, gpa: std.mem.Allocator, content: []const u8, header: Line, de 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; + for (t.padsOf(&table, r.n, 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); @@ -604,7 +604,7 @@ fn add(t: *Tables, gpa: std.mem.Allocator, content: []const u8, header: Line, de /// 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 { +pub fn padsOf(t: *const Tables, table: *const Table, line: usize, 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) { @@ -625,6 +625,17 @@ pub fn padsOf(t: *const Tables, table: *const Table, text: []const u8, out: *[ma // 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]; + // The delimiter row's cells keep their colons at their edges: the + // rule is drawn long between them (a pad before a closing `:`). + if (line == table.first + 1) { + var last = stop; + while (last > from and (text[last - 1] == ' ' or text[last - 1] == '\t')) last -= 1; + const at = if (last > from and text[last - 1] == ':') last - 1 else stop; + if (at == 0) continue; + out[n] = .{ .at = @intCast(at), .cells = missing }; + n += 1; + continue; + } const before: u16 = switch (how) { .left => 0, .right => missing, @@ -717,7 +728,7 @@ pub fn paint(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: const table = File.rowTable(pane, w.line) orelse continue; const text = File.sourceLine(pane, w.line); var buf: [max_pads]Pad = undefined; - const pads = f.tables.padsOf(table, text, &buf); + const pads = f.tables.padsOf(table, @intCast(w.line), text, &buf); const pipes = Pipes.of(text); const delimiter = w.line == table.first + 1; const header = w.line == table.first; @@ -818,11 +829,11 @@ test "tables: a pipe table's columns, alignments and pads, by line" { 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)); + }, t.padsOf(&table, 6, 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)); + }, t.padsOf(&table, 4, "| 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. @@ -847,7 +858,7 @@ test "tables: every byte's cell maps back to it, and every pad cell to the byte 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); + const pads = t.padsOf(table, n, text, &buf); var col: usize = 0; for (text, 0..) |_, b| { // The pad before b: each of its cells is b's. @@ -1054,6 +1065,24 @@ test "tables: a big text's tables are read a frame's budget at a time from the t } } +test "tables: a table wider than a wrapping pane is shown as its source, laid out again with Wrap off" { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 34, .rows = 24 }); + defer p.deinit(); + var frame = std.heap.ArenaAllocator.init(testing.allocator); + defer frame.deinit(); + const pane = try testPane(p, sample, frame.allocator()); + try testing.expect(pane.body_wrapped); + try testing.expect(File.wrapWidth(pane, true) < 34); + try testing.expect(File.rowTable(pane, 2) == null); + // Source: a pipe is a pipe, at its source column. + try testing.expectEqual(@as(i32, 7), File.displayOffset(pane, 5, 0, 7)); + try testing.expect(p.executeBuiltinLine(0, "Wrap off")); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + try testing.expect(!pane.body_wrapped); + try testing.expect(File.rowTable(pane, 2) != null); +} + test "zz tables timings on a big markdown file (TABLES_TIMES=)" { const path_z = std.c.getenv("TABLES_TIMES") orelse return error.SkipZigTest; const path = std.mem.span(path_z); -- cgit v1.3 From 0d3179f04a91c942fc10b0a05cdd6b8aa958d13e Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 14:38:19 -0300 Subject: anim 5: a scroll's colours are painted ahead on a worker (Stream.paintAhead), two views on the way it goes, so a page after a page parses nothing on the frame --- src/File.zig | 32 +++++++++ src/Stream.zig | 201 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ src/draw.zig | 23 +++++-- src/pardes.zig | 1 + src/syntax.zig | 49 ++++++++++++++ 5 files changed, 302 insertions(+), 4 deletions(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index cf44c69a..798e3e84 100644 --- a/src/File.zig +++ b/src/File.zig @@ -18,6 +18,7 @@ const limits = @import("memory.zig").limits; const locations = @import("locations.zig"); const Colors = @import("colors.zig"); const Tables = @import("Tables.zig"); +const Stream = @import("Stream.zig"); const Pane = panes.Pane; const Output = panes.Output; const Mini = panes.mini; @@ -1730,10 +1731,22 @@ pub fn refreshHighlights(p: *Pardes) void { need_end <= f.highlight_start + f.highlights.len) { f.syntax_dirty = false; + if (!f.tree_context and pane.colorAlgo() == .source) paintAhead(p, pane, f); continue; } const slack: usize = if (f.highlights.len == 0) 0 else pane.rows; const whole = pane.colorAlgo() == .locations or f.tree_context; + // Painted ahead on a worker (Stream.paintAhead): taken, no parse. + if (!whole and pane.colorAlgo() == .source) if (Stream.takeAhead(p, pane.serial, f.revision, need_start, need_end)) |got| { + if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); + f.highlights = got.styles; + f.highlight_start = got.start; + f.syntax_dirty = false; + p.stream.painted_ahead += 1; + paintAhead(p, pane, f); + continue; + }; + if (pane.colorAlgo() == .source and !whole) p.stream.painted_on_loop += 1; const start = if (whole) 0 else lineStart(p.gpa, f, f.scroll -| slack); const end = if (whole) f.content.len @@ -1755,9 +1768,28 @@ pub fn refreshHighlights(p: *Pardes) void { f.highlights = new_highlights; f.highlight_start = if (f.highlights.len > 0) start else 0; f.syntax_dirty = false; + if (!whole and pane.colorAlgo() == .source) paintAhead(p, pane, f); } } +/// The stretch a scroll of `pane` is heading into, two views on the way it +/// last went, asked of a worker (Stream.paintAhead) so it is painted by the +/// time the view gets there. +fn paintAhead(p: *Pardes, pane: *Pane, f: *State) void { + const seen = &p.stream.ahead_seen; + if (seen.serial == pane.serial and f.scroll != seen.scroll) seen.dir = if (f.scroll > seen.scroll) 1 else -1; + if (seen.serial != pane.serial) seen.dir = 1; + seen.serial = pane.serial; + seen.scroll = f.scroll; + const rows: usize = pane.rows; + const view = if (seen.dir > 0) f.scroll + 2 * rows else f.scroll -| 2 * rows; + const start = lineStart(p.gpa, f, view -| rows); + const end = @max(start, lineStart(p.gpa, f, view + 2 * rows + SYNTAX_CONTEXT_AFTER_ROWS)); + // Painted already, as far as that goes. + if (f.highlights.len > 0 and start >= f.highlight_start and end <= f.highlight_start + f.highlights.len) return; + Stream.paintAhead(p, pane.serial, f.revision, f.path, f.content, start, end); +} + pub fn supportsContext(pane: *const Pane) bool { const file = pane.file orelse return false; return file.output == null and file.mini == null and syntax.supportsPath(file.path); diff --git a/src/Stream.zig b/src/Stream.zig index eb420b42..ace73ca4 100644 --- a/src/Stream.zig +++ b/src/Stream.zig @@ -68,12 +68,17 @@ pub const Batch = struct { /// text at `revision`. parsed: ?struct { serial: u32, revision: u32 } = null, decls: []syntax.ContextDeclaration = &.{}, + /// A paint's answer (`paintAhead`): the colours of pane `serial`'s text + /// at `revision` from byte `start`, one syntax.Syn a byte. + painted: ?struct { serial: u32, revision: u32, start: usize } = null, + styles: []u8 = &.{}, pub const End = enum { done, failed }; pub fn deinit(b: *const Batch, gpa: std.mem.Allocator) void { gpa.free(b.rows); gpa.free(b.decls); + gpa.free(b.styles); } }; @@ -101,6 +106,41 @@ pub const ParseJob = struct { const ParseTask = struct { job: *ParseJob, future: ?std.Io.Future(void) = null, io: ?std.Io = null }; +/// The colours of the text a scroll is heading into, worked out on a +/// worker before it gets there, as a game streams in the level ahead of +/// the player: refreshHighlights paints only the rows a view shows (and a +/// view's worth either side), so a scroll past them used to parse the next +/// stretch on the frame (6-58 ms in Debug on a 1.6 MB file, a hitch every +/// few pages). Now it finds them painted already, and only a jump past +/// what was foreseen (ge, a Look) paints on the frame. +/// ponytail: one paint at a time, for the pane last scrolled, in the way it +/// went; a pane per worker if two scroll at once. +pub const PaintJob = struct { + gpa: std.mem.Allocator, + out: std.mem.Allocator, + gen: u32, + serial: u32, + revision: u32, + /// Where `source` starts in the text. + start: usize, + path: []u8, + source: []u8, + stop: std.atomic.Value(bool) = .init(false), + + pub fn deinit(job: *PaintJob) void { + job.gpa.free(job.path); + job.gpa.free(job.source); + job.gpa.destroy(job); + } +}; + +const PaintTask = struct { job: *PaintJob, future: ?std.Io.Future(void) = null, io: ?std.Io = null }; + +/// A paint's generation has the top bit, so it can never be a search's or +/// a parse's (those count from 0 in `gen`, and it would take two billion +/// searches to reach it). +const paint_bit: u32 = 1 << 31; + /// Where a worker hands a batch: false when it was turned away (the inbox /// closed, the wait for room canceled), and the worker stops. pub const Sink = *const fn (ctx: ?*anyopaque, batch: Batch) bool; @@ -161,10 +201,23 @@ parse_gen: u32 = 0, parse_next: ?struct { serial: u32, revision: u32 } = null, /// What the last parse cost the worker. parse_ns: u64 = 0, +/// The paint running (one at a time), its generation's count, and the +/// painted stretch it gave, kept until the view gets there (tree_sitter_gpa). +paint: ?PaintTask = null, +paint_count: u32 = 0, +ahead: []u8 = &.{}, +ahead_for: struct { serial: u32 = 0, revision: u32 = 0, start: usize = 0 } = .{}, +/// Stretches a view took painted ahead, and painted on the loop itself +/// (the tests count them). +painted_ahead: u32 = 0, +painted_on_loop: u32 = 0, +/// The view the last paint was asked from, and which way it was going. +ahead_seen: struct { serial: u32 = 0, scroll: usize = 0, dir: i2 = 1 } = .{}, pub fn deinit(s: *Stream, gpa: std.mem.Allocator) void { s.cancelTask(); s.cancelParse(); + s.cancelPaint(); s.pattern.deinit(gpa); s.dir.deinit(gpa); } @@ -184,6 +237,96 @@ pub fn cancelParse(s: *Stream) void { t.job.deinit(); } +/// The paint's worker told to stop and joined. +pub fn cancelPaint(s: *Stream) void { + const t = s.paint orelse return; + s.paint = null; + t.job.stop.store(true, .release); + if (t.future) |f| { + pardes.turn.yield(); + var future = f; + future.cancel(t.io.?); + pardes.turn.back(); + } + t.job.deinit(); +} + +/// The painted stretch kept for pane `serial`'s text at `revision`, if it +/// covers bytes `need_start..need_end`: handed over (the caller owns it, +/// tree_sitter_gpa), with where it starts. +pub fn takeAhead(p: *Pardes, serial: u32, revision: u32, need_start: usize, need_end: usize) ?struct { styles: []u8, start: usize } { + const s = &p.stream; + const a = s.ahead_for; + if (s.ahead.len == 0 or a.serial != serial or a.revision != revision) return null; + if (need_start < a.start or need_end > a.start + s.ahead.len) return null; + defer s.ahead = &.{}; + return .{ .styles = s.ahead, .start = a.start }; +} + +/// Asks a worker to paint bytes `start..end` of pane `serial`'s text ahead +/// of its view, unless that is painted or being painted already. Only with +/// workers, and only for a grammar a worker can paint (syntax.readyApart). +pub fn paintAhead(p: *Pardes, serial: u32, revision: u32, path: []const u8, content: []const u8, from: usize, to: usize) void { + const s = &p.stream; + if (p.host.vtable.search == null or p.fs.serving or to <= from or to > content.len) return; + const a = s.ahead_for; + if (s.ahead.len != 0 and a.serial == serial and a.revision == revision and from >= a.start and to <= a.start + s.ahead.len) return; + if (s.paint) |t| { + // One under way for the same text that reaches into the stretch + // asked for is let finish: held keys move the stretch every frame, + // and a paint restarted every frame would never land. + if (t.job.serial == serial and t.job.revision == revision and t.job.start < to and t.job.start + t.job.source.len > from) return; + s.cancelPaint(); + } + if (!syntax.readyApart(path)) return; + const job = p.gpa.create(PaintJob) catch return; + const path_copy = p.gpa.dupe(u8, path) catch { + p.gpa.destroy(job); + return; + }; + const source = p.gpa.dupe(u8, content[from..to]) catch { + p.gpa.free(path_copy); + p.gpa.destroy(job); + return; + }; + s.paint_count +%= 1; + const gen = paint_bit | (s.paint_count & ~paint_bit); + job.* = .{ .gpa = p.gpa, .out = p.gpa, .gen = gen, .serial = serial, .revision = revision, .start = from, .path = path_copy, .source = source }; + s.paint = .{ .job = job }; + p.emit(.{ .search = .{ .gen = gen } }); +} + +fn paintWork(job: *PaintJob, ctx: ?*anyopaque, sink: Sink) void { + const styles = syntax.highlightApart(job.out, job.path, job.source, &job.stop) catch return; + if (!sink(ctx, .{ .gen = job.gen, .styles = styles, .painted = .{ .serial = job.serial, .revision = job.revision, .start = job.start }, .end = .done })) return; +} + +/// A paint's answer: its task joined, its stretch kept for when the view +/// gets there, if the text is still what was painted. +fn receivePaint(p: *Pardes, b: *const Batch) void { + const s = &p.stream; + const painted = b.painted.?; + if (s.paint) |t| if (t.job.gen == b.gen) { + s.paint = null; + if (t.future) |f| { + pardes.turn.yield(); + var future = f; + future.await(t.io.?); + pardes.turn.back(); + } + t.job.deinit(); + }; + const id = p.paneBySerial(painted.serial) orelse return; + const f = p.panes[id].?.file orelse return; + if (f.revision != painted.revision or b.styles.len == 0) return; + const copy = p.tree_sitter_gpa.dupe(u8, b.styles) catch return; + if (s.ahead.len > 0) p.tree_sitter_gpa.free(s.ahead); + s.ahead = copy; + s.ahead_for = .{ .serial = painted.serial, .revision = painted.revision, .start = painted.start }; + // The next frame looks again: the view may be there already. + p.panes[id].?.file.?.syntax_dirty = true; +} + /// Pane `id`'s declarations asked for, as its text is now, unless a parse of /// that text is already on its way. With workers, on one; without (a test), /// here only for a small text, else not at all (the rows stay ungrouped). @@ -338,6 +481,20 @@ pub fn wake(s: *const Stream, next_frame: u64) ?u64 { /// inbox). Called by the shell for the `search` effect, on the loop. pub fn start(io: std.Io, gpa: std.mem.Allocator, p: *Pardes, gen: u32, ctx: ?*anyopaque, sink: Sink) void { const s = &p.stream; + // A paint's generation: its own task, its own worker. + if (gen & paint_bit != 0) { + if (s.paint) |*t| if (t.job.gen == gen and t.future == null) { + t.job.out = gpa; + t.future = io.concurrent(paintWork, .{ t.job, ctx, sink }) catch { + const job = t.job; + s.paint = null; + job.deinit(); + return; + }; + t.io = io; + }; + return; + } // A parse's generation: its own task. if (s.parse) |*t| if (gen == s.parse_gen and t.job.gen == gen and t.future == null) { t.job.out = gpa; @@ -424,6 +581,7 @@ const Collect = struct { pub fn receive(p: *Pardes, b: *const Batch) void { const s = &p.stream; if (b.parsed) |parsed| return receiveParse(p, b, parsed.serial, parsed.revision); + if (b.painted != null) return receivePaint(p, b); if (b.gen != s.gen or (s.state != .searching and s.state != .capped)) { s.dropped += 1; return; @@ -1079,6 +1237,49 @@ test "Stream: a big text's declarations are parsed on a worker, never the loop, try testing.expect(p.stream.parse == null); } +test "Stream: a scroll's colours are painted ahead on a worker, so PageDown after PageDown parses nothing on the frame" { + if (comptime !filesystem.platform_has_fs or !syntax.enabled) return; + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 40 }); + defer p.deinit(); + var text: std.ArrayList(u8) = .empty; + defer text.deinit(testing.allocator); + for (0..6000) |i| try text.print(testing.allocator, "fn f{d}() void {{\n _ = \"needle\";\n}}\n", .{i}); + const pane = try p.setTestFile(text.items); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, "/tmp/big.zig"); + p.advance(1); + var shell: TestShell = .init(); + TestShell.attach(p); + defer { + p.stream.cancelTask(); + p.stream.cancelParse(); + p.stream.cancelPaint(); + shell.q.deinit(); + } + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + _ = try p.render(arena.allocator()); + const first = p.stream.painted_on_loop; + for (0..20) |_| { + // The worker has had its time (a frame's work at a held key's pace + // is all it needs; here it is waited for, so the test is not a race). + const until = std.Io.Clock.awake.now(testing.io).toMilliseconds() + 60_000; + while (p.stream.paint != null) { + if (std.Io.Clock.awake.now(testing.io).toMilliseconds() > until) return error.Timeout; + shell.pump(p); + testing.io.sleep(.fromMilliseconds(1), .awake) catch {}; + } + p.update(.{ .key = .{ .cp = pardes.Key.page_down } }); + _ = arena.reset(.retain_capacity); + _ = try p.render(arena.allocator()); + // Coloured: the rows shown have their colours. + const f = &pane.file.?; + try testing.expect(f.highlights.len > 0 and f.highlight_start <= f.line_starts[f.scroll]); + } + try testing.expect(p.stream.painted_on_loop == first); + try testing.expect(p.stream.painted_ahead >= 5); +} + test "zz stream timings on the stress file with a worker (QUERY_TIMES=)" { const path_z = std.c.getenv("QUERY_TIMES") orelse return error.SkipZigTest; const path = std.mem.span(path_z); diff --git a/src/draw.zig b/src/draw.zig index 92fd8205..265e07c1 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -1971,7 +1971,7 @@ test "each Motion flavour reaches the lift as its own trajectory" { try std.testing.expect(peaks[2] <= 1.001 and peaks[3] > 1.25 and peaks[4] > peaks[3]); } -test "the focused cursor glides a jump, lands a step at once, and is exact at rest" { +test "the focused cursor glides a jump, eases a step, the thin caret too, and is exact at rest" { if (!builtins.capabilities.lift) return error.SkipZigTest; const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 30 }); defer p.deinit(); @@ -1983,12 +1983,17 @@ test "the focused cursor glides a jump, lands a step at once, and is exact at re var now: u64 = std.time.ns_per_s; p.advance(now); _ = try p.render(arena.allocator()); - // A step down: at once. + // A step down: eases there in a few frames. p.update(.{ .key = .{ .cp = 'j' } }); now += 16 * ms; p.advance(now); _ = arena.reset(.retain_capacity); var s = try p.render(arena.allocator()); + try std.testing.expectEqual(@as(u8, 3), s.chrome.cursor_glide); + now += 100 * ms; + p.advance(now); + _ = arena.reset(.retain_capacity); + s = try p.render(arena.allocator()); try std.testing.expectEqual(@as(u8, 2), s.chrome.cursor_glide); const before = s.cursor.?; // To the last line: it glides, a quad partway, and asks for frames. @@ -2023,7 +2028,7 @@ test "the focused cursor glides a jump, lands a step at once, and is exact at re // At rest the quad is the cursor's own cell. try std.testing.expectEqual(@as(f32, @floatFromInt(target.x)), s.chrome.cursor_quad[0]); try std.testing.expectEqual(@as(f32, @floatFromInt(target.y)), s.chrome.cursor_quad[1]); - // A mode change mid-glide lands at once: insert mode never trails. + // A mode change mid-glide: the thin caret glides on to the mark. p.update(.{ .key = .{ .cp = 'g' } }); p.update(.{ .key = .{ .cp = 'g' } }); now += 7 * ms; @@ -2036,7 +2041,17 @@ test "the focused cursor glides a jump, lands a step at once, and is exact at re p.advance(now); _ = arena.reset(.retain_capacity); s = try p.render(arena.allocator()); - try std.testing.expectEqual(@as(u8, 2), s.chrome.cursor_glide); + try std.testing.expectEqual(@as(u8, 3), s.chrome.cursor_glide); + try std.testing.expect(s.cursor.?.bar); + while (p.continuous()) { + now += 7 * ms; + p.advance(now); + _ = arena.reset(.retain_capacity); + s = try p.render(arena.allocator()); + } + // At rest, a bar's width at the caret's cell. + try std.testing.expectEqual(@as(f32, @floatFromInt(s.cursor.?.x)), s.chrome.cursor_quad[0]); + try std.testing.expectApproxEqAbs(@as(f32, 1.0 / 8.0), s.chrome.cursor_quad[2] - s.chrome.cursor_quad[0], 1e-4); } test "a tag caret past its row's end glides to the tag's right edge, where the layer's is" { diff --git a/src/pardes.zig b/src/pardes.zig index df6d347f..9177721f 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -4983,6 +4983,7 @@ pub const Pardes = struct { p.pipe.deinit(gpa); p.stream.deinit(gpa); p.handover.deinit(gpa); + if (p.stream.ahead.len > 0) p.tree_sitter_gpa.free(p.stream.ahead); p.locations_cache.deinit(p.tree_sitter_gpa); p.fs.deinit(gpa); p.shell_rows.reset(gpa); diff --git a/src/syntax.zig b/src/syntax.zig index aca2c3ff..821754fa 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -304,6 +304,55 @@ pub fn highlightFileRange(gpa: std.mem.Allocator, path: []const u8, content: []c return styles; } +/// Whether `highlightApart` can colour `path` on a worker: a grammar with +/// no injections (markdown's and typst's reach the shared parsers), made +/// ready here, on the loop, so the worker only reads its query. +pub fn readyApart(path: []const u8) bool { + if (!enabled) return false; + const selected = (forExt(std.fs.path.extension(path)) catch return false) orelse return false; + return !std.mem.eql(u8, selected.name, "markdown") and !std.mem.eql(u8, selected.name, "typst"); +} + +/// `highlightFileRange` of `source` (a copy of the range), on a worker: a +/// parser and a query cursor of its own, the grammar's query shared (it +/// is only read); `halt` ends the parse early. After `readyApart`. +pub fn highlightApart(gpa: std.mem.Allocator, path: []const u8, source: []const u8, halt: *const std.atomic.Value(bool)) ![]u8 { + if (comptime !enabled) return &.{}; + const shared = (try forExt(std.fs.path.extension(path))) orelse return &.{}; + const parser = ts.Parser.create(); + defer parser.destroy(); + try parser.setLanguage(shared.lang); + const cursor = ts.QueryCursor.create(); + defer cursor.destroy(); + const Reader = struct { + text: []const u8, + fn read(payload: ?*anyopaque, byte: u32, _: ts.Point, n: *u32) callconv(.c) [*c]const u8 { + const r: *@This() = @ptrCast(@alignCast(payload.?)); + const at = @min(byte, r.text.len); + n.* = @intCast(r.text.len - at); + return r.text.ptr + at; + } + fn progress(state: *ts.Parser.State) callconv(.c) bool { + const flag: *const std.atomic.Value(bool) = @ptrCast(@alignCast(state.payload.?)); + return flag.load(.monotonic); + } + }; + var reader: Reader = .{ .text = source }; + const tree = parser.parseWithOptions( + .{ .payload = &reader, .read = Reader.read, .encoding = .utf8 }, + null, + .{ .payload = @constCast(halt), .progress_callback = @ptrCast(&Reader.progress) }, + ) orelse return error.Canceled; + defer tree.destroy(); + const styles = try gpa.alloc(u8, source.len); + @memset(styles, 0); + var own = shared; + own.parser = parser; + own.cursor = cursor; + runQuery(styles, own, tree, 0); + return styles; +} + /// Source spans are independent of editor rows. Locations output uses the same /// declarations as sticky editor headers. Byte ends are exclusive; rows are /// zero-based and inclusive, including the last signature/opening-brace row. -- cgit v1.3 From a9e33e52d789c7433da1da17a8c82093c9114243 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 24 Oct 2026 15:23:45 -0300 Subject: anim 7: what the probe found: the paced wait spins (asleep, the CPU's clock fell and an input's frame took 2-5x as long), a glide measures the core's line count first and emits only the rows it shows, a far jump paints only its view, a long line 16 KB round the caret, the caret's sideways scroll measured from the view's edge, a paint never joined on the loop nor asked while the view stands still, rewritten generated panes do not glide, pictures decode off the loop --- src/File.zig | 101 ++++++++++++++++++++++++++++++++++++++++++++++++-------- src/Stream.zig | 49 ++++++++++++++++++--------- src/gui/gui.zig | 77 ++++++++++++++++++++++++++++-------------- src/image.zig | 45 ++++++++++++++++++++++--- src/panes.zig | 20 ++++++----- src/pardes.zig | 4 ++- src/syntax.zig | 1 + src/tty/tty.zig | 38 +++++++++++++++++---- 8 files changed, 262 insertions(+), 73 deletions(-) (limited to 'src/File.zig') diff --git a/src/File.zig b/src/File.zig index 798e3e84..6df49c98 100644 --- a/src/File.zig +++ b/src/File.zig @@ -26,6 +26,7 @@ const terminal = panes.terminal; const Text = panes.Text; const SYNTAX_CONTEXT_AFTER_ROWS: usize = 2; +const long_paint: usize = 16 << 10; /// Content and primary selection at one file edit boundary. Keeping only the /// primary avoids putting Text.max_selections ranges in every history entry. @@ -1724,8 +1725,23 @@ pub fn refreshHighlights(p: *Pardes) void { f.syntax_dirty = false; continue; } - const need_start = lineStart(p.gpa, f, f.scroll); - const need_end = @max(need_start, lineStart(p.gpa, f, f.scroll + pane.rows + SYNTAX_CONTEXT_AFTER_ROWS)); + // ponytail: a stretch over `long_paint` bytes (a minified line) is + // painted only around the caret, so a key typed in a 500 KB line + // parses 16 KB, not the line (190 ms a key in ReleaseSafe; 25 ms at + // 64 KB, so 16, still eight views of 80x25); its first + // tokens may be coloured as if the line began there. The upgrade: an + // incremental parse of the whole text, edited in place. + const caret = @min(f.content.len, lineStart(p.gpa, f, @intCast(@max(0, pane.body.cur_row))) + @as(usize, @intCast(@max(0, pane.body.cur_col)))); + const around = struct { + fn clamp(a: usize, b: usize, at: usize) [2]usize { + if (b - a <= long_paint) return .{ a, b }; + const lo = std.math.clamp(at -| long_paint / 2, a, b - long_paint); + return .{ lo, lo + long_paint }; + } + }; + const need = around.clamp(lineStart(p.gpa, f, f.scroll), @max(lineStart(p.gpa, f, f.scroll), lineStart(p.gpa, f, f.scroll + pane.rows + SYNTAX_CONTEXT_AFTER_ROWS)), caret); + const need_start = need[0]; + const need_end = need[1]; if ((!f.tree_context or (f.highlight_start == 0 and f.highlights.len == f.content.len)) and f.highlights.len > 0 and need_start >= f.highlight_start and need_end <= f.highlight_start + f.highlights.len) @@ -1734,7 +1750,11 @@ pub fn refreshHighlights(p: *Pardes) void { if (!f.tree_context and pane.colorAlgo() == .source) paintAhead(p, pane, f); continue; } - const slack: usize = if (f.highlights.len == 0) 0 else pane.rows; + // A view far from what is painted (a jump: ge, a Look) paints only + // itself on the frame, a third of the work; the stretch around it + // comes painted ahead (paintAhead) where there are workers. + const far = f.highlights.len == 0 or need_end <= f.highlight_start or need_start >= f.highlight_start + f.highlights.len; + const slack: usize = if (far and p.host.vtable.search != null) 0 else if (f.highlights.len == 0) 0 else pane.rows; const whole = pane.colorAlgo() == .locations or f.tree_context; // Painted ahead on a worker (Stream.paintAhead): taken, no parse. if (!whole and pane.colorAlgo() == .source) if (Stream.takeAhead(p, pane.serial, f.revision, need_start, need_end)) |got| { @@ -1747,11 +1767,14 @@ pub fn refreshHighlights(p: *Pardes) void { continue; }; if (pane.colorAlgo() == .source and !whole) p.stream.painted_on_loop += 1; - const start = if (whole) 0 else lineStart(p.gpa, f, f.scroll -| slack); - const end = if (whole) + const wide_start = if (whole) 0 else lineStart(p.gpa, f, f.scroll -| slack); + const wide_end = if (whole) f.content.len else - @max(start, lineStart(p.gpa, f, f.scroll + pane.rows + SYNTAX_CONTEXT_AFTER_ROWS + slack)); + @max(wide_start, lineStart(p.gpa, f, f.scroll + pane.rows + SYNTAX_CONTEXT_AFTER_ROWS + slack)); + const window = if (whole) [2]usize{ wide_start, wide_end } else around.clamp(wide_start, wide_end, caret); + const start = window[0]; + const end = window[1]; const new_highlights = (switch (pane.colorAlgo()) { .none => @as([]u8, &.{}), .diff => syntax.highlightDiff(p.tree_sitter_gpa, f.content, start, end), @@ -1772,24 +1795,76 @@ pub fn refreshHighlights(p: *Pardes) void { } } -/// The stretch a scroll of `pane` is heading into, two views on the way it -/// last went, asked of a worker (Stream.paintAhead) so it is painted by the -/// time the view gets there. +/// The stretch a scroll of `pane` is heading into, the view and three more +/// the way it last went, asked of a worker (Stream.paintAhead) so it is +/// painted by the time the view gets there. From the view itself: two +/// views out, an upward stretch stopped short of the view's own bottom +/// rows, and a half page up (or down) missed it by a line and painted on +/// the frame, 11-17 ms in ReleaseSafe. fn paintAhead(p: *Pardes, pane: *Pane, f: *State) void { const seen = &p.stream.ahead_seen; - if (seen.serial == pane.serial and f.scroll != seen.scroll) seen.dir = if (f.scroll > seen.scroll) 1 else -1; + // A view standing still (typing in it) needs nothing ahead: each edit + // is a new revision, and a paint asked at every keystroke was a copy + // of the stretch and a worker's start on the loop per key. + if (seen.serial == pane.serial and f.scroll == seen.scroll) return; + if (seen.serial == pane.serial) seen.dir = if (f.scroll > seen.scroll) 1 else -1; if (seen.serial != pane.serial) seen.dir = 1; seen.serial = pane.serial; seen.scroll = f.scroll; const rows: usize = pane.rows; - const view = if (seen.dir > 0) f.scroll + 2 * rows else f.scroll -| 2 * rows; - const start = lineStart(p.gpa, f, view -| rows); - const end = @max(start, lineStart(p.gpa, f, view + 2 * rows + SYNTAX_CONTEXT_AFTER_ROWS)); + const start = lineStart(p.gpa, f, if (seen.dir > 0) f.scroll else f.scroll -| 3 * rows); + const end = @max(start, lineStart(p.gpa, f, f.scroll + (if (seen.dir > 0) 4 * rows else rows) + SYNTAX_CONTEXT_AFTER_ROWS)); // Painted already, as far as that goes. if (f.highlights.len > 0 and start >= f.highlight_start and end <= f.highlight_start + f.highlights.len) return; Stream.paintAhead(p, pane.serial, f.revision, f.path, f.content, start, end); } +test "a long line is painted only around the caret" { + if (!syntax.enabled) return; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + const line = try std.testing.allocator.alloc(u8, 600 << 10); + defer std.testing.allocator.free(line); + for (line, 0..) |*c, i| c.* = if (i % 2 == 0) '1' else ','; + const pane = try p.setTestFile(line); + p.gpa.free(pane.file.?.path); + pane.file.?.path = try p.gpa.dupe(u8, "/tmp/long.json"); + pane.body.cur_col = 300 << 10; + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + _ = try p.render(arena.allocator()); + const f = &pane.file.?; + try std.testing.expect(f.highlights.len == long_paint); + try std.testing.expect(f.highlight_start <= 300 << 10 and f.highlight_start + f.highlights.len >= 300 << 10); +} + +test "a caret deep in a long line scrolls the view sideways to it, measured from the view's edge" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + p.settings.wrap = false; + const line = try std.testing.allocator.alloc(u8, 500 << 10); + defer std.testing.allocator.free(line); + @memset(line, 'a'); + const pane = try p.setTestFile(line); + var arena: std.heap.ArenaAllocator = .init(std.testing.allocator); + defer arena.deinit(); + _ = try p.render(arena.allocator()); + // Right, far: the caret ends a margin in from the right edge. + pane.body.cur_col = 400_000; + pane.ensureCursorVisible(); + const w: i32 = @as(i32, pane.cols) - @as(i32, gutterWidth(pane)); + const hmargin: i32 = @min(config.scroll_off, @divTrunc(w - 1, 2)); + try std.testing.expectEqual(@as(i32, 400_000 - (w - 1 - hmargin)), pane.hscroll); + // Back left of the view: a margin in from the left edge. + pane.body.cur_col = 100_000; + pane.ensureCursorVisible(); + try std.testing.expectEqual(@as(i32, 100_000 - hmargin), pane.hscroll); + // At the start: none. + pane.body.cur_col = 1; + pane.ensureCursorVisible(); + try std.testing.expectEqual(@as(i32, 0), pane.hscroll); +} + pub fn supportsContext(pane: *const Pane) bool { const file = pane.file orelse return false; return file.output == null and file.mini == null and syntax.supportsPath(file.path); diff --git a/src/Stream.zig b/src/Stream.zig index ace73ca4..e42d4a16 100644 --- a/src/Stream.zig +++ b/src/Stream.zig @@ -140,6 +140,7 @@ const PaintTask = struct { job: *PaintJob, future: ?std.Io.Future(void) = null, /// a parse's (those count from 0 in `gen`, and it would take two billion /// searches to reach it). const paint_bit: u32 = 1 << 31; +const max_paint_bytes = 512 << 10; /// Where a worker hands a batch: false when it was turned away (the inbox /// closed, the wait for room canceled), and the worker stops. @@ -204,6 +205,10 @@ parse_ns: u64 = 0, /// The paint running (one at a time), its generation's count, and the /// painted stretch it gave, kept until the view gets there (tree_sitter_gpa). paint: ?PaintTask = null, +/// One told to stop and not waited for: joined when its answer comes (a +/// paint of a long line runs on in its query; waiting for it here held the +/// loop for half a second). No new paint starts while it is out. +paint_retired: ?PaintTask = null, paint_count: u32 = 0, ahead: []u8 = &.{}, ahead_for: struct { serial: u32 = 0, revision: u32 = 0, start: usize = 0 } = .{}, @@ -237,18 +242,20 @@ pub fn cancelParse(s: *Stream) void { t.job.deinit(); } -/// The paint's worker told to stop and joined. +/// The paints' workers told to stop and joined (the session's end). pub fn cancelPaint(s: *Stream) void { - const t = s.paint orelse return; - s.paint = null; - t.job.stop.store(true, .release); - if (t.future) |f| { - pardes.turn.yield(); - var future = f; - future.cancel(t.io.?); - pardes.turn.back(); + for ([_]*?PaintTask{ &s.paint, &s.paint_retired }) |slot| { + const t = slot.* orelse continue; + slot.* = null; + t.job.stop.store(true, .release); + if (t.future) |f| { + pardes.turn.yield(); + var future = f; + future.cancel(t.io.?); + pardes.turn.back(); + } + t.job.deinit(); } - t.job.deinit(); } /// The painted stretch kept for pane `serial`'s text at `revision`, if it @@ -271,12 +278,19 @@ pub fn paintAhead(p: *Pardes, serial: u32, revision: u32, path: []const u8, cont if (p.host.vtable.search == null or p.fs.serving or to <= from or to > content.len) return; const a = s.ahead_for; if (s.ahead.len != 0 and a.serial == serial and a.revision == revision and from >= a.start and to <= a.start + s.ahead.len) return; + // A stretch bigger than this (a few lines of a minified file) is not + // painted ahead: the loop paints what it shows of it. + if (to - from > max_paint_bytes) return; if (s.paint) |t| { // One under way for the same text that reaches into the stretch // asked for is let finish: held keys move the stretch every frame, // and a paint restarted every frame would never land. if (t.job.serial == serial and t.job.revision == revision and t.job.start < to and t.job.start + t.job.source.len > from) return; - s.cancelPaint(); + // Else it is told to stop and left to end on its own, once. + if (s.paint_retired != null) return; + t.job.stop.store(true, .release); + s.paint_retired = t; + s.paint = null; } if (!syntax.readyApart(path)) return; const job = p.gpa.create(PaintJob) catch return; @@ -297,8 +311,10 @@ pub fn paintAhead(p: *Pardes, serial: u32, revision: u32, path: []const u8, cont } fn paintWork(job: *PaintJob, ctx: ?*anyopaque, sink: Sink) void { - const styles = syntax.highlightApart(job.out, job.path, job.source, &job.stop) catch return; - if (!sink(ctx, .{ .gen = job.gen, .styles = styles, .painted = .{ .serial = job.serial, .revision = job.revision, .start = job.start }, .end = .done })) return; + // Stopped or failed, it still answers (with nothing), so the loop + // knows to join it. + const styles: []u8 = syntax.highlightApart(job.out, job.path, job.source, &job.stop) catch @constCast(&[_]u8{}); + _ = sink(ctx, .{ .gen = job.gen, .styles = styles, .painted = .{ .serial = job.serial, .revision = job.revision, .start = job.start }, .end = .done }); } /// A paint's answer: its task joined, its stretch kept for when the view @@ -306,8 +322,9 @@ fn paintWork(job: *PaintJob, ctx: ?*anyopaque, sink: Sink) void { fn receivePaint(p: *Pardes, b: *const Batch) void { const s = &p.stream; const painted = b.painted.?; - if (s.paint) |t| if (t.job.gen == b.gen) { - s.paint = null; + // Its task joined: it has sent its last, so the join is a return away. + for ([_]*?PaintTask{ &s.paint, &s.paint_retired }) |slot| if (slot.*) |t| if (t.job.gen == b.gen) { + slot.* = null; if (t.future) |f| { pardes.turn.yield(); var future = f; @@ -315,6 +332,8 @@ fn receivePaint(p: *Pardes, b: *const Batch) void { pardes.turn.back(); } t.job.deinit(); + // A retired one's answer is for a stretch nobody wants now. + if (slot == &s.paint_retired) return; }; const id = p.paneBySerial(painted.serial) orelse return; const f = p.panes[id].?.file orelse return; diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 1a56ecd0..5d3cbafd 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -4126,8 +4126,8 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { // tick, skipping (never bunching) the ticks a slow frame missed. tick = if (g.pace_ns != 0 and now -| g.pace_ns < 2 * period) g.pace_ns + period else now; if (tick < now) tick += (now - tick) / period * period; - const left: c_int = @intCast(@min(std.math.maxInt(c_int), (tick -| now) / std.time.ns_per_ms)); - ms = if (ms < 0) left else @min(ms, left); + // Waited out polling, below. + ms = 0; } g.input_seen = false; // The wait is the 9P connections' turn with the core. @@ -4177,16 +4177,25 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { // never adds a tick to an input's latency), and the ticks after it // run from it. if (paced and g.input_seen) tick = c.SDL_GetTicksNS(); + // The tick is waited out polling, not asleep, as a game's frame + // limiter spins: asleep between 60 Hz frames, the CPU's clock fell + // (intel_pstate, 4.9 GHz down toward 0.8) and every frame, an + // input's first among them, took 2-5x as long: input-to-present p50 + // 1.9 ms spinning against 7-8 ms asleep (docs/next-anim.md). + // ponytail: a core while something moves (~250 ms a scroll); a + // sleep to a millisecond short of the tick if the power matters more. while (paced and !g.input_seen) { - const left = tick -| c.SDL_GetTicksNS(); - if (left < std.time.ns_per_ms) break; - const wait_ms: c_int = @intCast(@min(left / std.time.ns_per_ms, @as(u64, @intCast(demoDue(g) orelse std.math.maxInt(c_int))))); + if (tick -| c.SDL_GetTicksNS() < 50 * std.time.ns_per_us) break; pardes.turn.rest(); - const more = c.SDL_WaitEventTimeout(&sev, wait_ms); + const more = c.SDL_PollEvent(&sev); pardes.turn.wake(); if (more) { dispatch(g, &in, &sev); while (c.SDL_PollEvent(&sev)) dispatch(g, &in, &sev); + } else { + // The events asked for every 100 µs, the core busy between. + const until = c.SDL_GetTicksNS() + 100 * std.time.ns_per_us; + while (c.SDL_GetTicksNS() < @min(until, tick)) std.atomic.spinLoopHint(); } runDemo(g, &in, core); if (g.input_seen) tick = c.SDL_GetTicksNS(); @@ -5071,7 +5080,7 @@ const Glide = struct { /// whatever moved it. /// When the picture was last sampled (sample). shown_ns: u64 = 0, - seen: [pardes.MAX_PANES]struct { serial: u32 = 0, line: i64 = 0, file: u64 = 0 } = @splat(.{}), + seen: [pardes.MAX_PANES]struct { serial: u32 = 0, line: i64 = 0, file: u64 = 0, revision: u32 = 0 } = @splat(.{}), /// How far the picture may lag, in bodies: the rows kept past each /// edge, so a jump made while one glides carries on from where it is. @@ -5152,23 +5161,31 @@ const Glide = struct { } }; // The least shift under which the rows agree, but for a few: the - // cursor's line and its number's weight move with the scroll. - var shift: u16 = found: for (1..h) |k| { - const kk: u16 = @intCast(k); - const allowed = @max(2, (h - kk) / 8); - var misses: usize = 0; - for (0..h - kk) |r| { - const rr: u16 = @intCast(r); - const old_row = glide.before[@as(usize, if (glide.dir > 0) rr + kk else rr) * w ..][0..w]; - const new_row = now.row(surface, x0, glide.body_y + if (glide.dir > 0) rr else rr + kk, w); - if (!sameRow(old_row, new_row)) { - misses += 1; - if (misses > allowed) continue :found; + // cursor's line and its number's weight move with the scroll. The + // lines the core moved are tried first: unwrapped, they are the + // rows, and one pass over the body settles it (the search over + // every shift was 6 ms of the first frame of a page in Debug). + const agrees = struct { + fn at(gl: *const Glide, surf: *const pardes.Surface, x: u16, width: u16, height: u16, kk: u16) bool { + if (kk == 0 or kk + 3 > height) return false; + const allowed = @max(2, (height - kk) / 8); + var misses: usize = 0; + for (0..height - kk) |r| { + const rr: u16 = @intCast(r); + const old_row = gl.before[@as(usize, if (gl.dir > 0) rr + kk else rr) * width ..][0..width]; + const new_row = now.row(surf, x, gl.body_y + if (gl.dir > 0) rr else rr + kk, width); + if (!sameRow(old_row, new_row)) { + misses += 1; + if (misses > allowed) return false; + } } + return true; } - // Too few rows left to tell: none in common. - if (h - kk < 3) break :found 0; - break :found kk; + }; + const guess: u16 = @intFromFloat(@min(glide.pending_lines, @as(f32, @floatFromInt(h)))); + // A body's lines or more: every row moved off, none in common. + var shift: u16 = if (guess >= h) 0 else if (agrees.at(glide, surface, x0, w, h, guess)) guess else found: for (1..h) |k| { + if (agrees.at(glide, surface, x0, w, h, @intCast(k))) break :found @intCast(k); } else 0; // None in common: a body's move from the last frame's body, if the // lines moved are that many (rows that merely changed, a small @@ -5285,9 +5302,14 @@ fn stepGlide(g: *Gui, core: *pardes.Pardes, gpa: std.mem.Allocator) void { }; const line: i64 = if (pane.file) |f| @intCast(f.scroll) else if (pane.isTerminal()) pardes.panes.terminal.gridOffset(pane) else 0; const file: u64 = if (pane.file) |f| std.hash.Wyhash.hash(0, f.path) else 0; + const revision: u32 = if (pane.file) |f| f.revision else 0; const was = glide.seen[id]; - glide.seen[id] = .{ .serial = pane.serial, .line = line, .file = file }; + glide.seen[id] = .{ .serial = pane.serial, .line = line, .file = file, .revision = revision }; if (was.serial != pane.serial or was.file != file or was.line == line or pane.collapsed or pane.hasPdf()) continue; + // Generated text rewritten as its view moved (a query pane's live + // rows, a +Search refilled, Callstack): the rows are another + // text's, not this one's moved; it lands. + if (pane.file) |f| if (f.output != null and revision != was.revision) continue; if (pane.file == null and wheeled != id) continue; if (g.scroll_pane == id and (g.scroll_lag != 0 or g.scroll_delta != 0)) continue; const moved = line - was.line; @@ -5350,8 +5372,13 @@ fn emitGlideRows(g: *Gui, instances: [*]CellInstance, base: u32, surface: *parde const cursor_idx: u32 = if (surface.cursor) |cu| @as(u32, cu.y) * surface.cols + cu.x else std.math.maxInt(u32); const cursor_bar = if (surface.cursor) |cu| cu.bar else false; var n: u32 = 0; - var row = y0 + kept.rows; - while (row < y0 + bh) : (row += 1) { + // Only the rows the scissor shows: lagging a body or more, every body + // row is past the edge, and drawing them all was twice the frame's + // instances for the length of a long glide. + const lag: u16 = @intFromFloat(@min(@floor(@abs(glide.offset)), @as(f32, @floatFromInt(bh)))); + var row = y0 + kept.rows + if (glide.offset > 0) lag else 0; + const row_end = y0 + bh - if (glide.offset < 0) lag else 0; + while (row < row_end) : (row += 1) { const line = surface.cells[@as(usize, row) * surface.cols ..][0..surface.cols]; const row_cursor: ?usize = if (surface.cursor) |cu| if (cu.y == row) cu.x else null else null; var col = x0; diff --git a/src/image.zig b/src/image.zig index 5797ce9e..19dbb9e4 100644 --- a/src/image.zig +++ b/src/image.zig @@ -1,5 +1,6 @@ //! Image decoding, pixel placement, and glyph approximation. const std = @import("std"); +const builtin = @import("builtin"); const zstbi = @import("zstbi"); /// The 16-colour ANSI table below is the only thing this file ever wanted from /// the emulator, and a build without one still renders images — see @@ -767,7 +768,9 @@ pub fn readable(bytes: []const u8) bool { /// decode + downscale to RGBA, gpa-owned. Returns null on any failure — the /// pane then simply shows a blank body. -pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) ?struct { rgba: []u8, w: usize, h: usize } { +const Decoded = struct { rgba: []u8, w: usize, h: usize }; + +pub fn decode(gpa: std.mem.Allocator, bytes: []const u8) ?Decoded { if (bytes.len == 0 or bytes.len > std.math.maxInt(c_int)) return null; // Bounded before decoding: a few KB of PNG can name gigapixels. var iw: c_int = 0; @@ -812,8 +815,14 @@ pub const State = struct { raw: []u8 = &.{}, grid: GlyphArt.Grid = .{ .cells = &.{}, .cols = 0, .rows = 0 }, grid_key: GridKey = .{}, + /// The decode under way off the loop (ensureDecoded), and its answer. + decoder: ?std.Thread = null, + decoded: std.atomic.Value(bool) = .init(false), + answer: ?Decoded = null, pub fn deinit(state: *State, gpa: std.mem.Allocator) void { + if (state.decoder) |t| t.join(); + if (state.answer) |a| gpa.free(a.rgba); gpa.free(state.path); if (state.rgba.len > 0) gpa.free(state.rgba); if (state.raw.len > 0) gpa.free(state.raw); @@ -941,15 +950,41 @@ pub fn tagPrefix(arena: std.mem.Allocator, state: *const State, glyphs: bool) ![ ); } +/// The picture decoded off the loop: the first draw starts a thread and +/// draws the pane without it (its tag and frame at once); the frames after +/// it look (Pardes.nextWake asks for them) and the picture lands on the +/// first one after the decode (80 ms in ReleaseSafe, 290 in Debug, for the +/// docs' screenshot: all of it once on the frame before). +/// ponytail: a thread a picture; a pool if many open at once. fn ensureDecoded(p: *pardes.Pardes, state: *State) void { - if (state.tried) return; - state.tried = true; - if (state.raw.len == 0) return; // nothing was readable at open - if (decode(p.image_gpa, state.raw)) |decoded| { + if (state.decoder) |t| { + if (!state.decoded.load(.acquire)) return; + t.join(); + state.decoder = null; + } + if (state.answer) |decoded| { + state.answer = null; state.rgba = decoded.rgba; state.iw = decoded.w; state.ih = decoded.h; } + if (state.tried) return; + state.tried = true; + if (state.raw.len == 0) return; // nothing was readable at open + const Work = struct { + fn run(gpa: std.mem.Allocator, st: *State) void { + st.answer = decode(gpa, st.raw); + st.decoded.store(true, .release); + } + }; + if (comptime pardes.hosted and !builtin.is_test) { + if (std.Thread.spawn(.{}, Work.run, .{ p.image_gpa, state })) |t| { + state.decoder = t; + return; + } else |_| {} + } + Work.run(p.image_gpa, state); + ensureDecoded(p, state); } fn ensureGrid(p: *pardes.Pardes, state: *State, cols: u16, rows: u16) void { diff --git a/src/panes.zig b/src/panes.zig index 20618ccc..51710d08 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -619,14 +619,18 @@ pub const Pane = struct { const line = modal.lineSlice(f.content, @intCast(@max(0, pane.body.cur_row))); const raw_cur: usize = @intCast(@max(0, pane.body.cur_col)); const raw_scroll: usize = @intCast(@max(0, pane.hscroll)); - const cur = @as(i32, @intCast(File.rawDisplayCol(line, raw_cur))); - const visual_scroll = @as(i32, @intCast(File.rawDisplayCol(line, raw_scroll))); - var target = visual_scroll; - if (cur < visual_scroll + hmargin) - target = @max(0, cur - hmargin) - else if (cur > visual_scroll + w - 1 - hmargin) - target = cur - (w - 1 - hmargin); - if (target != visual_scroll) pane.hscroll = @intCast(File.rawAtDisplay(line, @intCast(target))); + // Measured from the view's left edge to the caret, never from the + // line's start: a 500 KB line was walked from byte 0 at every key + // (widths add, so the span alone is exact). + const apart = File.lineDisplayOffset(line, raw_scroll, raw_cur); + const back: ?i32 = if (apart < hmargin) hmargin else if (apart > w - 1 - hmargin) w - 1 - hmargin else null; + if (back) |cols| { + // The byte `cols` columns before the caret, looked for from a + // few bytes a column back (a grapheme is at most 4 a column). + const from = raw_cur -| @as(usize, @intCast(cols)) * 4; + const ahead = File.lineDisplayOffset(line, from, raw_cur) - cols; + pane.hscroll = @intCast(if (ahead <= 0) from else File.byteAtDisplayFrom(line, from, @intCast(ahead))); + } } } diff --git a/src/pardes.zig b/src/pardes.zig index 9177721f..0f3f87f2 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -7696,8 +7696,10 @@ pub const Pardes = struct { // seen are stamped 0, which `advance` would count back from). if (p.fs.batch.bytes.items.len > 0) return @max(next, p.fs.batch.last_ns + ctlfs.pane.batch_pause_ns); if (p.chrome_animation.isActive() or p.presentation.animating()) return next; - // Places still to find resume on the next frame. + // Places still to find resume on the next frame; a picture being + // decoded is looked for. for (p.panes) |slot| if (slot) |pane| if (pane.places.busy(pane)) return next; + for (p.panes) |slot| if (slot) |pane| if (pane.image) |iv| if (iv.decoder != null) return next; // A markdown text's tables still being read from the top (Tables.zig). for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.tables.busy()) return next; if (panes.Query.busy(p)) return next; diff --git a/src/syntax.zig b/src/syntax.zig index 821754fa..985a9888 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -344,6 +344,7 @@ pub fn highlightApart(gpa: std.mem.Allocator, path: []const u8, source: []const .{ .payload = @constCast(halt), .progress_callback = @ptrCast(&Reader.progress) }, ) orelse return error.Canceled; defer tree.destroy(); + if (halt.load(.monotonic)) return error.Canceled; const styles = try gpa.alloc(u8, source.len); @memset(styles, 0); var own = shared; diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 264cfbef..b7bb2d54 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -1521,8 +1521,10 @@ const Shell = struct { /// PARDES_TEST_CLOCK's virtual time (host_io.testClock), and where the /// running-out wait moves it: the core's next wake. test_clock: ?u64 = null, - /// The tick the last paced frame was due at (waitInput). + /// The tick the last paced frame was due at (waitInput), and whether + /// this wait read an input (its frame is drawn at once). pace_ns: u64 = 0, + input_seen: bool = false, wake_to: u64 = 0, fn of(ctx: ?*anyopaque) *Shell { @@ -1574,7 +1576,6 @@ const Shell = struct { fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { const s = of(ctx); - var batch: usize = 0; // The wait is the 9P connections' turn with the core. A timeout (the // core's next wake) arrives through the same queue (`wakeWatch`). // While anything moves, a frame a tick (animation.frame_ns) on a grid @@ -1583,14 +1584,32 @@ const Shell = struct { // ends the wait at once and its frame is drawn then; the ticks after // it run from it. var wait = timeout_ms; - if (s.test_clock == null and s.core.continuous()) { + const paced = s.test_clock == null and s.core.continuous(); + var tick: u64 = 0; + if (paced) { const period = pardes.animation.frame_ns; const now: u64 = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); - var tick = if (s.pace_ns != 0 and now -| s.pace_ns < 2 * period) s.pace_ns + period else now; + tick = if (s.pace_ns != 0 and now -| s.pace_ns < 2 * period) s.pace_ns + period else now; if (tick < now) tick += (now - tick) / period * period; s.pace_ns = tick; wait = @intCast(@max(1, (tick -| now) / std.time.ns_per_ms)); } + s.input_seen = false; + // Paced, what is not an input (a frame's ack, a pty's output) is + // taken in and the wait goes on to the tick: the acks alone ran the + // loop at the terminal's round trip. + while (true) { + s.waitOnce(wait); + if (!paced or s.input_seen or s.core.quit) break; + const now: u64 = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + if (now + std.time.ns_per_ms > tick) break; + wait = @intCast((tick - now) / std.time.ns_per_ms); + } + if (paced and s.input_seen) s.pace_ns = @intCast(std.Io.Clock.awake.now(s.io).nanoseconds); + } + + fn waitOnce(s: *Shell, wait: u32) void { + var batch: usize = 0; if (wait != 0) { s.wake_to = s.core.nextWake() orelse 0; requestWake(s.io, wait); @@ -1638,8 +1657,15 @@ const Shell = struct { // A key's or a click's time, for its latency to the frame that // answers it (FrameStats): when the loop takes it in. switch (event) { - .key_press => core.frames.input(pardes.FrameStats.nowNs()), - .mouse => |m| if (m.type == .press) core.frames.input(pardes.FrameStats.nowNs()), + .key_press => { + core.frames.input(pardes.FrameStats.nowNs()); + s.input_seen = true; + }, + .mouse => |m| if (m.type == .press) { + core.frames.input(pardes.FrameStats.nowNs()); + s.input_seen = true; + }, + .paste, .paste_start, .winsize => s.input_seen = true, else => {}, } switch (event) { -- cgit v1.3