From 02ea4db25f9802e76112f3b4e69aa75e5a9464dc Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 15 Sep 2026 18:41:15 -0300 Subject: Default location results to stacked addresses and source previews --- src/dump.zig | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/dump.zig') diff --git a/src/dump.zig b/src/dump.zig index 0c538a1a..89abd995 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -75,7 +75,7 @@ pub const Terminal = struct { }; pub const LocationRow = struct { - kind: enum { match, context }, + kind: enum { match, context, preview }, declaration: bool = false, path: []const u8, line: usize, -- cgit v1.3 From 9695cb098c784792af79c22d46a17f7bc7247d33 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 22 Sep 2026 17:43:57 -0300 Subject: Repaint PDF highlights by row, send rasters by shared memory, and animate messages PDF highlights (hover preview, search, selection) are baked into page rasters, and any change re-rendered the whole page with MuPDF; the TTY then re-sent it as base64 (4.7 MB a page), the GUI as a new texture. Worse, a pointer motion over a PDF invalidated the page even when no preview was shown, so every motion paid that. Now: - A raster whose baked highlight set equals the wanted one is left alone. - A highlighted page keeps its clean rows (before highlights and tint); a change repaints only the rows of quads that differ, running MuPDF's highlight pass (pardes_pdf_paint_highlights) over those clean rows and tinting them: the operations a full render performs, so the pixels are identical. MuPDF band renders are NOT bit-identical to a whole page (edge rows, resampled images), so they are never used to patch; the comment claiming otherwise is corrected. - ImagePlace.patch hands shells the changed rows; the GUI uploads just those rows into the texture it holds. - The TTY probes kitty shared memory (t=s) with an id vaxis never reaches and sends rasters as a /dev/shm name when the terminal reads it; direct base64 otherwise (ssh). - Shells that take row patches (GUI, TTY with shm) repaint a selection while it is dragged instead of only on release. Latency elsewhere: - TTY: an animating frame no longer sleeps 16 ms blind; a tick thread posts into the input queue, so input inside the frame is handled at once. - TTY and GUI: queued pointer motions coalesce to the last. - GUI: a skipped swapchain image re-arms the frame (3 retries); animations still tick while nothing presents. - Editing: the line index is carried across an edit instead of rebuilt from a scan of the whole file per keystroke. Messages fall into their row (ease-in; the GUI slides the band out from under the tagline, a terminal fades it), stay until the next input as before, linger MessageLinger ms (default 800), and dissolve (ease-out). MessageAnimation toggles it; both are settings, in Config and startup files. The snapshot harness pins the old behaviour. The detached server now ticks animations. A restored terminal comes back live: the old screen and scrollback (dumped as clean VT by ghostty's formatter, replayed at the new size; older dumps fall back to their rendered text), a dim "restored history" marker, then a new shell in the directory it was in. Right-click on a line number in a file pane looks at that line (a sticky context header's number included). Measured with an external pty driver (TTY), an in-process fence trace (GUI, PARDES_TEST_LATENCY), and test/pdf_pointer_bench.zig (pixel identity against the baseline and a whole-page oracle); balanced A/A/B rounds, paired per-round statistics. Messages stack: each event gets its own row and its own fall, linger and dissolve; a line keeps its row until it leaves and a new one fills the first free row. Announcements and statuses are replaced in place, not stacked. MessageFall, MessageDissolve and DumpDir are settings Config reports. Co-Authored-By: Claude Opus 5.5 (1M context) --- build.zig | 19 ++ docs/config.md | 24 ++- src/config.zig | 66 +++++- src/detached/server.zig | 14 +- src/dump.zig | 19 +- src/fs.zig | 4 +- src/gui/gui.zig | 110 ++++++++-- src/macos.zig | 4 +- src/panes.zig | 484 ++++++++++++++++++++++++++++++++++++++++-- src/pardes.zig | 433 +++++++++++++++++++++++++++++++++++-- src/pdf.zig | 67 ++++++ src/pdf_bridge.c | 228 ++++++++++++++++---- src/pdf_bridge.h | 46 +++- src/tag_layer.zig | 4 + src/tty/tty.zig | 148 +++++++++++-- test/output.zig | 3 +- test/panes.zig | 37 ++++ test/pdf_pointer_bench.zig | 224 +++++++++++++++++++ test/snapshot.zig | 4 +- test/snapshots/builtins.snap | 4 + test/snapshots/dump.golden | 3 + test/snapshots/load.golden | 18 +- test/snapshots/restore.golden | 6 +- 23 files changed, 1815 insertions(+), 154 deletions(-) create mode 100644 test/pdf_pointer_bench.zig (limited to 'src/dump.zig') diff --git a/build.zig b/build.zig index 562ed89f..7010c863 100644 --- a/build.zig +++ b/build.zig @@ -142,6 +142,7 @@ pub fn build(b: *std.Build) void { const mupdf_check = b.step("mupdf-check", "compile, link, render, and search docs/design.pdf with MuPDF"); const pdf_bench_step = b.step("pdf-bench", "benchmark real MuPDF page rendering (-- [--json] [--reps N] [--warmup N] [--path FILE] [--page N] [--pages N])"); const pdf_sections_bench_step = b.step("pdf-sections-bench", "benchmark PDF outline/sections paths in ReleaseFast (-Doptimize=ReleaseFast -- [--json] [--reps N] [--warmup N])"); + const pdf_pointer_bench_step = b.step("pdf-pointer-bench", "time PDF hover and selection gestures and prove their pixels (-Doptimize=ReleaseFast -- [--label L] [--reps N] [--path FILE] [--cell WxH])"); const pdf_scroll_bench_step = b.step("pdf-scroll-bench", "benchmark fast continuous-strip PDF scrolling in ReleaseFast (-Doptimize=ReleaseFast -- [--json] [--reps N] [--warmup N] [--path FILE])"); if (!enable_mupdf) mupdf_check.dependOn(&b.addFail("mupdf-check is unavailable with -Dmupdf=false").step); @@ -151,6 +152,8 @@ pub fn build(b: *std.Build) void { pdf_sections_bench_step.dependOn(&b.addFail("pdf-sections-bench is unavailable with -Dmupdf=false").step); if (!enable_mupdf) pdf_scroll_bench_step.dependOn(&b.addFail("pdf-scroll-bench is unavailable with -Dmupdf=false").step); + if (!enable_mupdf) + pdf_pointer_bench_step.dependOn(&b.addFail("pdf-pointer-bench is unavailable with -Dmupdf=false").step); const shaders_step = b.step("shaders", "refresh paired shaders/prebuilt/*.spv + *.glsl snapshots (glslc)"); const update_shaders = b.addUpdateSourceFiles(); @@ -482,6 +485,22 @@ pub fn build(b: *std.Build) void { run_pdf_sections_bench.setCwd(b.path(".")); pdf_sections_bench_step.dependOn(&run_pdf_sections_bench.step); + const pdf_pointer_bench = b.addExecutable(.{ + .name = "pardes-pdf-pointer-bench", + .root_module = b.createModule(.{ + .target = target, + .optimize = .ReleaseFast, + .root_source_file = b.path("test/pdf_pointer_bench.zig"), + .link_libc = true, + }), + }); + pdf_pointer_bench.root_module.addImport("pardes", core_module); + pdf_pointer_bench.root_module.addImport("mupdf", mupdf_mod); + const run_pdf_pointer_bench = b.addRunArtifact(pdf_pointer_bench); + if (b.args) |args| run_pdf_pointer_bench.addArgs(args); + run_pdf_pointer_bench.setCwd(b.path(".")); + pdf_pointer_bench_step.dependOn(&run_pdf_pointer_bench.step); + const pdf_scroll_bench = b.addExecutable(.{ .name = "pardes-pdf-scroll-bench", .root_module = b.createModule(.{ diff --git a/docs/config.md b/docs/config.md index 8eff79a8..27818b5b 100644 --- a/docs/config.md +++ b/docs/config.md @@ -115,6 +115,16 @@ compact screen. Hiding it preserves your custom column commands. name before it runs; it is on by default, and the builtins that own the message row themselves (`Msg`) never announce. Turning it off leaves the row to the messages a builtin chooses to write. +`MessageAnimation` toggles how a message comes and goes; it is on by default. +A message eases down into its row (graphical frontends slide it out from under +the tagline; a terminal fades it in), stays until the next key or click as it +always has, then lingers for `MessageLinger` milliseconds (default 800) before +it dissolves into the page. `MessageFall` (default 180) and `MessageDissolve` +(default 300) set how long the fall and the dissolve take, also in +milliseconds; each timing is at most 60000, and `Config` reports all three. `MessageLinger 0` with +`MessageAnimation off` restores the old behaviour, a message cleared by the +very input that follows it. An updated line on a row already showing one swaps +its text in place rather than falling again. `SyntaxBold` toggles bold syntax keywords; it is off by default. These settings are shared by GUI and TTY, and `Config` reports their current states. Like `Colors` and `Wrap`, these commands take no argument and invert @@ -573,8 +583,18 @@ control all yield null, and the flag has to work anyway. Neither is a question asked at runtime — a binary that shelled out to `git` would describe whatever tree it was standing in rather than the one it came from. -`Restore a.dump` first looks for the relative path in the default dump directory -(`$XDG_DATA_HOME/pardes`, or `~/.local/share/pardes`). If it is absent, Restore +`Restore a.dump` first looks for the relative path in the dump directory: +`DumpDir ` when set (a leading `~/` is your home; bare `DumpDir` returns +to the default), else `$XDG_DATA_HOME/pardes` or `~/.local/share/pardes`. +`Config` reports the directory in effect as `DumpDir `, so the line can +be fed back as configuration. If it is absent, Restore 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 restored terminal comes back live: its recorded output (the last MiB of it) +is replayed as history, a dim `── restored history ──` line marks where it +ends, and a new shell starts below it in the directory the old one was in. A +view left scrolled back stays where it was. Only the shell is new; nothing the +old one was running is restarted. The web shell, which has no ptys, still +shows the history alone. diff --git a/src/config.zig b/src/config.zig index 98bbf3f4..527c3752 100644 --- a/src/config.zig +++ b/src/config.zig @@ -102,6 +102,11 @@ pub const leader_path = paths: { table.set(.TaglineSize, null); } if (pardes.platform == .gui) table.set(.Pet, null); + table.set(.MessageAnimation, null); + table.set(.MessageLinger, null); + table.set(.MessageFall, null); + table.set(.MessageDissolve, null); + table.set(.DumpDir, null); if (builtins.capabilities.window_opacity) table.set(.WindowOpacity, null); if (builtins.capabilities.window_blur) table.set(.WindowBlur, null); if (builtins.capabilities.panel_transitions) { @@ -269,6 +274,10 @@ pub const wheel_cols: i32 = 4; pub const look_preview_delay_frames: ?u16 = 2; +/// The longest any message timing (MessageLinger, MessageFall, +/// MessageDissolve) may be set to, in milliseconds. +pub const message_ms_max: u16 = 60_000; + // Tag fonts keep body-cell geometry; valid sizes are 1...100 percent. pub const gui_tagline_font_percent: u8 = 82; comptime { @@ -558,6 +567,17 @@ pub const Runtime = struct { syntax_bold: bool = false, /// Builtins announce themselves on the message row. verbose: bool = true, + /// A message falls into its row and dissolves out of it. + message_animation: bool = true, + /// How long a message stays after the key or click that dismisses it. + message_linger_ms: u16 = 800, + /// How long its ease-in fall into the row takes. + message_fall_ms: u16 = 180, + /// How long its ease-out dissolve takes. + message_dissolve_ms: u16 = 300, + /// Where Dump writes and a relative Restore looks; empty is the default + /// ($XDG_DATA_HOME/pardes, else ~/.local/share/pardes). + dump_dir: Text(limits.host_path_cap) = .{}, window_opacity: u8 = 100, window_blur: u8 = 0, window_opacity_pending: bool = true, @@ -655,7 +675,10 @@ pub const Runtime = struct { pub const Capability = std.meta.FieldEnum(Capabilities); - pub const Toggle = enum { colors, wrap, tree_context_tag_style, tag_bottom, debug, focus_tint, column_tags, syntax_bold, verbose }; + /// 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, column_tags, syntax_bold, verbose, message_animation }; pub const Scene = std.meta.FieldEnum(layout.SceneEffect); pub const Action = union(enum) { @@ -666,6 +689,8 @@ pub const Runtime = struct { tagline_size, window_opacity, window_blur, + message_ms: MessageTime, + dump_dir, transition: layout.Transition, scene: Scene, }; @@ -679,7 +704,7 @@ pub const Runtime = struct { return switch (setting.action) { // A toggle flips when it is a bare tagline word and SETS when // it is given `on` or `off`, so the report is configuration. - .shell, .theme, .font, .tagline_size, .window_opacity, .window_blur, .toggle => true, + .shell, .theme, .font, .tagline_size, .window_opacity, .window_blur, .message_ms, .dump_dir, .toggle => true, else => false, }; } @@ -703,6 +728,11 @@ pub const Runtime = struct { .{ .word = "ColumnTags", .action = .{ .toggle = .column_tags } }, .{ .word = "SyntaxBold", .action = .{ .toggle = .syntax_bold } }, .{ .word = "Verbose", .action = .{ .toggle = .verbose } }, + .{ .word = "MessageAnimation", .action = .{ .toggle = .message_animation } }, + .{ .word = "MessageLinger", .action = .{ .message_ms = .linger } }, + .{ .word = "MessageFall", .action = .{ .message_ms = .fall } }, + .{ .word = "MessageDissolve", .action = .{ .message_ms = .dissolve } }, + .{ .word = "DumpDir", .action = .dump_dir }, .{ .word = "Theme", .action = .theme }, .{ .word = "Shell", .action = .shell }, .{ .word = "Font", .action = .font, .availability = .font_picker }, @@ -827,6 +857,17 @@ pub const Runtime = struct { if (percent > 100) return false; state.window_blur = percent; }, + // Bare, it returns to the default directory. + .dump_dir => if (!state.dump_dir.set(std.mem.trim(u8, argument orelse "", " \t\r\n"))) 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; + switch (which) { + inline else => |w| @field(state, "message_" ++ @tagName(w) ++ "_ms") = ms, + } + }, .transition => |effect| state.toggleTransition(effect), .scene => |effect| switch (effect) { inline else => |field| { @@ -847,6 +888,9 @@ pub const Runtime = struct { compiled_default_shell: []const u8, gui_shader_source_mode: ?[]const u8 = null, hover_delay_frames: ?u16, + /// Where dumps go when `DumpDir` is unset; empty without a host + /// filesystem. + default_dump_dir: []const u8 = "", native_images: bool, capabilities: Capabilities, state: *const Runtime, @@ -895,6 +939,13 @@ pub const Runtime = struct { else try out.print("{s} unsupported\n", .{setting.word}); }, + .dump_dir => { + const dir = if (state.dump_dir.len > 0) state.dump_dir.get() else context.default_dump_dir; + try out.print("{s} {s}\n", .{ setting.word, if (dir.len > 0) dir else "(none)" }); + }, + .message_ms => |which| try out.print("{s} {d}\n", .{ setting.word, switch (which) { + inline else => |w| @field(state, "message_" ++ @tagName(w) ++ "_ms"), + } }), .shell => { const chosen = state.shell.requested.get(); try out.print( @@ -993,7 +1044,7 @@ pub const Runtime = struct { for (settings[i + 1 ..]) |later| try std.testing.expect(!std.mem.eql(u8, setting.word, later.word)); try std.testing.expectEqual(switch (setting.action) { - .shell, .theme, .font, .tagline_size, .window_opacity, .window_blur, .toggle => true, + .shell, .theme, .font, .tagline_size, .window_opacity, .window_blur, .message_ms, .dump_dir, .toggle => true, else => false, }, setting.takesArg()); } @@ -1152,6 +1203,8 @@ pub const Runtime = struct { .tagline_size => "73", .window_opacity => "85", .window_blur => "40", + .message_ms => "1500", + .dump_dir => "~/dumps", else => null, }; try std.testing.expect(apply(&state, setting, argument)); @@ -1170,11 +1223,18 @@ pub const Runtime = struct { .column_tags => "ColumnTags off\n", .syntax_bold => "SyntaxBold on\n", .verbose => "Verbose off\n", + .message_animation => "MessageAnimation off\n", }, .shell => "Shell requested (new panes) fish\n", .tagline_size => "TaglineSize 73\n", .window_opacity => "WindowOpacity 85 (pending)\n", .window_blur => "WindowBlur 40\n", + .dump_dir => "DumpDir ~/dumps\n", + .message_ms => |which| switch (which) { + .linger => "MessageLinger 1500\n", + .fall => "MessageFall 1500\n", + .dissolve => "MessageDissolve 1500\n", + }, .transition => |transition| switch (transition) { .off => unreachable, .slide => "Panel transition PanelSlide\n", diff --git a/src/detached/server.zig b/src/detached/server.zig index 3e98fc9d..6959e577 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -536,7 +536,7 @@ pub const Session = struct { fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { const s = of(ctx); var pbuf: [1024:0]u8 = undefined; - const path = pardes.dump.outPath(&pbuf) orelse return; + const path = pardes.dump.outPath(&pbuf, s.core.settings.dump_dir.get()) orelse return; filesystem.write(s.core, path, bytes) catch |err| return s.core.reportError(0, "dump", err); s.core.setLastDump(path); } @@ -809,8 +809,11 @@ pub const Session = struct { // The wait is the 9P connections' turn with the core. if (n == 0) { pardes.turn.rest(); - defer pardes.turn.wake(); - return nap(if (timeout_ms == 0) 16 else timeout_ms); + nap(if (timeout_ms == 0) 16 else timeout_ms); + pardes.turn.wake(); + // An animating frame's wait is the frame: tick it. + if (timeout_ms != 0) s.core.update(.tick); + return; } var timeout: c_int = if (timeout_ms == 0) -1 else @intCast(@min(timeout_ms, std.math.maxInt(c_int))); if (s.nextWake(now)) |due| timeout = if (timeout < 0) due else @min(timeout, due); @@ -819,6 +822,9 @@ pub const Session = struct { const ready = libc.poll(&fds, @intCast(n), timeout); pardes.turn.wake(); if (ready > 0) s.dispatch(fds[0..n], src[0..n]); + // Animating, the frame's time is up: advance it. There is no other + // tick in a detached session, and without it an animation never ends. + if (timeout_ms != 0 and monotonicMs() -| now >= timeout_ms) s.core.update(.tick); _ = s.drainCompletions(true); s.expire(monotonicMs()); s.harvest(); @@ -1156,7 +1162,7 @@ pub fn run(init: std.process.Init, opts: pardes.Options, name: []const u8) !void try session.core.pump(h); if (session.core.quit) break; if (session.core.takeRestore()) |path| restore: { - const bytes = filesystem.readRestore(gpa, path) catch |err| { + const bytes = filesystem.readRestore(gpa, path, session.core.settings.dump_dir.get()) catch |err| { session.core.reportError(session.core.active, "Restore", err); break :restore; }; diff --git a/src/dump.zig b/src/dump.zig index 89abd995..ff5d2166 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -11,11 +11,11 @@ const log = std.log.scoped(.dump); /// pins it for deterministic goldens); else $XDG_DATA_HOME|~/.local/share /// /pardes/pardes-.zon — timestamped so dumps never overwrite each other. /// Creates the pardes dir (parents assumed; a failure surfaces at open). -pub fn outPath(buf: *[1024:0]u8) ?[:0]const u8 { +pub fn outPath(buf: *[1024:0]u8, dir_setting: []const u8) ?[:0]const u8 { if (std.c.getenv("PARDES_DUMP")) |p| return std.fmt.bufPrintSentinel(buf, "{s}", .{std.mem.span(p)}, 0) catch null; var dir_buf: [900]u8 = undefined; - const dir = defaultDirectory(&dir_buf) orelse return null; + 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; @@ -32,6 +32,15 @@ pub fn outPath(buf: *[1024:0]u8) ?[:0]const u8 { ds.getSecondsIntoMinute(), }, 0) catch null; } +/// Where dumps go and relative Restore names are looked up: the `DumpDir` +/// setting when set (a leading `~/` is the home directory), else the default. +pub fn directory(buf: []u8, dir_setting: []const u8) ?[]const u8 { + if (dir_setting.len == 0) return defaultDirectory(buf); + if (std.mem.startsWith(u8, dir_setting, "~/")) if (std.c.getenv("HOME")) |h| + return std.fmt.bufPrint(buf, "{s}/{s}", .{ std.mem.span(h), dir_setting[2..] }) catch null; + return std.fmt.bufPrint(buf, "{s}", .{dir_setting}) catch null; +} + /// The standard dump directory, without creating it or generating a filename. pub fn defaultDirectory(buf: []u8) ?[]const u8 { if (std.c.getenv("XDG_DATA_HOME")) |x| @@ -69,8 +78,14 @@ pub const PaneKind = enum { pub const Terminal = struct { cwd: []const u8 = "", + /// The rendered scrollback and screen as plain text, one row per line. stream: []const u8 = "", stream_b64: []const u8 = "", + /// `stream_b64` is the emulator's primary screen and scrollback as clean + /// VT (ghostty's formatter), which replays to what the screen showed. + /// Absent (older dumps), it is the raw tail of the pty's output, which + /// replays faithfully only if it holds the whole session at one size. + stream_is_screen: bool = false, cursor: Cursor = .{}, }; diff --git a/src/fs.zig b/src/fs.zig index 85eae825..84ab3b95 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -1104,9 +1104,9 @@ pub fn readFile(gpa: std.mem.Allocator, path: []const u8) ![]u8 { /// Restore first tries a relative argument under the default dump directory, /// then preserves the ordinary file lookup. Absolute paths remain verbatim. -pub fn readRestore(gpa: std.mem.Allocator, path: []const u8) ![]u8 { +pub fn readRestore(gpa: std.mem.Allocator, path: []const u8, dir_setting: []const u8) ![]u8 { var dir_buf: [4096]u8 = undefined; - const dir = @import("dump.zig").defaultDirectory(&dir_buf); + const dir = @import("dump.zig").directory(&dir_buf, dir_setting); return readRestoreIn(gpa, path, dir); } diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 17bdb46f..7f28124c 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -2111,8 +2111,8 @@ fn runNative(init: std.process.Init, opts_in: pardes.Options, attach: ?[]const u } var win_flags: c.SDL_WindowFlags = c.SDL_WINDOW_RESIZABLE; if (!test_mode) win_flags |= c.SDL_WINDOW_HIGH_PIXEL_DENSITY; - // A latency run renders to the capture texture; keep it off the desktop. - if (latency_fd >= 0) win_flags |= c.SDL_WINDOW_HIDDEN; + // A test run renders to the capture texture; keep it off the desktop. + if (test_mode) win_flags |= c.SDL_WINDOW_HIDDEN; 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. @@ -2353,6 +2353,7 @@ fn localSession( } else try pardes.Pardes.init(allocs.pardes, opts); defer core.deinit(); core.native_images = true; + core.native_image_patches = true; observeGuiFont(g, core); syncTaglineFont(g, core); @@ -2448,7 +2449,7 @@ fn localSession( } } if (core.takeRestore()) |rp| blk: { - const bytes = filesystem.readRestore(gpa, rp) catch |err| { + const bytes = filesystem.readRestore(gpa, rp, core.settings.dump_dir.get()) catch |err| { core.reportError(core.active, "Restore", err); break :blk; }; @@ -2473,6 +2474,7 @@ fn localSession( g.presented_images.clearRetainingCapacity(); g.prepared_images.clearRetainingCapacity(); nc.native_images = true; + nc.native_image_patches = true; nc.host = host; if (fs) |f| f.reset(nc); core.deinit(); @@ -3591,6 +3593,7 @@ const Shell = struct { test_mode: bool = false, feed: StdinFeed = .{}, presented: bool = false, + skipped_presents: u8 = 0, surface: ?*pardes.Surface = null, animation_clock: AnimationClock = .{}, saw_event: bool = false, @@ -3774,14 +3777,29 @@ fn waitInput(ctx: ?*anyopaque, timeout_ms: u32) void { var in: Input = .{ .core = core }; if (s.gui) |g| { var sev = std.mem.zeroes(c.SDL_Event); - const ms: c_int = if (timeout_ms != 0) @intCast(timeout_ms) else 16; + // A latency trace is fed on stdin, whose poll below paces the loop: + // waiting here too would make every tick cost two frames. + const ms: c_int = if (latency_fd >= 0) 0 else if (timeout_ms != 0) @intCast(timeout_ms) else 16; // The wait is the 9P connections' turn with the core. pardes.turn.rest(); const got = c.SDL_WaitEventTimeout(&sev, ms); pardes.turn.wake(); if (got) { - dispatch(g, &in, &sev); - while (c.SDL_PollEvent(&sev)) dispatch(g, &in, &sev); + // A run of queued motions is one move to its last position (the + // handler reads only absolute x/y and held buttons): acting on + // each would repeat hover and selection work the next undoes. + var motion: ?c.SDL_Event = null; + while (true) { + if (sev.type == c.SDL_EVENT_MOUSE_MOTION) { + motion = sev; + } else { + if (motion) |*m| dispatch(g, &in, m); + motion = null; + dispatch(g, &in, &sev); + } + if (!c.SDL_PollEvent(&sev)) break; + } + if (motion) |*m| dispatch(g, &in, m); } } if (s.test_mode) { @@ -3913,6 +3931,10 @@ fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) void { log.err("render: {t}", .{err}); break :blk false; }; + // A skipped swapchain image would otherwise hide this input's frame until + // the next event. A few retries only: a minimized window never gets one. + s.skipped_presents = if (s.presented) 0 else s.skipped_presents +| 1; + if (!s.presented and s.skipped_presents <= 3) core.present_skipped = true; if (g.scene_target_failed) { g.scene_failures +|= 1; log.err("scene target unavailable (attempt {d}/3)", .{g.scene_failures}); @@ -3926,7 +3948,12 @@ fn present(ctx: ?*anyopaque, surface: *const pardes.Surface) void { fn postPresent(ctx: ?*anyopaque) void { const s = shellOf(ctx); const g = s.gui orelse return; - if (!s.presented) return; + if (!s.presented) { + // No image (a minimized window): time still passes, so a lingering + // message or a hover wait runs out instead of redrawing forever. + if (s.animation_clock.due(s.core.animationActive(), c.SDL_GetTicksNS())) s.core.update(.tick); + return; + } const frame = s.surface orelse return; refreshPresentedPointer(g, s.core); finishPresentedAnimationFrame( @@ -4030,7 +4057,7 @@ fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) vo fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { const s = shellOf(ctx); var pbuf: [1024:0]u8 = undefined; - const path = pardes.dump.outPath(&pbuf) orelse return; + const path = pardes.dump.outPath(&pbuf, s.core.settings.dump_dir.get()) orelse return; filesystem.write(s.core, path, bytes) catch |err| return s.core.reportError(0, "dump", err); s.core.setLastDump(path); } @@ -4533,6 +4560,23 @@ fn uploadNativeTexture( const byte_len = validImageBytes(place) orelse return error.BadImage; const key = place.cacheKey(); if (g.native_images.contains(key)) return; + if (comptime pardes.pdf_enabled) if (place.patch) |patch| patch: { + // The core changed only these rows since a revision we still hold: + // write them into that texture rather than sending the whole page. + var base = key; + base.revision = patch.from; + if (patch.y + patch.h > place.ih) break :patch; + const texture = g.native_images.get(base) orelse break :patch; + const row = place.iw * 4; + try uploadTextureRows(g, cmd, texture, place.rgba[patch.y * row ..][0 .. patch.h * row], place.iw, patch.y, patch.h); + try g.native_images.put(gpa, key, texture); + _ = g.native_images.remove(base); + // A transition snapshot of the last frame follows its texture. + for (g.presented_images.items) |*saved| if (saved.key.eql(base)) { + saved.key = key; + }; + return; + }; var tex_info = std.mem.zeroes(c.SDL_GPUTextureCreateInfo); tex_info.type = c.SDL_GPU_TEXTURETYPE_2D; @@ -4545,39 +4589,51 @@ fn uploadNativeTexture( tex_info.sample_count = c.SDL_GPU_SAMPLECOUNT_1; const texture = c.SDL_CreateGPUTexture(g.device, &tex_info) orelse return error.GpuCreate; errdefer c.SDL_ReleaseGPUTexture(g.device, texture); + try uploadTextureRows(g, cmd, texture, place.rgba[0..byte_len], place.iw, 0, place.ih); + try g.native_images.put(gpa, key, texture); +} +/// Copy `rows` rows of RGBA, `width` pixels each, into `texture` at row `y`. +fn uploadTextureRows( + g: *Gui, + cmd: *c.SDL_GPUCommandBuffer, + texture: *c.SDL_GPUTexture, + rgba: []const u8, + width: usize, + y: usize, + rows: usize, +) !void { var xf_info = c.SDL_GPUTransferBufferCreateInfo{ .usage = c.SDL_GPU_TRANSFERBUFFERUSAGE_UPLOAD, - .size = byte_len, + .size = @intCast(rgba.len), .props = 0, }; const transfer = c.SDL_CreateGPUTransferBuffer(g.device, &xf_info) orelse return error.GpuCreate; defer c.SDL_ReleaseGPUTransferBuffer(g.device, transfer); const mapped: [*]u8 = @ptrCast(c.SDL_MapGPUTransferBuffer(g.device, transfer, false) orelse return error.GpuMap); - @memcpy(mapped[0..byte_len], place.rgba); + @memcpy(mapped[0..rgba.len], rgba); c.SDL_UnmapGPUTransferBuffer(g.device, transfer); const copy = c.SDL_BeginGPUCopyPass(cmd); const src = c.SDL_GPUTextureTransferInfo{ .transfer_buffer = transfer, .offset = 0, - .pixels_per_row = @intCast(place.iw), - .rows_per_layer = @intCast(place.ih), + .pixels_per_row = @intCast(width), + .rows_per_layer = @intCast(rows), }; const dst = c.SDL_GPUTextureRegion{ .texture = texture, .mip_level = 0, .layer = 0, .x = 0, - .y = 0, + .y = @intCast(y), .z = 0, - .w = @intCast(place.iw), - .h = @intCast(place.ih), + .w = @intCast(width), + .h = @intCast(rows), .d = 1, }; c.SDL_UploadToGPUTexture(copy, &src, &dst, false); c.SDL_EndGPUCopyPass(copy); - try g.native_images.put(gpa, key, texture); } fn appendPreparedImage( @@ -5442,16 +5498,30 @@ fn emitTagLayer(g: *Gui, instances: [*]CellInstance, next: *u32, layer: *const p const left = @as(f32, @floatFromInt(layer.viewport.x)) * bw; const right = left + @as(f32, @floatFromInt(layer.viewport.w)) * bw; const background: pardes.Cell = .{ .default = false, .style = .{ .bg = .{ .rgb = layer.bg } } }; - emitInstance(g, instances, next.*, 0, layer.viewport.y, .{ .w = right - left, .h = bh, .x_off = left, .y_off = 0 }, win_w, win_h, track, .body, &background, old_layer, false, page); + // A band sliding into place is drawn offset and cut at its row's top, so + // it comes out from under whatever is above it. + const slide = layer.slide * bh; + const top = @as(f32, @floatFromInt(layer.viewport.y)) * bh; + emitInstance(g, instances, next.*, 0, layer.viewport.y, .{ .w = right - left, .h = bh, .x_off = left, .y_off = slide }, win_w, win_h, track, .body, &background, old_layer, false, page); + if (slide != 0) clipInstanceTop(&instances[next.*], top, win_h); next.* += 1; for (0..tagLayerCellCount(g, layer)) |col| { const cursor = if (layer.cursor) |cu| show_cursor and !cu.bar and cu.col == col else false; - emitInstance(g, instances, next.*, @intCast(col), layer.viewport.y, .{ .w = tw, .h = bh, .x_off = left, .y_off = 0 }, win_w, win_h, track, .tagline, &layer.cells[col], old_layer, cursor, page); + emitInstance(g, instances, next.*, @intCast(col), layer.viewport.y, .{ .w = tw, .h = bh, .x_off = left, .y_off = slide }, win_w, win_h, track, .tagline, &layer.cells[col], old_layer, cursor, page); clipInstanceRight(&instances[next.*], right, win_w); + if (slide != 0) clipInstanceTop(&instances[next.*], top, win_h); next.* += 1; } } +fn clipInstanceTop(instance: *CellInstance, top: f32, win_h: f32) void { + const limit = 1 - top / win_h * 2; + if (instance.y0 <= limit) return; + const fraction = std.math.clamp((limit - instance.y1) / (instance.y0 - instance.y1), 0, 1); + instance.v0 = instance.v1 + (instance.v0 - instance.v1) * fraction; + instance.y0 = @max(instance.y1, limit); +} + fn bodyLayerAt(surface: *const pardes.Surface, col: u16, row: u16) ?*const pardes.BodyLayer { return bodyLayerIn(surface.bodyLayers(), col, row); } @@ -6436,7 +6506,9 @@ fn captureFrame(g: *Gui, gpa: std.mem.Allocator, cmd: *c.SDL_GPUCommandBuffer, t } fn writeCapturePpm(g: *Gui, gpa: std.mem.Allocator, pixels: []const u8, width: u32, height: u32) !void { - if (g.capture_dir.len == 0) return; + // A latency trace times frames, and an 8 MB file write per frame would + // stall the loop it is timing. + if (g.capture_dir.len == 0 or latency_fd >= 0) return; const bpp = c.SDL_GPUTextureFormatTexelBlockSize(g.swapchain_format); if (bpp != 4) return error.UnsupportedCaptureFormat; const bgr = switch (g.swapchain_format) { diff --git a/src/macos.zig b/src/macos.zig index a7ee3164..c359eb3f 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -1325,7 +1325,7 @@ export fn pardes_tick() bool { fn restoreCore(st: *State) bool { if (st.core.quit) return false; const path = st.core.takeRestore() orelse return false; - const bytes = filesystem.readRestore(st.gpa, path) catch |err| { + const bytes = filesystem.readRestore(st.gpa, path, st.core.settings.dump_dir.get()) catch |err| { st.core.reportError(st.core.active, "Restore", err); return false; }; @@ -2431,7 +2431,7 @@ fn writeFile(ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) vo fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { const st = hostState(ctx); var pbuf: [1024:0]u8 = undefined; - const path = pardes.dump.outPath(&pbuf) orelse return; + const path = pardes.dump.outPath(&pbuf, st.core.settings.dump_dir.get()) orelse return; filesystem.write(st.core, path, bytes) catch |err| return st.core.reportError(0, "dump", err); st.core.setLastDump(path); } diff --git a/src/panes.zig b/src/panes.zig index b3424385..8d4330e9 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -183,6 +183,20 @@ pub const Pane = struct { tty_filter: bool = false, msg: [256]u8 = undefined, msg_len: u16 = 0, + /// Where the newest message line is in its life. + msg_life: MessageLife = .{}, + /// The row (among the notice rows) the newest line holds for its life. + msg_slot: u8 = 0, + /// Earlier message lines still on screen, oldest first, each running its + /// own life: a new message stacks under them instead of replacing them. + msg_older: [message_stack]OlderMessage = undefined, + msg_older_len: u8 = 0, + /// The newest line is a builtin announcing itself in this step: what + /// the step says next replaces it rather than stacking under it. + msg_announcement: bool = false, + /// The newest line is a status (progress, a server's state): the next + /// line replaces it rather than stacking under it. + msg_status: bool = false, /// The transient lines this pane shows between its body and its tagline: /// a builtin's message, the pending leader chord, a prompt waiting for /// input. Rebuilt every frame from the state that owns each one, so a @@ -192,30 +206,102 @@ pub const Pane = struct { /// reserves rows for sticky context headers. notices: Notices = .{}, + pub const MessagePhase = enum { entering, shown, lingering, leaving }; + /// One message line's animation: falling in, shown, lingering after the + /// key or click that dismissed it, dissolving. `frame` counts animation + /// frames within the phase. + pub const MessageLife = struct { + phase: MessagePhase = .shown, + frame: u16 = 0, + /// Dismissed while still falling: it lingers once it has landed. + dismissed: bool = false, + }; + /// Older message lines kept on screen under a new one. + pub const message_stack = 3; + pub const OlderMessage = struct { + text: [256]u8 = undefined, + len: u16 = 0, + life: MessageLife = .{}, + slot: u8 = 0, + + pub fn slice(line: *const OlderMessage) []const u8 { + return line.text[0..line.len]; + } + }; + + /// Move the newest line onto the stack of older ones, dropping the oldest + /// when it is full; the newest slot is left empty for what arrives. + pub fn pushOlderMessage(pane: *Pane) void { + if (pane.msg_older_len == message_stack) { + std.mem.copyForwards(OlderMessage, pane.msg_older[0 .. message_stack - 1], pane.msg_older[1..]); + pane.msg_older_len -= 1; + } + pane.msg_older[pane.msg_older_len] = .{ .text = pane.msg, .len = pane.msg_len, .life = pane.msg_life, .slot = pane.msg_slot }; + pane.msg_older_len += 1; + pane.msg_len = 0; + pane.msg_life = .{}; + } + + /// The first row no older line holds. A line keeps its row until it + /// leaves, and a new one fills the first gap: nothing on screen moves. + pub fn freeMessageSlot(pane: *const Pane) u8 { + var used: u8 = 0; + for (pane.msg_older[0..pane.msg_older_len]) |line| used |= @as(u8, 1) << @intCast(line.slot); + var slot: u8 = 0; + while (used & (@as(u8, 1) << @intCast(slot)) != 0) slot += 1; + return slot; + } + + pub fn removeOlderMessage(pane: *Pane, i: usize) void { + std.mem.copyForwards(OlderMessage, pane.msg_older[i .. pane.msg_older_len - 1], pane.msg_older[i + 1 .. pane.msg_older_len]); + pane.msg_older_len -= 1; + } + pub const Notices = struct { /// Painted bottom-up in this order, so a prompt keeps the row nearest /// the tagline that it has always had, and its cursor with it. - pub const Kind = enum { message, leader, prompt }; - pub const max = @typeInfo(Kind).@"enum".fields.len; + /// `older` is an earlier message line still on screen; `index` says + /// which (`Pane.msg_older`). + pub const Kind = enum { older, message, leader, prompt }; + pub const max = @typeInfo(Kind).@"enum".fields.len - 1 + message_stack; kinds: [max]Kind = undefined, + index: [max]u8 = @splat(0), + /// Each band's row below the body's top: message lines keep theirs, + /// so a band that leaves leaves a gap rather than moving the rest. + row: [max]u8 = @splat(0), /// Where each band's chip starts, as an absolute grid column. A chip /// is only as wide as its own text, so the rest of the row underneath /// is ordinary body text and a click there has to reach it. left: [max]u16 = @splat(std.math.maxInt(u16)), len: u8 = 0, + /// A band on the next row after every band so far. pub fn push(n: *Notices, kind: Kind) void { + n.pushAt(kind, 0, n.span()); + } + + pub fn pushAt(n: *Notices, kind: Kind, index: u8, row: u8) void { if (n.len >= max) return; n.kinds[n.len] = kind; + n.index[n.len] = index; + n.row[n.len] = row; n.left[n.len] = std.math.maxInt(u16); n.len += 1; } /// Is this cell inside the chip drawn for band `i`? Nothing else on /// that row belongs to the notice. - pub fn covers(n: *const Notices, i: usize, col: u16) bool { - return i < n.len and col >= n.left[i]; + pub fn covers(n: *const Notices, row: usize, col: u16) bool { + for (0..n.len) |i| if (n.row[i] == row) return col >= n.left[i]; + return false; + } + + /// Rows from the body's top down to the last band's. + pub fn span(n: *const Notices) u8 { + var rows: u8 = 0; + for (n.row[0..n.len]) |row| rows = @max(rows, row + 1); + return rows; } pub fn slice(n: *const Notices) []const Kind { @@ -1327,7 +1413,15 @@ pub const File = struct { 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)); - try std.testing.expectEqual(@as(usize, 0), file.line_starts.len); + // 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); @@ -1546,6 +1640,80 @@ pub const File = struct { 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); @@ -1760,12 +1928,13 @@ pub const File = struct { 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 = &.{}; + f.line_starts = starts; if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); f.highlights = &.{}; f.highlight_start = 0; @@ -2864,7 +3033,10 @@ pub const Output = struct { pub fn openConfig(p: *Pardes, id: usize) !void { var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); + var dir_buf: [1024]u8 = undefined; + const host_fs = comptime (pardes.platform != .web and pardes.platform != .esp32p4); try config.Runtime.writeReport(&out.writer, .{ + .default_dump_dir = if (host_fs) (pardes.dump.defaultDirectory(&dir_buf) orelse "") else "", .startup_config_path = p.opts.startup_config_path, .platform = @tagName(pardes.platform), .theme_name = p.theme().name, @@ -3599,6 +3771,9 @@ pub const Pdf = struct { const Page = struct { page: usize, items: []const Highlight }; pages: [3]Page = undefined, len: usize = 0, + /// Repaint whenever the set changes, not only when a page's raster was + /// invalidated (`HighlightInput.live`). + live: bool = false, pub fn forPage(highlights: @This(), page: usize) []const Highlight { for (highlights.pages[0..highlights.len]) |group| @@ -3612,6 +3787,7 @@ pub const Pdf = struct { hover_page: ?usize = null, hover_color: [3]u8, selection_color: [3]u8, + live: bool = false, } else void; pub fn buildHighlights( @@ -3623,7 +3799,7 @@ pub const Pdf = struct { const search_len = if (state.search_results) |results| results.quads.len else 0; const selection_len = if (state.selection) |selection| selection.quads.len else 0; const items = try arena.alloc(Highlight, input.hover_quads.len + search_len + selection_len); - var result: Highlights = .{}; + var result: Highlights = .{ .live = input.live }; var n: usize = 0; // Hover, search and selection can belong to three different pages. // Group them once so raster rendering can borrow a contiguous slice. @@ -3721,6 +3897,19 @@ pub const Pdf = struct { decorated: bool = false, tint_key: ?TintKey = null, revision: u32 = 0, + /// `rgba` before its highlights and tint, kept once the page has been + /// highlighted: a highlight change repaints rows from it instead of + /// rendering the page again. + clean: []u8 = &.{}, + /// The highlights baked into `rgba` (gpa-owned), so a change repaints + /// only the rows of the quads that differ. + baked: []Highlight = &.{}, + /// `baked` is a true record (false after a render could not copy it). + baked_valid: bool = false, + /// Page rows changed since revision `patch_from`, the one last handed + /// to a shell; 0 when the pixels were replaced wholesale since. + patch_from: u32 = 0, + patch_rows: pdf.Document.Rows = .{ .start = 0, .end = 0 }, } else void; pub const SectionsOutput = if (enabled) struct { @@ -3894,6 +4083,8 @@ pub const Pdf = struct { } fn retireRaster(state: *@This(), gpa: std.mem.Allocator, raster: *Raster) void { + if (raster.clean.len > 0) gpa.free(raster.clean); + gpa.free(raster.baked); state.retireRgba(gpa, raster.rgba); raster.* = .{}; } @@ -4138,8 +4329,11 @@ pub const Pdf = struct { pub fn deinit(state: *@This(), gpa: std.mem.Allocator) void { gpa.free(state.path); - for (state.rasters[0..state.rasters_len]) |raster| + for (state.rasters[0..state.rasters_len]) |raster| { if (raster.rgba.len > 0) gpa.free(raster.rgba); + if (raster.clean.len > 0) gpa.free(raster.clean); + gpa.free(raster.baked); + } for (state.spare[0..state.spare_len]) |rgba| gpa.free(rgba); gpa.free(state.page_sizes); gpa.free(state.page_starts); @@ -4614,16 +4808,27 @@ pub const Pdf = struct { const slot = raster.?; const page_highlights = highlights.forPage(page); const decorated = page_highlights.len > 0; - const stale = !slot.tried or !slot.request_valid or - !slot.request.eql(request) or slot.decorated != decorated or + const base_stale = !slot.request_valid or !slot.request.eql(request) or slot.tint_key == null or !slot.tint_key.?.eql(tint_key) or slot.rgba.len == 0 or slot.band_h == 0; - const uncovered = !stale and uncovered: { + const uncovered = !base_stale and uncovered: { const want = wantedBand(state, viewport, page, slotShape(slot), is_flinging); break :uncovered slot.band_y > want.y or slot.band_y + slot.band_h < want.y + want.height; }; - if (!stale and !uncovered) continue; + if (!base_stale and !uncovered) { + if (slot.tried and slot.decorated == decorated and + !(highlights.live and !sameHighlights(slot.baked, page_highlights))) continue; + // Invalidated, but it already shows exactly these highlights + // (a preview withdrawn that was never drawn, on every pointer + // move over a page): nothing to render. + if (slot.baked_valid and sameHighlights(slot.baked, page_highlights)) { + slot.tried = true; + continue; + } + // Only the highlights moved: repaint their rows in place. + if (repaintHighlights(state, gpa, slot, request, tint_key, page_highlights)) continue; + } slot.tried = true; slot.request = request; @@ -4640,15 +4845,27 @@ pub const Pdf = struct { { const tz_render = tracy.zone(@src(), "pdf.render_into"); defer tz_render.end(); + // A highlighted page keeps its clean rows for repaints. + const keep_clean = pardes.platform != .macos and (decorated or slot.clean.len > 0); state.document.renderIntoAtWithPaper( page, request, shape, want, - page_highlights, + if (keep_clean) &.{} else page_highlights, fresh, pardes.platform == .macos, ) catch break :filled false; + if (slot.clean.len != 0 and (!keep_clean or slot.clean.len != fresh.len)) { + gpa.free(slot.clean); + slot.clean = &.{}; + } + if (keep_clean) { + if (slot.clean.len == 0) slot.clean = gpa.alloc(u8, fresh.len) catch &.{}; + if (slot.clean.len == fresh.len) @memcpy(slot.clean, fresh); + state.document.paintHighlightsAt(page, request, shape, want, page_highlights, fresh) catch + break :filled false; + } } const tz_tint = tracy.zone(@src(), "pdf.tint"); defer tz_tint.end(); @@ -4658,6 +4875,9 @@ pub const Pdf = struct { }; if (!filled) { state.retireRgba(gpa, fresh); + // `clean` may already hold the band that failed. + if (slot.clean.len > 0) gpa.free(slot.clean); + slot.clean = &.{}; continue; } @@ -4669,6 +4889,18 @@ pub const Pdf = struct { slot.band_h = want.height; slot.decorated = decorated; slot.tint_key = tint_key; + if (gpa.dupe(Highlight, page_highlights)) |copy| { + gpa.free(slot.baked); + slot.baked = copy; + slot.baked_valid = true; + } else |_| { + // Unrecorded highlights cannot be compared or diffed. + slot.baked_valid = false; + if (slot.clean.len > 0) gpa.free(slot.clean); + slot.clean = &.{}; + } + slot.patch_from = 0; + slot.patch_rows = .{ .start = 0, .end = 0 }; state.next_raster_revision +%= 1; if (state.next_raster_revision == 0) state.next_raster_revision = 1; slot.revision = state.next_raster_revision; @@ -4676,6 +4908,114 @@ pub const Pdf = struct { state.trimSpares(gpa); } + /// Repaint only the rows where the old and new highlights differ: the + /// clean rows kept from the page's last render, MuPDF's highlight pass + /// (the whole new set) over them, the per-pixel tint — the operations a + /// full render performs, in its order, on fewer rows and without running + /// the page again. False leaves the slot for the full path. + fn repaintHighlights( + state: *State, + gpa: std.mem.Allocator, + slot: *Raster, + request: RenderRequest, + tint_key: TintKey, + page_highlights: []const Highlight, + ) bool { + const tz = tracy.zone(@src(), "pdf.repaint_highlights"); + defer tz.end(); + if (slot.clean.len != slot.rgba.len or !slot.baked_valid) return false; + if (sameHighlights(slot.baked, page_highlights)) { + slot.tried = true; + return true; + } + const baked = gpa.dupe(Highlight, page_highlights) catch return false; + const changed = changedHighlights(gpa, slot.baked, page_highlights) catch { + gpa.free(baked); + return false; + }; + defer gpa.free(changed); + var dirty = state.document.highlightRows(slot.page, request, changed) catch { + gpa.free(baked); + return false; + }; + slot.tried = true; + dirty.start = @max(dirty.start, slot.band_y); + dirty.end = @min(dirty.end, slot.band_y + slot.band_h); + if (dirty.start < dirty.end) { + const shape = slotShape(slot); + const band = shape.band(dirty.start, dirty.end - dirty.start); + const offset = (dirty.start - slot.band_y) * shape.stride; + const out = slot.rgba[offset..][0..band.len]; + @memcpy(out, slot.clean[offset..][0..band.len]); + // On failure the rows are half-made: let the full path redo them. + state.document.paintHighlightsAt(slot.page, request, shape, band, page_highlights, out) catch { + gpa.free(baked); + slot.tried = false; + return false; + }; + pdf.tintRgba(out, tint_key.mode, tint_key.colors) catch { + gpa.free(baked); + slot.tried = false; + return false; + }; + slot.patch_rows = unionRows(slot.patch_rows, dirty); + state.next_raster_revision +%= 1; + if (state.next_raster_revision == 0) state.next_raster_revision = 1; + slot.revision = state.next_raster_revision; + } + gpa.free(slot.baked); + slot.baked = baked; + slot.decorated = page_highlights.len > 0; + return true; + } + + fn sameHighlights(a: []const Highlight, b: []const Highlight) bool { + return std.mem.eql(u8, std.mem.sliceAsBytes(a), std.mem.sliceAsBytes(b)); + } + + /// The highlights in one set and not the other, as multisets (a quad + /// painted twice blends twice). When only the order changed, blending + /// order did, so everything counts. + // ponytail: quadratic match; past 64k comparisons every quad counts. + fn changedHighlights(gpa: std.mem.Allocator, old: []const Highlight, new: []const Highlight) ![]Highlight { + const out = try gpa.alloc(Highlight, old.len + new.len); + errdefer gpa.free(out); + var n: usize = 0; + if (old.len * new.len <= 1 << 16) { + const matched = try gpa.alloc(bool, new.len); + defer gpa.free(matched); + @memset(matched, false); + for (old) |h| { + for (new, matched) |candidate, *used| { + if (!used.* and std.mem.eql(u8, std.mem.asBytes(&h), std.mem.asBytes(&candidate))) { + used.* = true; + break; + } + } else { + out[n] = h; + n += 1; + } + } + for (new, matched) |h, used| if (!used) { + out[n] = h; + n += 1; + }; + } + if (n == 0) { + @memcpy(out[0..old.len], old); + @memcpy(out[old.len..], new); + return out; + } + // Freed by length: hand back exactly what the caller will free. + return gpa.realloc(out, n); + } + + fn unionRows(a: pdf.Document.Rows, b: pdf.Document.Rows) pdf.Document.Rows { + if (a.start >= a.end) return b; + if (b.start >= b.end) return a; + return .{ .start = @min(a.start, b.start), .end = @max(a.end, b.end) }; + } + pub fn renderFrame( state: *State, gpa: std.mem.Allocator, @@ -5837,6 +6177,7 @@ pub const Pdf = struct { .hover_page = hover_page, .hover_color = if (link_hover) core.theme().box else selection_color, .selection_color = selection_color, + .live = core.native_image_patches, }; } @@ -5907,6 +6248,16 @@ pub const Pdf = struct { const visible_end = visible.first + visible.len; while (page < visible_end) : (page += 1) { const placed = placedRaster(state, view, page) orelse continue; + const slot = rasterForPage(state, page).?; + const patch: ?pardes.ImagePatch = if (slot.patch_from != 0 and + slot.patch_rows.start < slot.patch_rows.end) + .{ + .from = slot.patch_from, + .y = @intCast(slot.patch_rows.start - slot.band_y), + .h = @intCast(slot.patch_rows.end - slot.patch_rows.start), + } + else + null; if (!core.appendImagePlace(.{ .pane = @intCast(pane_id), .serial = pane.serial, @@ -5928,14 +6279,18 @@ pub const Pdf = struct { .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.len, + .y = core.bodyTop(rect) + pane.notices.span(), .w = text_width, - .h = (rect.h -| pardes.BOX_H) -| pane.notices.len, + .h = (rect.h -| pardes.BOX_H) -| pane.notices.span(), .rgba = placed.rgba, .iw = placed.width, // The texture contains the retained band, not the full page. .ih = placed.band_height, + .patch = patch, })) break; + // A shell now holds (or will fetch whole) this revision. + slot.patch_from = slot.revision; + slot.patch_rows = .{ .start = 0, .end = 0 }; placed_any = true; } if (!placed_any) return false; @@ -6439,9 +6794,15 @@ pub const Terminal = struct { return pane; } - /// Rebuild a dump's dead terminal emulator. 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) !*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)); @@ -6450,12 +6811,28 @@ pub const Terminal = struct { pane.ovl = .{ .row = 0, .rows = 1, .text = try p.gpa.dupe(u8, terminal.stream) }; return pane; } - const bytes = if (terminal.stream_b64.len > 0) + // 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 (bytes.len > 0) { + 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) @@ -6613,7 +6990,7 @@ pub const Terminal = struct { .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); @@ -6624,6 +7001,58 @@ pub const Terminal = struct { try std.testing.expectEqualSlices(u8, try replayBytes(pane, gpa), try replayBytes(restored, gpa)); } + 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"); + try p.dumpState(); + const restored = try Pardes.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.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 { @@ -7247,6 +7676,16 @@ pub const Terminal = struct { 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, @@ -7318,7 +7757,8 @@ pub const Terminal = struct { .terminal = .{ .cwd = try arena.dupe(u8, pane.cwdSlice()), .stream = stream[0..len], - .stream_b64 = try dump.encodeBytes(arena, try replayBytes(pane, arena)), + .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, diff --git a/src/pardes.zig b/src/pardes.zig index cc57127f..fae14f47 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -2722,8 +2722,16 @@ test "Msg writes the transient row by hand, bare or with text, and input ends it try std.testing.expect(p.executeBuiltinLine(2, "Msg")); try std.testing.expectEqualStrings("Msg: NoMessage", row(p, 2)); - // A message is exactly as old as your last input. + // Input starts its exit: it lingers, dissolves, and is gone. p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqualStrings("Msg: NoMessage", row(p, 2)); + for (0..200) |_| p.update(.tick); + try std.testing.expectEqualStrings("", row(p, 2)); + // ...and with neither linger nor animation it is as old as your last input. + try std.testing.expect(p.executeBuiltinLine(2, "MessageAnimation off")); + try std.testing.expect(p.executeBuiltinLine(2, "MessageLinger 0")); + try std.testing.expect(p.executeBuiltinLine(2, "Msg gone")); + p.update(.{ .key = .{ .cp = 'h' } }); try std.testing.expectEqualStrings("", row(p, 2)); // Longer than the row's buffer is CUT, never refused and never overrun: @@ -2735,6 +2743,151 @@ test "Msg writes the transient row by hand, bare or with text, and input ends it try std.testing.expectEqual(p.panes[2].?.msg.len, row(p, 2).len); } +test "a message falls in, lingers past the input that dismisses it, and dissolves" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[p.active].?; + try std.testing.expect(p.settings.message_animation); + try std.testing.expect(p.executeBuiltinLine(p.active, "MessageLinger 160")); + try std.testing.expect(p.executeBuiltinLine(p.active, "Msg hello")); + try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); + try std.testing.expect(p.animationActive()); + // An ease-in fall: starts a whole row up, lands exactly on it. + const start = p.messageMotion(pane.msg_life); + try std.testing.expectEqual(@as(f32, -1), start.slide); + var last = start.slide; + for (0..Pardes.messageFrames(p.settings.message_fall_ms)) |_| { + p.needs_frame = false; + p.update(.tick); + // Every tick that moves it owes a frame, the landing one included. + try std.testing.expect(p.needs_frame); + const now = p.messageMotion(pane.msg_life); + try std.testing.expect(now.slide >= last); + last = now.slide; + } + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); + try std.testing.expectEqual(@as(f32, 0), p.messageMotion(pane.msg_life).slide); + try std.testing.expect(!p.animationActive()); + // Shown until input, like always; the same line again does not re-enter. + for (0..100) |_| p.update(.tick); + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); + try std.testing.expect(p.executeBuiltinLine(p.active, "Msg hello")); + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); + // Input (a key that announces nothing): 160 ms of lingering (ten frames), unaffected by more input... + p.update(.{ .key = .{ .cp = 'h' } }); + try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_life.phase); + for (0..9) |_| { + p.update(.tick); + p.update(.{ .key = .{ .cp = 'h' } }); + } + try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_life.phase); + p.update(.tick); + // ...then an ease-out dissolve toward nothing, and gone. + try std.testing.expectEqual(Pane.MessagePhase.leaving, pane.msg_life.phase); + var alpha: f32 = 1; + for (0..Pardes.messageFrames(p.settings.message_dissolve_ms)) |_| { + const now = p.messageMotion(pane.msg_life).alpha; + try std.testing.expect(now <= alpha); + alpha = now; + p.needs_frame = false; + p.update(.tick); + } + try std.testing.expectEqual(@as(u16, 0), pane.msg_len); + try std.testing.expect(!p.animationActive()); + // The tick that clears it still owes the frame that shows it gone. + try std.testing.expect(p.needs_frame); + + // Dismissed mid-fall: it lands, then lingers. + try std.testing.expect(p.executeBuiltinLine(p.active, "Msg again")); + try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); + p.update(.tick); + p.update(.{ .key = .{ .cp = 'h' } }); + try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); + for (0..Pardes.messageFrames(p.settings.message_fall_ms)) |_| p.update(.tick); + try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_life.phase); + // Shown again while lingering: fresh, so it stays; a status update to a + // line on screen swaps its text in place instead of falling again. + try std.testing.expect(p.executeBuiltinLine(p.active, "Msg again")); + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); + p.setStatus(p.active, "progress 50%"); + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); + try std.testing.expectEqualStrings("progress 50%", pane.msg[0..pane.msg_len]); + try std.testing.expectEqual(@as(u8, 0), pane.msg_older_len); + // The fall and the dissolve are timings of their own, in milliseconds. + try std.testing.expect(p.executeBuiltinLine(p.active, "MessageFall 48")); + try std.testing.expect(p.executeBuiltinLine(p.active, "MessageDissolve 0")); + try std.testing.expectEqual(@as(u16, 3), Pardes.messageFrames(p.settings.message_fall_ms)); + try std.testing.expectEqual(@as(u16, 1), Pardes.messageFrames(p.settings.message_dissolve_ms)); + // The Config 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")); + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); +} + +test "messages stack, oldest on top, each on its own timing" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 24 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[p.active].?; + try std.testing.expect(p.executeBuiltinLine(p.active, "Verbose off")); + try std.testing.expect(p.executeBuiltinLine(p.active, "MessageLinger 160")); + // `Verbose off` announced itself before it took effect. + pane.msg_len = 0; + pane.msg_life = .{}; + const fall = Pardes.messageFrames(p.settings.message_fall_ms); + p.setMessage(p.active, "first"); + for (0..fall) |_| p.update(.tick); + try std.testing.expectEqual(Pane.MessagePhase.shown, pane.msg_life.phase); + // A second message stacks under the first instead of replacing it. + p.setMessage(p.active, "second"); + try std.testing.expectEqual(@as(u8, 1), pane.msg_older_len); + try std.testing.expectEqualStrings("first", pane.msg_older[0].slice()); + try std.testing.expectEqualStrings("second", pane.msg[0..pane.msg_len]); + try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); + p.collectNotices(pane, p.rects[p.active], p.active); + try std.testing.expectEqual(Pane.Notices.Kind.older, pane.notices.kinds[0]); + try std.testing.expectEqual(Pane.Notices.Kind.message, pane.notices.kinds[1]); + // One key dismisses both, but each runs its own clock: the first starts + // lingering now, the second only once it has landed. + p.update(.{ .key = .{ .cp = 'h' } }); + try std.testing.expectEqual(Pane.MessagePhase.lingering, pane.msg_older[0].life.phase); + try std.testing.expectEqual(Pane.MessagePhase.entering, pane.msg_life.phase); + const linger = Pardes.messageFrames(p.settings.message_linger_ms); + const dissolve = Pardes.messageFrames(p.settings.message_dissolve_ms); + for (0..linger + dissolve) |_| p.update(.tick); + // The first is gone; the second, a fall later, is still dissolving. + try std.testing.expectEqual(@as(u8, 0), pane.msg_older_len); + try std.testing.expectEqualStrings("second", pane.msg[0..pane.msg_len]); + try std.testing.expectEqual(Pane.MessagePhase.leaving, pane.msg_life.phase); + for (0..fall) |_| p.update(.tick); + try std.testing.expectEqual(@as(u16, 0), pane.msg_len); + try std.testing.expect(!p.animationActive()); + // A status ticking in place does not pile up. + p.setStatus(p.active, "lsp 10%"); + p.setStatus(p.active, "lsp 20%"); + try std.testing.expectEqual(@as(u8, 0), pane.msg_older_len); + // Lines keep their rows: when the top one leaves, the one under it does + // not move up, and the next message fills the gap instead. + p.setMessage(p.active, "top"); + p.setMessage(p.active, "under"); + try std.testing.expectEqual(@as(u8, 0), pane.msg_older[0].slot); + try std.testing.expectEqual(@as(u8, 1), pane.msg_slot); + pane.removeOlderMessage(0); + p.collectNotices(pane, p.rects[p.active], p.active); + try std.testing.expectEqual(@as(u8, 1), pane.notices.row[0]); + try std.testing.expectEqual(@as(u8, 2), pane.notices.span()); + p.setMessage(p.active, "fills"); + try std.testing.expectEqual(@as(u8, 0), pane.msg_slot); + try std.testing.expectEqual(@as(u8, 1), pane.msg_older[0].slot); + // The stack keeps the newest few. + for ([_][]const u8{ "a", "b", "c", "d", "e" }) |text| p.setMessage(p.active, text); + try std.testing.expectEqual(@as(u8, Pane.message_stack), pane.msg_older_len); + try std.testing.expectEqualStrings("b", pane.msg_older[0].slice()); + try std.testing.expectEqualStrings("e", pane.msg[0..pane.msg_len]); +} + test "Font keeps requested and acknowledged faces as separate plain state" { if (comptime !font_picker) return; // there is no Font builtin on tty or web const p = try Pardes.init(std.testing.allocator, .{ .cols = 80, .rows = 24 }); @@ -3774,6 +3927,8 @@ pub const NativePlacement = if (pdf_enabled) struct { paper_bg: ?[3]u8 = null, } else struct {}; +pub const ImagePatch = struct { from: u32, y: u32, h: u32 }; + pub const ImagePlace = struct { pane: u8, /// Pane slots are reused. This identity makes a cached GPU texture or @@ -3787,6 +3942,10 @@ pub const ImagePlace = struct { rgba: []const u8, iw: usize, ih: usize, + /// Rows [y, y+h) of `rgba` are the only ones that differ from the + /// same pane page at revision `from`: a shell still holding that one may + /// update just these rows instead of taking the whole image again. + patch: ?ImagePatch = null, pub fn cacheKey(place: ImagePlace) ImageCacheKey { if (comptime pdf_enabled) @@ -6194,6 +6353,10 @@ pub const Pardes = struct { chrome_animation: ChromeAnimation = ChromeAnimation.init(initial_chrome), animate_theme_changes: bool = false, native_images: bool = false, + /// The shell can take a changed image a few rows at a time (a texture row + /// upload, a shared-memory hand-off), so a PDF selection is repainted as + /// it is dragged instead of once on release. + native_image_patches: bool = false, quit: bool = false, haptic: HapticSlot = if (platform == .macos) .none else {}, drag: Drag = .none, @@ -6250,6 +6413,9 @@ pub const Pardes = struct { /// Is there a frame worth drawing? Cleared once one is presented, set by /// anything that can change what is on screen. The first frame always is. needs_frame: bool = true, + /// Set by a shell whose present was skipped (no swapchain image): the + /// frame is still owed, and the next pump draws it again. + present_skipped: bool = false, /// Builtins announce themselves on the message row. Off while startup /// configuration is applied: those lines are nobody clicking, and should /// not leave the row holding the name of the last one. @@ -7040,16 +7206,18 @@ pub const Pardes = struct { } }; + /// A status updates the message line in place (a progress count does not + /// pile up); a message is an event, and stacks. pub fn setStatus(p: *Pardes, id: usize, text: []const u8) void { - p.showMessage(id, text); + p.showMessage(id, text, false); } pub fn setMessage(p: *Pardes, id: usize, text: []const u8) void { p.logMessage(id, text); - p.showMessage(id, text); + p.showMessage(id, text, true); } - fn showMessage(p: *Pardes, id: usize, text: []const u8) void { + fn showMessage(p: *Pardes, id: usize, text: []const u8, stack: bool) void { if (id >= MAX_PANES) return; const pane = p.panes[id] orelse return; // One row of printable text: a language server's multi-line report @@ -7058,8 +7226,158 @@ pub const Pardes = struct { if (n < text.len) { while (n > 0 and text[n] & 0xC0 == 0x80) n -= 1; } + const same = pane.msg_len == n and for (text[0..n], pane.msg[0..n]) |c, have| { + if ((if (c < 0x20 or c == 0x7f) ' ' else c) != have) break false; + } else true; + // A new event moves the line on screen up the stack, where it keeps + // its own timing, and falls in below it. + // Only an event stacks on an event: an announcement or a status + // stands in for whatever comes next. + if (stack and pane.msg_len > 0 and !same and !pane.msg_announcement and !pane.msg_status) + pane.pushOlderMessage(); + if (pane.msg_len == 0) pane.msg_slot = pane.freeMessageSlot(); + pane.msg_announcement = 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; pane.msg_len = @intCast(n); + p.needs_frame = true; + if (arrives) { + pane.msg_life = .{ .phase = if (p.settings.message_animation and n > 0) .entering else .shown }; + } else if (pane.msg_life.phase == .lingering or + (pane.msg_life.phase == .entering and !p.settings.message_animation)) + { + // The same line again, or a status update: fresh, so it stays. + pane.msg_life = .{}; + } else { + pane.msg_life.dismissed = false; + } + } + + /// The key or click that used to clear the message row now starts each + /// line's exit: it stays `message_linger_ms`, then dissolves. A line + /// already on its way out keeps its own timing. + fn dismissMessage(p: *Pardes, pane: *Pane) void { + if (pane.msg_len > 0 and p.dismissLine(&pane.msg_life)) { + pane.msg_len = 0; + pane.msg_life = .{}; + } + var i: usize = 0; + while (i < pane.msg_older_len) { + if (p.dismissLine(&pane.msg_older[i].life)) pane.removeOlderMessage(i) else i += 1; + } + } + + /// Start one line's exit; true when it is gone at once (no linger, no + /// animation). + fn dismissLine(p: *const Pardes, life: *Pane.MessageLife) bool { + switch (life.phase) { + .lingering, .leaving => return false, + // A falling line lands first, then lingers -- unless falling was + // just turned off, and nothing will land it. + .entering => if (p.settings.message_animation) { + life.dismissed = true; + return false; + }, + .shown => {}, + } + life.frame = 0; + if (p.settings.message_linger_ms > 0) { + life.phase = .lingering; + } else if (p.settings.message_animation) { + life.phase = .leaving; + } else return true; + return false; + } + + /// One animation frame of every message line. Each one that moves owes + /// a frame, the one that finishes included: a tick asks for none itself. + fn advanceMessages(p: *Pardes) void { + for (p.panes) |slot| { + const pane = slot orelse continue; + if (pane.msg_len > 0 and pane.msg_life.phase != .shown) { + p.needs_frame = true; + if (p.advanceLine(&pane.msg_life)) { + pane.msg_len = 0; + pane.msg_life = .{}; + } + } + var i: usize = 0; + while (i < pane.msg_older_len) { + if (pane.msg_older[i].life.phase != .shown) p.needs_frame = true; + if (p.advanceLine(&pane.msg_older[i].life)) pane.removeOlderMessage(i) else i += 1; + } + } + } + + /// One frame of one line's life; true once it has left. + fn advanceLine(p: *const Pardes, life: *Pane.MessageLife) bool { + if (life.phase == .shown) return false; + life.frame +|= 1; + switch (life.phase) { + .shown => {}, + .entering => if (life.frame >= messageFrames(p.settings.message_fall_ms)) { + life.* = .{ .phase = if (life.dismissed) .lingering else .shown }; + }, + .lingering => if (life.frame >= messageFrames(p.settings.message_linger_ms)) { + if (!p.settings.message_animation) return true; + life.* = .{ .phase = .leaving }; + }, + .leaving => if (life.frame >= messageFrames(p.settings.message_dissolve_ms)) return true, + } + return false; + } + + /// Is any message line moving (and so owed ticks)? + fn messagesAnimating(pane: *const Pane) bool { + if (pane.msg_len > 0 and pane.msg_life.phase != .shown) return true; + for (pane.msg_older[0..pane.msg_older_len]) |line| if (line.life.phase != .shown) return true; + return false; + } + + /// How present a message is (1 = fully) and how far above its row it + /// still is (rows), eased: an ease-in fall, an ease-out dissolve. + const MessageMotion = struct { alpha: f32 = 1, slide: f32 = 0 }; + + /// Animation frames a message timing lasts; at least one. + pub fn messageFrames(ms: u16) u16 { + return @intCast(@max(1, (@as(u32, ms) + layout.Animation.frame_ms - 1) / layout.Animation.frame_ms)); + } + + fn messageMotion(p: *const Pardes, life: Pane.MessageLife) MessageMotion { + const fall_frames = messageFrames(p.settings.message_fall_ms); + const dissolve_frames = messageFrames(p.settings.message_dissolve_ms); + return switch (life.phase) { + .shown, .lingering => .{ .alpha = 1, .slide = 0 }, + .entering => blk: { + const t = @as(f32, @floatFromInt(@min(life.frame, fall_frames))) / @as(f32, @floatFromInt(fall_frames)); + const eased = t * t; + break :blk .{ .alpha = eased, .slide = eased - 1 }; + }, + .leaving => blk: { + const t = @as(f32, @floatFromInt(@min(life.frame, dissolve_frames))) / @as(f32, @floatFromInt(dissolve_frames)); + break :blk .{ .alpha = (1 - t) * (1 - t), .slide = 0 }; + }, + }; + } + + /// The life of the message line notice `i` shows, if it shows one. + fn noticeLife(pane: *const Pane, i: usize) ?Pane.MessageLife { + return switch (pane.notices.kinds[i]) { + .message => pane.msg_life, + .older => pane.msg_older[pane.notices.index[i]].life, + .leader, .prompt => null, + }; + } + + 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 { @@ -7358,8 +7676,11 @@ pub const Pardes = struct { _ = p.frame_arena.reset(.retain_capacity); 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 + // tick moves owes the next frame. + p.needs_frame = p.present_skipped; + p.present_skipped = false; if (v.post_present) |f| f(h.ctx); - p.needs_frame = false; } /// One request of the control filesystem, from whichever thread has the @@ -7389,6 +7710,10 @@ pub const Pardes = struct { // the screen. p.needs_frame = p.needs_frame or ev != .tick; p.shell_rows.sweep(p.gpa); + // An announcement stands in only until its own step says more. + for (p.panes) |slot| if (slot) |pane| { + pane.msg_announcement = false; + }; switch (ev) { .tick => {}, .mouse => |m| if (!(m.button == .none and m.kind == .motion)) { @@ -7415,10 +7740,11 @@ pub const Pardes = struct { switch (ev) { .key, .mouse => { for (p.panes) |slot| { - if (slot) |pane| pane.msg_len = 0; + if (slot) |pane| p.dismissMessage(pane); } p.clip_pending = null; }, + .tick => p.advanceMessages(), else => {}, } if (p.fs.listeners != 0) p.fs.origin = switch (ev) { @@ -11462,7 +11788,7 @@ pub const Pardes = struct { // 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.len and + 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) if (body_hit) |supplied| { const mapped_hit = p.bodyHitForPane(id, supplied, false) orelse return null; @@ -12252,6 +12578,21 @@ pub const Pardes = struct { } } else { const clk = pane.sel[b]; + // 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 + clk.c0 == clk.c1 and clk.c0 >= 0 and pane.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) { + pane.sel[b].state = .none; + var buf: [48]u8 = undefined; + const target = std.fmt.bufPrint(&buf, "@p{d}:{d}", .{ s.id, @as(usize, @intCast(line)) + 1 }) catch return; + p.runBuiltin(config.look_cmd, s.id, "", target); + return; + } + }; var operand = p.pointerOperand(pane, clk); if (operand.expanded) |expanded| pane.sel[b] = expanded @@ -12876,8 +13217,10 @@ pub const Pardes = struct { // A builtin says its own name before it runs, so a tagline click is // legible even when what it did is invisible. Whatever the builtin // then says for itself replaces the announcement. - if (p.announce and p.settings.verbose and builtins.registry.announces(b)) + if (p.announce and p.settings.verbose and builtins.registry.announces(b)) { p.setMessage(id, @tagName(b)); + pane.msg_announcement = true; + } const c: builtins.Ctx = .{ .p = p, .pane = pane, .id = id, .txt = txt, .arg = arg }; builtins.registry.dispatch(b, c); } @@ -13121,10 +13464,16 @@ pub const Pardes = struct { const pane: *Pane = switch (src.kind) { .terminal => terminal: { const t = src.terminal.?; - const restored = try panes.Terminal.restore(p, src); + // A host that runs shells gets them back: the old history + // above a new shell in the directory it was in. The web + // shell and an isolated build only ever replay it. + const live = comptime (terminal_panes and platform != .web and !isolated); + const revive = live and t.cwd.len <= effect_path_cap; + const restored = try 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 (revive) p.emit(.{ .spawn = .{ .pane = @intCast(i), .cwd = .from(t.cwd) } }); break :terminal restored; }, .file => try panes.File.restore(p, i, src), @@ -13487,6 +13836,9 @@ pub const Pardes = struct { /// core work belongs in this one predicate so TTY and GUI mature it alike. pub fn animationActive(p: *const Pardes) bool { if (p.chrome_animation.isActive() or p.look_hover_wait != null) return true; + for (p.panes) |slot| if (slot) |pane| { + if (messagesAnimating(pane)) return true; + }; const scene = p.settings.scene_effects; if (scene.crt or scene.ripple or scene.glitch) return true; return p.presentation.animating(); @@ -13653,7 +14005,7 @@ pub const Pardes = struct { const first = p.bodyTop(r); var leader_buf: [16]u8 = undefined; for (pane.notices.slice(), 0..) |kind, i| { - const row = first + @as(u16, @intCast(i)); + const row = first + @as(u16, pane.notices.row[i]); // Every notice is painted on the canonical grid as well as // emitted as a tag layer: the grid is what a terminal client // draws, and a band it cannot see is a message it never gets. @@ -13661,6 +14013,7 @@ pub const Pardes = struct { // drawn twice there. const text = switch (kind) { .message => pane.msg[0..pane.msg_len], + .older => pane.msg_older[pane.notices.index[i]].slice(), .leader => p.leaderText(&leader_buf), .prompt => blk: { const at = pane.promptAt() orelse continue; @@ -13671,13 +14024,24 @@ pub const Pardes = struct { if (chip == 0) continue; const cx = tx + tw - chip; pane.notices.left[i] = cx; - s.fill(cx, row, chip, 1, .{ .bg = msg_style.bg, .font_role = .tagline }); + // 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; + if (noticeLife(pane, i)) |life| { + // No page colour to fade to (a terminal's own default): + // the text dissolves into its chip instead. + const alpha = p.messageMotion(life).alpha; + const page = th.bg orelse chrome.tag_bg; + style.fg = .{ .rgb = blendRgb(chrome.tag_fg, page, alpha) }; + style.bg = .{ .rgb = blendRgb(chrome.tag_bg, page, alpha) }; + } + s.fill(cx, row, chip, 1, .{ .bg = style.bg, .font_role = .tagline }); // One column short of the chip's right edge: a prompt's caret // sits AFTER its last character the moment it opens, and flush // right would put it past the pane, off the grid, and past what // the detached wire will encode -- which drops every frame for // as long as the prompt is up. - const printed = printRight(s, cx, row, chip -| 1, text, msg_style); + const printed = 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; @@ -14166,6 +14530,7 @@ pub const Pardes = struct { for (pane.notices.slice(), 0..) |kind, i| { const text = switch (kind) { .message => pane.msg[0..pane.msg_len], + .older => pane.msg_older[pane.notices.index[i]].slice(), .leader => p.leaderText(&leader_buf), // A prompt is an editing line with a cursor in it, so it // stays on the grid where the cursor can sit on a cell. @@ -14190,12 +14555,19 @@ pub const Pardes = struct { const line = try arena.alloc(u8, pad + kept.len); @memset(line[0..pad], ' '); @memcpy(line[pad..], kept); - try p.renderHeaderLayer(arena, NOTICE_LAYER_BASE + id * Pane.Notices.max + i, .notice, @intCast(id), .{ + // A pixel shell slides the message in whole and only fades + // it on the way out. + const motion: MessageMotion = if (noticeLife(pane, i)) |life| p.messageMotion(life) else .{}; + const fade = if (motion.slide == 0) motion.alpha else 1; + const page = p.theme().bg orelse chrome.tag_bg; + const layer_index = NOTICE_LAYER_BASE + id * Pane.Notices.max + i; + try p.renderHeaderLayer(arena, layer_index, .notice, @intCast(id), .{ .x = cx, - .y = first + @as(u16, @intCast(i)), + .y = first + @as(u16, pane.notices.row[i]), .w = chip, .h = BOX_H, - }, line, chrome.tag_bg, chrome.tag_fg); + }, line, blendRgb(chrome.tag_bg, page, fade), blendRgb(chrome.tag_fg, page, fade)); + p.surface.tag_layers[layer_index].slide = motion.slide; } } if (p.columnBarHeight() > 0) for (0..p.ncol) |column| { @@ -14221,6 +14593,7 @@ pub const Pardes = struct { layer.cols = columns; layer.bg = bg; layer.cursor = null; + layer.slide = 0; var surface: Surface = .{ .cols = columns, .rows = 1, .cells = layer.cells }; // 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 @@ -14270,7 +14643,10 @@ pub const Pardes = struct { 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 (pane.msg_len > 0) pane.notices.push(.message); + // 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); + if (pane.msg_len > 0) pane.notices.pushAt(.message, 0, pane.msg_slot); if (id == p.active and p.leader_on) pane.notices.push(.leader); if (pane.promptAt()) |at| { if (pane.tagSlice()[@min(at, pane.tag_tail_len)..].len > 0) pane.notices.push(.prompt); @@ -14281,11 +14657,26 @@ pub const Pardes = struct { // 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)); - if (pane.notices.len > room) { - const drop = pane.notices.len - room; - for (0..room) |i| pane.notices.kinds[i] = pane.notices.kinds[i + drop]; - pane.notices.len = room; + const n = &pane.notices; + if (n.span() <= room) return; + // Too short for the gaps: close them up in screen order, and if even + // that does not fit, the top bands go. + var i: usize = 1; + while (i < n.len) : (i += 1) { + var j = i; + while (j > 0 and n.row[j - 1] > n.row[j]) : (j -= 1) { + std.mem.swap(Pane.Notices.Kind, &n.kinds[j - 1], &n.kinds[j]); + std.mem.swap(u8, &n.index[j - 1], &n.index[j]); + std.mem.swap(u8, &n.row[j - 1], &n.row[j]); + } + } + const drop = n.len -| room; + for (0..n.len - drop) |k| { + n.kinds[k] = n.kinds[k + drop]; + n.index[k] = n.index[k + drop]; + n.row[k] = @intCast(k); } + n.len -= @intCast(drop); } fn renderBodyLayer(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize) !void { @@ -14390,7 +14781,7 @@ pub const Pardes = struct { // Below the notice chips: a picture is drawn after the cells (the // 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.len; + const shown = pane.notices.span(); const image_h = (r.h -| BOX_H) -| 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 — diff --git a/src/pdf.zig b/src/pdf.zig index 712750dc..de5e6d86 100644 --- a/src/pdf.zig +++ b/src/pdf.zig @@ -1017,6 +1017,73 @@ pub const Document = struct { ) != c.PARDES_PDF_OK) return error.RenderFailed; } + /// Only the highlight pass of `renderIntoAtWithPaper`, over `rgba`, which + /// holds `band` of this page as that render left it before highlighting + /// (opaque paper). Rendering with highlights equals rendering without and + /// then this, row for row: the render draws highlights over the finished + /// page, and so does this. + pub fn paintHighlightsAt( + document: *Document, + page: usize, + request: RenderRequest, + raster: Raster, + band: Raster.Band, + highlights: []const Highlight, + rgba: []u8, + ) !void { + if (rgba.len != band.len) return error.BadPixmap; + if (band.height == 0 or band.y + band.height > raster.height) + return error.BadPixmap; + const bounded = try boundedRequest(document, page, request); + if (highlights.len > c.PARDES_PDF_MAX_RESULT_QUADS) return error.RenderFailed; + if (c.pardes_pdf_paint_highlights( + document.handle, + @intCast(page), + bounded.dpi, + bounded.minimum_width, + bounded.minimum_height, + bounded.max_dimension, + if (highlights.len == 0) null else @ptrCast(highlights.ptr), + highlights.len, + rgba.ptr, + rgba.len, + @intCast(raster.width), + @intCast(raster.height), + @intCast(raster.stride), + @intCast(band.y), + @intCast(band.height), + ) != c.PARDES_PDF_OK) return error.RenderFailed; + } + + pub const Rows = struct { start: usize, end: usize }; + + /// The rows of `request`'s raster that painting `highlights` can touch, + /// by the transform the render itself uses (rotation included). Empty + /// when nothing would paint. + pub fn highlightRows( + document: *Document, + page: usize, + request: RenderRequest, + highlights: []const Highlight, + ) !Rows { + const bounded = try boundedRequest(document, page, request); + var row_start: c_int = 0; + var row_end: c_int = 0; + if (c.pardes_pdf_highlight_rows( + document.handle, + @intCast(page), + bounded.dpi, + bounded.minimum_width, + bounded.minimum_height, + bounded.max_dimension, + if (highlights.len == 0) null else @ptrCast(highlights.ptr), + highlights.len, + &row_start, + &row_end, + ) != c.PARDES_PDF_OK) return error.RenderFailed; + return .{ .start = @intCast(row_start), .end = @intCast(row_end) }; + } + const BoundedRequest = struct { dpi: c_int, minimum_width: c_int, diff --git a/src/pdf_bridge.c b/src/pdf_bridge.c index 976ed838..2c723dbb 100644 --- a/src/pdf_bridge.c +++ b/src/pdf_bridge.c @@ -572,6 +572,55 @@ pardes_pdf_measure_render( return PARDES_PDF_OK; } +/* The highlight pass of a render: fills over whatever the pixmap holds. */ +static void +pardes_pdf_fill_highlights(fz_context *ctx, pardes_pdf_document *document, + fz_device *device, const pardes_pdf_highlight *highlights, size_t highlight_count) +{ + fz_path *path = NULL; + size_t i; + + fz_var(path); + fz_try(ctx) + { + for (i = 0; i < highlight_count; ++i) { + fz_quad quad; + float color[3]; + float alpha; + + if (!pardes_pdf_valid_quad(highlights[i].quad)) + fz_throw(ctx, FZ_ERROR_ARGUMENT, + "PDF highlight contains a non-finite point"); + if (highlights[i].rgba[3] == 0) + continue; + + /* Kind is semantic metadata; caller-supplied RGBA is final. */ + (void)highlights[i].kind; + quad = pardes_pdf_quad_to_page(document, highlights[i].quad); + color[0] = highlights[i].rgba[0] / 255.0f; + color[1] = highlights[i].rgba[1] / 255.0f; + color[2] = highlights[i].rgba[2] / 255.0f; + alpha = highlights[i].rgba[3] / 255.0f; + + path = fz_new_path(ctx); + fz_moveto(ctx, path, quad.ul.x, quad.ul.y); + fz_lineto(ctx, path, quad.ur.x, quad.ur.y); + fz_lineto(ctx, path, quad.lr.x, quad.lr.y); + fz_lineto(ctx, path, quad.ll.x, quad.ll.y); + fz_closepath(ctx, path); + fz_fill_path(ctx, device, path, 0, fz_identity, + fz_device_rgb(ctx), color, alpha, + fz_default_color_params); + fz_drop_path(ctx, path); + path = NULL; + } + } + fz_always(ctx) + fz_drop_path(ctx, path); + fz_catch(ctx) + fz_rethrow(ctx); +} + int pardes_pdf_render_into( pardes_pdf_document *document, @@ -594,10 +643,8 @@ pardes_pdf_render_into( fz_context *ctx; fz_pixmap *pixmap = NULL; fz_device *device = NULL; - fz_path *path = NULL; fz_matrix ctm; fz_irect bbox; - size_t i; if (document == NULL || page_number < 0 || page_number >= document->page_count || dpi < 1 || @@ -614,7 +661,6 @@ pardes_pdf_render_into( ctx = document->ctx; fz_var(pixmap); fz_var(device); - fz_var(path); fz_try(ctx) { pardes_pdf_render_geometry(document, page_number, dpi, @@ -627,10 +673,12 @@ pardes_pdf_render_into( * The BAND: rows [band_y, band_y + band_height) of the page raster, * and nothing else. A pixmap's bbox IS the draw device's clip, so the * page runs under the same CTM it would for a full raster and MuPDF - * discards everything outside these rows. Every row inside them is - * therefore bit-identical to the same row of the full-page raster — - * "band rows equal full-page rows" in pdf.zig proves it, because the - * whole point of a band is that the reader cannot tell. + * discards everything outside these rows. The rows are NOT always + * bit-identical to the full page's: rows at the band's edges, and a + * resampled image anywhere in it, can differ (measured on + * docs/registry.pdf and docs/design.pdf). Good enough for a band that + * is only shown while flinging; never use a band to patch rows into a + * whole-page raster -- `pardes_pdf_paint_highlights` exists for that. */ bbox.y0 += band_y; bbox.y1 = bbox.y0 + band_height; @@ -674,43 +722,12 @@ pardes_pdf_render_into( if (highlight_count != 0) { device = fz_new_draw_device(ctx, ctm, pixmap); - for (i = 0; i < highlight_count; ++i) { - fz_quad quad; - float color[3]; - float alpha; - - if (!pardes_pdf_valid_quad(highlights[i].quad)) - fz_throw(ctx, FZ_ERROR_ARGUMENT, - "PDF highlight contains a non-finite point"); - if (highlights[i].rgba[3] == 0) - continue; - - /* Kind is semantic metadata; caller-supplied RGBA is final. */ - (void)highlights[i].kind; - quad = pardes_pdf_quad_to_page(document, highlights[i].quad); - color[0] = highlights[i].rgba[0] / 255.0f; - color[1] = highlights[i].rgba[1] / 255.0f; - color[2] = highlights[i].rgba[2] / 255.0f; - alpha = highlights[i].rgba[3] / 255.0f; - - path = fz_new_path(ctx); - fz_moveto(ctx, path, quad.ul.x, quad.ul.y); - fz_lineto(ctx, path, quad.ur.x, quad.ur.y); - fz_lineto(ctx, path, quad.lr.x, quad.lr.y); - fz_lineto(ctx, path, quad.ll.x, quad.ll.y); - fz_closepath(ctx, path); - fz_fill_path(ctx, device, path, 0, fz_identity, - fz_device_rgb(ctx), color, alpha, - fz_default_color_params); - fz_drop_path(ctx, path); - path = NULL; - } + pardes_pdf_fill_highlights(ctx, document, device, highlights, highlight_count); fz_close_device(ctx, device); } } fz_always(ctx) { - fz_drop_path(ctx, path); fz_drop_device(ctx, device); /* Drops only the wrapper: caller-owned samples remain untouched. */ fz_drop_pixmap(ctx, pixmap); @@ -742,6 +759,139 @@ pardes_pdf_render_into( return PARDES_PDF_OK; } +int +pardes_pdf_paint_highlights( + pardes_pdf_document *document, + int page_number, + int dpi, + int minimum_width, + int minimum_height, + int max_dimension, + const pardes_pdf_highlight *highlights, + size_t highlight_count, + unsigned char *samples, + size_t samples_len, + int width, + int height, + int stride, + int band_y, + int band_height) +{ + fz_context *ctx; + fz_pixmap *pixmap = NULL; + fz_device *device = NULL; + fz_matrix ctm; + fz_irect bbox; + + if (document == NULL || page_number < 0 || + page_number >= document->page_count || dpi < 1 || + minimum_width < 0 || minimum_height < 0 || max_dimension < 1 || + (highlight_count != 0 && highlights == NULL) || + highlight_count > PARDES_PDF_MAX_RESULT_QUADS || samples == NULL || + width < 1 || height < 1 || width > INT_MAX / 4 || stride != width * 4 || + band_y < 0 || band_height < 1 || band_y > height - band_height || + (size_t)band_height > SIZE_MAX / (size_t)stride || + samples_len != (size_t)stride * (size_t)band_height) + return PARDES_PDF_ERROR; + if (highlight_count == 0) + return PARDES_PDF_OK; + + ctx = document->ctx; + fz_var(pixmap); + fz_var(device); + fz_try(ctx) + { + pardes_pdf_render_geometry(document, page_number, dpi, + minimum_width, minimum_height, max_dimension, &ctm, &bbox); + if (fz_irect_width(bbox) != width || fz_irect_height(bbox) != height) + fz_throw(ctx, FZ_ERROR_ARGUMENT, + "PDF raster layout changed between measure and paint"); + bbox.y0 += band_y; + bbox.y1 = bbox.y0 + band_height; + pixmap = fz_new_pixmap_with_bbox_and_data( + ctx, fz_device_rgb(ctx), bbox, NULL, 1, samples); + device = fz_new_draw_device(ctx, ctm, pixmap); + pardes_pdf_fill_highlights(ctx, document, device, highlights, highlight_count); + fz_close_device(ctx, device); + } + fz_always(ctx) + { + fz_drop_device(ctx, device); + fz_drop_pixmap(ctx, pixmap); + } + fz_catch(ctx) + { + fz_report_error(ctx); + return PARDES_PDF_ERROR; + } + return PARDES_PDF_OK; +} + +int +pardes_pdf_highlight_rows( + pardes_pdf_document *document, + int page_number, + int dpi, + int minimum_width, + int minimum_height, + int max_dimension, + const pardes_pdf_highlight *highlights, + size_t highlight_count, + int *row_start, + int *row_end) +{ + fz_context *ctx; + fz_matrix ctm; + fz_irect bbox; + float y0 = 0, y1 = 0; + int any = 0; + size_t i; + + if (row_start == NULL || row_end == NULL) + return PARDES_PDF_ERROR; + *row_start = *row_end = 0; + if (document == NULL || page_number < 0 || + page_number >= document->page_count || dpi < 1 || + minimum_width < 0 || minimum_height < 0 || max_dimension < 1 || + (highlight_count != 0 && highlights == NULL)) + return PARDES_PDF_ERROR; + + ctx = document->ctx; + fz_try(ctx) + { + pardes_pdf_render_geometry(document, page_number, dpi, + minimum_width, minimum_height, max_dimension, &ctm, &bbox); + for (i = 0; i < highlight_count; ++i) { + fz_rect r; + if (highlights[i].rgba[3] == 0 || + !pardes_pdf_valid_quad(highlights[i].quad)) + continue; + r = fz_rect_from_quad(fz_transform_quad( + pardes_pdf_quad_to_page(document, highlights[i].quad), ctm)); + if (!any || r.y0 < y0) y0 = r.y0; + if (!any || r.y1 > y1) y1 = r.y1; + any = 1; + } + } + fz_catch(ctx) + { + fz_report_error(ctx); + return PARDES_PDF_ERROR; + } + if (any) { + /* + * Antialiasing covers the pixel a fractional edge falls in, and the + * rasterizer paints row floor(y1) even for a zero-height quad. + */ + int lo = (int)floorf(y0) - bbox.y0; + int hi = (int)floorf(y1) + 1 - bbox.y0; + int h = fz_irect_height(bbox); + *row_start = lo < 0 ? 0 : (lo > h ? h : lo); + *row_end = hi < *row_start ? *row_start : (hi > h ? h : hi); + } + return PARDES_PDF_OK; +} + int pardes_pdf_page_text( pardes_pdf_document *document, diff --git a/src/pdf_bridge.h b/src/pdf_bridge.h index cda426aa..e3514437 100644 --- a/src/pdf_bridge.h +++ b/src/pdf_bridge.h @@ -222,8 +222,9 @@ int pardes_pdf_measure_render( * MuPDF wraps but never owns or frees samples. Every successful pixel is * opaque unless transparent_paper is nonzero. That mode preserves content * coverage and returns straight-alpha RGBA over an unpainted page. - * The CTM does not depend on the band, so a band's rows are bit-identical to - * the same rows of the whole page: it is a clip, not a different rendering. + * The CTM does not depend on the band, so a band is a clip of the same + * rendering -- but not a bit-exact one: its edge rows and resampled images can + * differ from the whole page's (see pardes_pdf_render_into). */ int pardes_pdf_render_into( pardes_pdf_document *document, @@ -244,6 +245,47 @@ int pardes_pdf_render_into( int transparent_paper ); +/* + * The highlight pass of `pardes_pdf_render_into` alone, over caller-supplied + * rows of that page's opaque raster: render_into(h) == paint(render_into({}), h) + * row for row, because a render draws its highlights over the finished page. + */ +int pardes_pdf_paint_highlights( + pardes_pdf_document *document, + int page, + int dpi, + int minimum_width, + int minimum_height, + int max_dimension, + const pardes_pdf_highlight *highlights, + size_t highlight_count, + unsigned char *samples, + size_t samples_len, + int width, + int height, + int stride, + int band_y, + int band_height +); + +/* + * The raster rows [*row_start, *row_end) that painting `highlights` can touch + * under the same request, in the coordinates `pardes_pdf_render_into` bands + * use. An empty set (or only transparent ones) yields start == end == 0. + */ +int pardes_pdf_highlight_rows( + pardes_pdf_document *document, + int page, + int dpi, + int minimum_width, + int minimum_height, + int max_dimension, + const pardes_pdf_highlight *highlights, + size_t highlight_count, + int *row_start, + int *row_end +); + int pardes_pdf_page_text( pardes_pdf_document *document, int page, diff --git a/src/tag_layer.zig b/src/tag_layer.zig index 0fb2297d..f8cc6eca 100644 --- a/src/tag_layer.zig +++ b/src/tag_layer.zig @@ -26,6 +26,10 @@ pub const Layer = struct { bg: [3]u8 = .{ 0, 0, 0 }, cells: []pardes.Cell = &.{}, cursor: ?struct { col: u16, bar: bool = false } = null, + /// Vertical offset in rows (negative: above its viewport), for a band + /// that is moving into place. A pixel shell draws it offset and clipped + /// to the rows below the viewport's top; the grid has no such thing. + slide: f32 = 0, pub fn capacity(layer: *const Layer, metrics: pardes.RowMetrics) u16 { return @intCast(@min(std.math.maxInt(u16), @max(1, @as(u32, layer.viewport.w) * @max(1, metrics.body_w) / @max(1, metrics.tagline_w)))); diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 03ccd3e2..5976852f 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -21,6 +21,56 @@ extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int const TIOCSWINSZ: c_int = @bitCast(@as(u32, if (@hasDecl(posix.T, "IOCSWINSZ")) posix.T.IOCSWINSZ else 0x80087467)); +/// The terminal answered the shared-memory probe (`kittyShmProbe`): it can +/// read a raster from a POSIX shm object, so a page costs a name on the wire +/// instead of its whole base64 body. Set by the input reader, which sees the +/// reply before vaxis' parser swallows every graphics APC alike. +var kitty_shm = std.atomic.Value(bool).init(false); +/// Only a reply that arrives while the probe is out counts. The id is one +/// vaxis' own image numbering (1, 2, ...) never reaches, because a terminal +/// answers every transmission `i=;OK` and one of those must not pass. +var kitty_shm_probing = std.atomic.Value(bool).init(false); +const kitty_shm_probe_id = 0x7fff_fff1; +var kitty_shm_serial: u32 = 0; + +fn kittyShmName(buf: []u8, n: u32) ![:0]const u8 { + return std.fmt.bufPrintSentinel(buf, "/pardes-{d}-{d}", .{ libc.getpid(), n }, 0); +} + +/// Write `bytes` to a fresh shm object; the terminal unlinks it after reading. +fn kittyShmWrite(name: [:0]const u8, bytes: []const u8) bool { + const fd = libc.shm_open(name, @bitCast(libc.O{ .ACCMODE = .RDWR, .CREAT = true, .EXCL = true }), @as(c_uint, 0o600)); + if (fd < 0) return false; + defer _ = libc.close(fd); + if (libc.ftruncate(fd, @intCast(bytes.len)) != 0) { + _ = libc.shm_unlink(name); + return false; + } + var off: usize = 0; + while (off < bytes.len) { + const n = libc.write(fd, bytes[off..].ptr, bytes.len - off); + if (n <= 0) { + _ = libc.shm_unlink(name); + return false; + } + off += @intCast(n); + } + return true; +} + +/// Ask with a 1x1 RGB image in shm whether the terminal reads that medium. A +/// remote terminal cannot see our shm and answers an error (or nothing). +fn kittyShmProbe(w: *std.Io.Writer) void { + var buf: [64]u8 = undefined; + const name = kittyShmName(&buf, 0) catch return; + if (!kittyShmWrite(name, &.{ 0, 0, 0 })) return; + var b64: [64]u8 = undefined; + const enc = std.base64.standard.Encoder.encode(&b64, name); + kitty_shm_probing.store(true, .release); + w.print("\x1b_Gi={d},s=1,v=1,a=q,t=s,f=24;{s}\x1b\\", .{ kitty_shm_probe_id, enc }) catch return; + w.flush() catch {}; +} + pub const Command = struct { pub var value: union(enum) { nop, @@ -81,6 +131,13 @@ fn readInput(loop: *Loop, tty: anytype, cache: *vaxis.GraphemeCache) !void { const received = try tty.read(buf[carried..]); if (received == 0) return; const end = carried + received; + if (kitty_shm_probing.load(.acquire)) if (std.mem.indexOf(u8, buf[0..end], std.fmt.comptimePrint("\x1b_Gi={d};", .{kitty_shm_probe_id}))) |at| { + kitty_shm_probing.store(false, .release); + kitty_shm.store(std.mem.startsWith(u8, buf[at..end], std.fmt.comptimePrint("\x1b_Gi={d};OK", .{kitty_shm_probe_id})), .release); + // Answered either way: a terminal that could not read it left it. + var name_buf: [64]u8 = undefined; + if (kittyShmName(&name_buf, 0)) |name| _ = libc.shm_unlink(name) else |_| {} + }; var parse_end = end; var lead = end; while (lead > 0 and buf[lead - 1] & 0xc0 == 0x80) lead -= 1; @@ -717,6 +774,7 @@ fn localSession( try startInput(loop, input_cache); defer if (attached.* == null) stopInput(loop); (try std.Thread.spawn(.{}, winchWatch, .{ loop, vx, tty })).detach(); + (try std.Thread.spawn(.{}, tickWatch, .{ io, loop })).detach(); if (fs) |f| try f.watch(loop, wakeFs); try vx.queryTerminalSend(tty.writer()); @@ -726,11 +784,20 @@ fn localSession( }; if (sh.inotify_fd >= 0) sh.watch_task = io.concurrent(watchFiles, .{ io, sh.inotify_fd, loop }) catch null; + // A terminal unlinks what it reads; whatever it never read (the probe + // unanswered, a transmission lost with the terminal) is ours to remove. + defer { + var name_buf: [64]u8 = undefined; + var n: u32 = 0; + while (n <= kitty_shm_serial) : (n += 1) { + if (kittyShmName(&name_buf, n)) |name| _ = libc.shm_unlink(name) else |_| {} + } + } frames: while (!core.quit) { pardes.turn.restoreSettled(); try core.pump(host); if (core.takeRestore()) |rp| blk: { - const bytes = filesystem.readRestore(gpa, rp) catch |err| { + const bytes = filesystem.readRestore(gpa, rp, core.settings.dump_dir.get()) catch |err| { core.reportError(core.active, "Restore", err); break :blk; }; @@ -872,29 +939,39 @@ 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. - if (timeout_ms == 0) { - pardes.turn.rest(); - const first = s.loop.nextEvent() catch { - pardes.turn.wake(); - s.core.quit = true; - return s.reloadWatched(); - }; - pardes.turn.wake(); - batch = 1; - if (s.apply(first)) return s.reloadWatched(); - } else { - pardes.turn.rest(); - std.Io.sleep(s.io, .fromMilliseconds(timeout_ms), .awake) catch {}; + // The wait is the 9P connections' turn with the core. Animating, the + // frame's tick arrives through the same queue (`tickWatch`). + if (timeout_ms != 0) tick_request.set(s.io); + pardes.turn.rest(); + const first = s.loop.nextEvent() catch { pardes.turn.wake(); - _ = s.apply(.tick); - batch = 1; - } - while (s.in_paste or batch < 64) { - const ev = (s.loop.tryEvent() catch null) orelse break; + s.core.quit = true; + return s.reloadWatched(); + }; + pardes.turn.wake(); + batch = 1; + // A run of queued motions is one move to its last cell: each would + // otherwise redo hover and selection work the next one undoes. + var motion: ?@TypeOf(Command.value) = null; + var ev = first; + while (true) { + if (ev == .mouse and (ev.mouse.type == .motion or ev.mouse.type == .drag)) { + if (motion) |m| if (m.mouse.button != ev.mouse.button or m.mouse.type != ev.mouse.type or + @as(u3, @bitCast(m.mouse.mods)) != @as(u3, @bitCast(ev.mouse.mods))) + { + _ = s.apply(m); + }; + motion = ev; + } else { + if (motion) |m| _ = s.apply(m); + motion = null; + if (s.apply(ev)) break; + } + if (!s.in_paste and batch >= 64) break; + ev = (s.loop.tryEvent() catch null) orelse break; batch += 1; - if (s.apply(ev)) break; } + if (motion) |m| _ = s.apply(m); s.reloadWatched(); } @@ -1001,6 +1078,7 @@ const Shell = struct { fn pollFrame(ctx: ?*anyopaque) void { const s = of(ctx); + s.core.native_image_patches = kitty_shm.load(.acquire); if (s.fs) |f| if (f.tick().pending) { _ = s.loop.tryPostEvent(.fs_ready) catch {}; }; @@ -1013,6 +1091,7 @@ const Shell = struct { s.caps_pending = false; s.vx.enableDetectedFeatures(s.tty.writer()) catch {}; s.core.native_images = s.vx.caps.kitty_graphics; + if (s.vx.caps.kitty_graphics) kittyShmProbe(s.tty.writer()); s.vx.queueRefresh(); } } @@ -1039,6 +1118,16 @@ const Shell = struct { if (!kittyImageRepresentable(place)) continue; } const key = place.cacheKey(); + 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; + 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| + s.kitty.put(key, handle) catch vx.freeImage(s.tty.writer(), handle.id) + else + _ = libc.shm_unlink(name); + } if (!s.kitty.contains(key) and vx.caps.kitty_graphics) { const enc = std.base64.standard.Encoder; if (s.gpa.alloc(u8, enc.calcSize(place.rgba.len))) |b64| { @@ -1160,7 +1249,7 @@ const Shell = struct { fn writeDump(ctx: ?*anyopaque, bytes: []const u8) void { const s = of(ctx); var pbuf: [1024:0]u8 = undefined; - const path = pardes.dump.outPath(&pbuf) orelse return; + const path = pardes.dump.outPath(&pbuf, s.core.settings.dump_dir.get()) orelse return; filesystem.write(s.core, path, bytes) catch |err| return s.core.reportError(0, "dump", err); s.core.setLastDump(path); } @@ -1415,6 +1504,21 @@ fn winchWatch(loop: *Loop, vx: *vaxis.Vaxis, tty: *vaxis.Tty) void { } } +/// Set by an animating frame's wait: post one `.tick` a frame from now. The +/// tick joins the input queue, so a key or a click that lands inside the +/// frame is handled at once instead of after a blind sleep. +var tick_request: std.Io.Event = .unset; + +fn tickWatch(io: std.Io, loop: *Loop) void { + while (true) { + tick_request.waitUncancelable(io); + tick_request.reset(); + var ts: libc.timespec = .{ .sec = 0, .nsec = @as(isize, pardes.layout.Animation.frame_ms) * std.time.ns_per_ms }; + _ = libc.nanosleep(&ts, null); + loop.postEvent(.tick) catch {}; + } +} + fn wakeFs(ctx: ?*anyopaque) void { const loop: *Loop = @ptrCast(@alignCast(ctx.?)); _ = loop.tryPostEvent(.fs_ready) catch {}; diff --git a/test/output.zig b/test/output.zig index ad33954f..7c80e105 100644 --- a/test/output.zig +++ b/test/output.zig @@ -1089,7 +1089,8 @@ test "identical result refresh keeps warm content caches without allocation" { try std.testing.expectEqual(revision + 1, file.revision); try std.testing.expectEqualStrings("short\n", file.content); try std.testing.expectEqualStrings("changed", file.output.?.arg()); - try std.testing.expectEqual(@as(usize, 0), file.line_starts.len); + // The warm index is carried through the edit, not dropped. + 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); diff --git a/test/panes.zig b/test/panes.zig index 8e71e69d..2d3aed43 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -394,6 +394,42 @@ const BodyHitTests = struct { } }; +const LineNumberLookTests = struct { + test "right-click on a line number looks at that line, sticky context headers included" { + if (!syntax.enabled) return error.SkipZigTest; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 64, .rows = 18 }); + defer p.deinit(); + p.row_metrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 8, .tagline_h = 10 }; + const pane = try TreeContextTests.setZigFile(p, "const Box = struct {\n pub fn work(\n value: usize,\n ) void {\n" ++ " // body\n" ** 60 ++ " }\n};\n"); + try std.testing.expect(p.executeBuiltinLine(0, "TreeContext")); + pane.scrollBy(30); + var frame = std.heap.ArenaAllocator.init(p.gpa); + defer frame.deinit(); + _ = try p.render(frame.allocator()); + const layer = &p.surface.body_layers[0]; + try std.testing.expect(layer.context_rows >= 2); + // A header row's number is its declaration's own source line, not the + // body line it sits over (`pub fn work(` is line 1); a body row's is + // its own. + try std.testing.expectEqual(@as(i32, 1), pane.wrapAt(1).line); + const rows = [_]u16{ 1, pane.context_rows + 3 }; + for (rows) |row| { + // Each Look recentres the view; come back under the headers. + pane.scrollBy(30 - pane.scroll()); + _ = frame.reset(.retain_capacity); + _ = try p.render(frame.allocator()); + const expected = pane.wrapAt(row).line; + var press = BodyHitTests.mouse(&p.surface.body_layers[0], row, 1, .press); + press.button = .right; + var release = BodyHitTests.mouse(&p.surface.body_layers[0], row, 1, .release); + release.button = .right; + p.update(.{ .mouse = press }); + p.update(.{ .mouse = release }); + try std.testing.expectEqual(expected, pane.cur_row); + } + } +}; + const TreeContextTests = struct { const source = "const Box = struct {\n" ++ " pub fn work(\n" ++ @@ -4069,6 +4105,7 @@ test { _ = TagNameTintTests; _ = TreeContextTests; _ = BodyHitTests; + _ = LineNumberLookTests; _ = TtySelectionTests; _ = ClickCursorTests; _ = JumpSelectionTests; diff --git a/test/pdf_pointer_bench.zig b/test/pdf_pointer_bench.zig new file mode 100644 index 00000000..f1d61229 --- /dev/null +++ b/test/pdf_pointer_bench.zig @@ -0,0 +1,224 @@ +//! Pointer gestures over a native PDF pane: hovering words (the Look preview +//! highlight), and dragging a selection to its release. +//! +//! zig build pdf-pointer-bench -Doptimize=ReleaseFast -- [--label L] [--reps N] [--path FILE] +//! [--cell WxH] [--scroll NOTCHES] [--verify 1] [--live 1] +//! +//! Every frame is timed the way a shell pump spends it: the event through +//! `Pardes.update`, one `render()` into a reset arena, the effect drain. A +//! hover step is its motion frame plus every tick frame the preview animates +//! before settling, which is when the highlight lands. Stdout is CSV, +//! `label,scenario:kind,round,ns`, one row per frame and one per step +//! (`kind=step`), for an external statistics pass. +//! +//! `visual` hashes every presented raster in full, with its placement, on the +//! frame each step settles on. It is the no-regression proof: a change to how highlights +//! are painted may change what it costs, never one presented pixel. +const std = @import("std"); +const pardes = @import("pardes"); +const pdf = @import("mupdf"); + +pub const std_options: std.Options = .{ .log_level = .err }; + +const gpa = std.heap.smp_allocator; +const cols: u16 = 120; +const rows: u16 = 40; + +const Config = struct { + path: []const u8 = "docs/design.pdf", + label: []const u8 = "run", + reps: usize = 5, + /// Wheel notches before the gestures, off the sparse title page. + scroll: usize = 40, + /// 8x16 is the Kitty policy's cell; the SDL shell's is closer to 16x35. + cell_w: u16 = 8, + cell_h: u16 = 16, + /// Re-render every raster that claims to hold the current highlights and + /// compare it row by row: exactness without a baseline build. + verify: bool = false, + /// A shell that takes row patches: selections repaint while dragged. + live: bool = false, +}; + +pub fn main(init: std.process.Init) !void { + const args = try init.minimal.args.toSlice(init.arena.allocator()); + var config: Config = .{}; + var i: usize = 1; + while (i + 1 < args.len) : (i += 2) { + const value = args[i + 1]; + if (std.mem.eql(u8, args[i], "--path")) config.path = value else if (std.mem.eql(u8, args[i], "--label")) config.label = value else if (std.mem.eql(u8, args[i], "--reps")) config.reps = try std.fmt.parseUnsigned(usize, value, 10) else if (std.mem.eql(u8, args[i], "--scroll")) config.scroll = try std.fmt.parseUnsigned(usize, value, 10) else if (std.mem.eql(u8, args[i], "--verify")) config.verify = std.mem.eql(u8, value, "1") else if (std.mem.eql(u8, args[i], "--live")) config.live = std.mem.eql(u8, value, "1") else if (std.mem.eql(u8, args[i], "--cell")) { + var it = std.mem.splitScalar(u8, value, 'x'); + config.cell_w = try std.fmt.parseUnsigned(u16, it.next() orelse "", 10); + config.cell_h = try std.fmt.parseUnsigned(u16, it.next() orelse "", 10); + } else return error.UnknownOption; + } + if (i != args.len) return error.MissingValue; + + var visual: ?u64 = null; + for (0..config.reps) |round| { + const got = try measure(config, round); + if (visual) |want| if (want != got) { + std.debug.print("pdf-pointer-bench: visual changed between rounds: {x} vs {x}\n", .{ want, got }); + return error.Unstable; + }; + visual = got; + } + std.debug.print("pdf-pointer-bench {s}: visual={x:0>16}\n", .{ config.label, visual.? }); +} + +const Run = struct { + core: *pardes.Pardes, + arena: std.heap.ArenaAllocator, + config: Config, + round: usize, + visual: u64 = 0x7061_7264_6573_5050, + step_ns: u64 = 0, + frames: usize = 0, + steps: usize = 0, + last: ?*const pardes.Surface = null, + + fn frame(run: *Run, scenario: []const u8, kind: []const u8, event: pardes.Event) !void { + const started = nowNs(); + run.core.update(event); + while (run.core.nextEffect()) |_| {} + _ = run.arena.reset(.retain_capacity); + const surface = try run.core.render(run.arena.allocator()); + while (run.core.nextEffect()) |_| {} + const elapsed = nowNs() - started; + run.step_ns += elapsed; + run.frames += 1; + print("{s},{s}:{s},{d},{d}\n", .{ run.config.label, scenario, kind, run.round, elapsed }); + run.last = surface; + if (run.config.verify) try verify(run.core, run.arena.allocator()); + } + + /// The step, then the tick frames its animation asks for (a hover's + /// preview arrives on one of them), as a pump with nothing else queued. + fn step(run: *Run, scenario: []const u8, kind: []const u8, event: pardes.Event) !void { + run.step_ns = 0; + try run.frame(scenario, kind, event); + var ticks: usize = 0; + while (run.core.animationActive() and ticks < 32) : (ticks += 1) + try run.frame(scenario, "tick", .tick); + print("{s},{s}:step,{d},{d}\n", .{ run.config.label, scenario, run.round, run.step_ns }); + // Only the settled frame is the invariant: how many frames a preview + // takes to arrive is a setting (look_preview_delay_frames). + run.observe(run.last.?); + run.steps += 1; + } + + fn observe(run: *Run, surface: *const pardes.Surface) void { + for (surface.images[0..surface.nimages]) |maybe| { + const place = maybe orelse continue; + run.visual = mix(run.visual, [_]u64{ place.pane, place.x, place.y, place.w, place.h, place.native.page, place.iw, place.ih }); + if (place.native.geometry) |g| run.visual = mix(run.visual, [_]u64{ g.src.x, g.src.y, g.src.w, g.src.h, g.dst.x, g.dst.y, g.dst.w, g.dst.h }); + run.visual = std.hash.Wyhash.hash(run.visual, place.rgba); + } + } +}; + +var verify_failures: usize = 0; + +fn verify(core: *pardes.Pardes, arena: std.mem.Allocator) !void { + const Pdf = pardes.panes.Pdf; + const pane = core.panes[0] orelse return; + const state = &(pane.pdf orelse return); + const highlights = try Pdf.buildHighlights(state, arena, Pdf.highlightInput(core, 0, pane)); + for (state.rasters[0..state.rasters_len]) |*r| { + if (!r.valid or r.rgba.len == 0 or r.tint_key == null) continue; + const want = highlights.forPage(r.page); + if (comptime !@hasField(@TypeOf(r.*), "baked")) return else if (!std.mem.eql(u8, std.mem.sliceAsBytes(want), std.mem.sliceAsBytes(r.baked))) continue; + const shape = try state.document.measureRenderAt(r.page, r.request); + // The oracle is the WHOLE page: a band's own edge rows can differ. + const whole = try arena.alloc(u8, shape.len); + try state.document.renderIntoAtWithPaper(r.page, r.request, shape, shape.wholePage(), want, whole, false); + try pdf.tintRgba(whole, r.tint_key.?.mode, r.tint_key.?.colors); + const fresh = whole[r.band_y * shape.stride ..][0 .. r.band_h * shape.stride]; + var first: ?usize = null; + var last: usize = 0; + var count: usize = 0; + for (0..r.band_h) |y| { + const row = fresh[y * shape.stride ..][0..shape.stride]; + if (std.mem.eql(u8, row, r.rgba[y * shape.stride ..][0..shape.stride])) continue; + if (first == null) first = y; + last = y; + count += 1; + } + if (first) |f| { + verify_failures += 1; + if (verify_failures <= 20) std.debug.print("verify: page {d} rows {d}..{d} ({d} differ), highlights {d}, band {d}+{d}\n", .{ r.page, f + r.band_y, last + r.band_y, count, want.len, r.band_y, r.band_h }); + } + } +} + +fn measure(config: Config, round: usize) !u64 { + const core = try pardes.Pardes.init(gpa, .{ .file = config.path, .cols = cols, .rows = rows }); + defer core.deinit(); + core.native_images = true; + if (comptime @hasField(pardes.Pardes, "native_image_patches")) core.native_image_patches = config.live; + var run: Run = .{ .core = core, .arena = .init(gpa), .config = config, .round = round }; + defer run.arena.deinit(); + const cell: pardes.CellPixels = .{ .w = config.cell_w, .h = config.cell_h }; + core.update(.{ .resize = .{ .cols = cols, .rows = rows, .cell_pixels = cell } }); + _ = try core.render(run.arena.allocator()); + const pane = core.panes[0] orelse return error.NoPane; + if (pane.pdf == null) return error.NotPdf; + const rect = core.rects[0]; + const mid_col = rect.x + rect.w / 2; + const mid_row = rect.y + rect.h / 2; + for (0..config.scroll) |_| { + core.update(.{ .mouse = .{ .button = .wheel_down, .kind = .press, .col = mid_col, .row = mid_row } }); + _ = run.arena.reset(.retain_capacity); + _ = try core.render(run.arena.allocator()); + while (core.nextEffect()) |_| {} + } + + const top = rect.y + 4; + const bottom = rect.y + rect.h -| 3; + const left = rect.x + 4; + const right = rect.x + rect.w -| 4; + + // Hover: walk four rows of the body, a word-ish stride at a time. + var row: u16 = top; + while (row < bottom) : (row += (bottom - top) / 4) { + var col: u16 = left; + while (col < right) : (col += 3) + try run.step("hover", "motion", .{ .mouse = .{ .button = .none, .kind = .motion, .col = col, .row = row } }); + } + // Leave the page so the last preview is withdrawn like a real exit. + try run.step("hover", "leave", .pointer_leave); + + // Select: press, drag across three lines, release; five times down the page. + row = top; + while (row + 3 < bottom) : (row += (bottom - top) / 5) { + try run.step("select", "press", .{ .mouse = .{ .button = .left, .kind = .press, .col = left, .row = row } }); + var n: u16 = 1; + while (n <= 24) : (n += 1) { + const col = left + (right - left) * (n % 8) / 8; + try run.step("select", "drag", .{ .mouse = .{ .button = .left, .kind = .drag, .col = col, .row = row + n / 8 } }); + } + try run.step("select", "release", .{ .mouse = .{ .button = .left, .kind = .release, .col = right, .row = row + 3 } }); + } + return mix(run.visual, @as(u64, run.steps)); +} + +fn print(comptime format: []const u8, args: anytype) void { + var buf: [256]u8 = undefined; + const line = std.fmt.bufPrint(&buf, format, args) catch return; + _ = std.c.write(1, line.ptr, line.len); +} + +fn mix(seed: u64, value: anytype) u64 { + var copy = value; + return std.hash.Wyhash.hash(seed, std.mem.asBytes(©)); +} + +fn nowNs() u64 { + var ts: std.c.timespec = undefined; + _ = std.c.clock_gettime(.MONOTONIC, &ts); + return @as(u64, @intCast(ts.sec)) * 1_000_000_000 + @as(u64, @intCast(ts.nsec)); +} + +comptime { + _ = pdf.Document; +} diff --git a/test/snapshot.zig b/test/snapshot.zig index 7cc5eb91..bdabb56e 100644 --- a/test/snapshot.zig +++ b/test/snapshot.zig @@ -569,7 +569,9 @@ fn runScript(arena: std.mem.Allocator, exe_z: [:0]const u8, script_path: []const try mkdir(arena, config_home, false); const pardes_config = try std.fmt.allocPrint(arena, "{s}/pardes", .{config_home}); try mkdir(arena, pardes_config, false); - try eh.writeFile(try std.fmt.allocPrintSentinel(arena, "{s}/init", .{pardes_config}, 0), "Shell bash\n"); + // Messages leave the moment they are dismissed, as goldens have always + // recorded: a linger or a dissolve is time, and time cannot be a golden. + try eh.writeFile(try std.fmt.allocPrintSentinel(arena, "{s}/init", .{pardes_config}, 0), "Shell bash\nMessageAnimation off\nMessageLinger 0\n"); _ = setenv("TERM", "xterm-256color", 1); _ = setenv("LC_ALL", "C", 1); // a wall clock cannot live in a golden; everything that would print one diff --git a/test/snapshots/builtins.snap b/test/snapshots/builtins.snap index cd47209f..02547b91 100644 --- a/test/snapshots/builtins.snap +++ b/test/snapshots/builtins.snap @@ -19,6 +19,10 @@ wheel up 110 50 wheel up 110 50 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/dump.golden b/test/snapshots/dump.golden index 8f920136..e466dbf1 100644 --- a/test/snapshots/dump.golden +++ b/test/snapshots/dump.golden @@ -38,6 +38,7 @@ .cwd = "/tmp/pardes-snap/dump/cwd", .stream = "ls\nd.txt\n", .stream_b64 = + .stream_is_screen = true, .cursor = .{ .col = 2, .row = 2 }, }, .file = null, @@ -57,6 +58,7 @@ .cwd = "/tmp/pardes-snap/dump/cwd", .stream = "ls\nd.txt\n", .stream_b64 = + .stream_is_screen = true, .cursor = .{ .col = 2, .row = 2 }, }, .file = null, @@ -76,6 +78,7 @@ .cwd = "/tmp/pardes-snap/dump/cwd", .stream = "ls\nd.txt\n", .stream_b64 = + .stream_is_screen = true, .cursor = .{ .col = 2, .row = 2 }, }, .file = null, diff --git a/test/snapshots/load.golden b/test/snapshots/load.golden index 994ab83e..32024cec 100644 --- a/test/snapshots/load.golden +++ b/test/snapshots/load.golden @@ -2,10 +2,10 @@ |Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill | New Tty Find Grep Joincol Delcol New Tty Find Grep Joincol Delcol | /tmp/pardes-snap/load/cwd Tty Save Mode Filter /tmp/pardes-snap/load/cwd Tty Save Mode Filter -| echo LOAD''MARK; seq 1 40; echo E''ND ls +| $ echo LOAD''MARK; seq 1 40; echo E''ND $ ls | LOADMARK d.txt -| 1 -| 2 +| 1 $ +| 2 ── restored history ── | 3 | 4 | 5 @@ -17,8 +17,10 @@ | 11 | 12 | /tmp/pardes-snap/load/cwd Tty Save Mode Filter -| ls +| $ ls | d.txt +| $ +| ── restored history ── == style loaded 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-49 d,#26362d, 50-51 #ffffff,#887455, 52-52 d,#1d2824, 53-84 #b2c3b8,#1d2824, 85-99 d,#1d2824, @@ -26,8 +28,8 @@ |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|7: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|6: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-73 #e5eee5,#0d1410,f 74-99 #e5eee5,#0d1410, +|7: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-99 d,#0d1410, |8: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, |9: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, |10: 0-0 d,#152019, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, @@ -41,8 +43,8 @@ |18: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, |19: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, |20: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, -|22: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|21: 0-0 d,#608269, 1-1 d,#0d1410, 2-23 #e5eee5,#0d1410,f 24-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, +|22: 0-0 d,#608269, 1-49 d,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, |23: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, |24: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, |25: 0-0 d,#608269, 1-1 d,#0d1410, 2-49 #e5eee5,#0d1410, 50-50 d,#608269, 51-51 d,#0d1410, 52-99 #e5eee5,#0d1410, diff --git a/test/snapshots/restore.golden b/test/snapshots/restore.golden index 11d92288..01b52984 100644 --- a/test/snapshots/restore.golden +++ b/test/snapshots/restore.golden @@ -6,9 +6,7 @@ | $ echo KEEP''ME | KEEPME | $ -== snap restored grid=100x31 cursor=4,6 +== snap restored grid=100x31 cursor=4,8 |0: Newcol Joincol Find Grep Help Changelog Tutor Dump NextColor Debug Kill |2: /tmp/pardes-snap/restore/cwd Tty Save Mode Filter Collapse Del -|3: ls -|4: echo KEEP''ME -|6: +|7: ── restored history ── -- cgit v1.3 From 7ba54de4bd498c2a56ea3d0d43c88356759f7b1f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 22:34:56 -0300 Subject: Move saving and loading a whole editor out of pardes.zig into dump.zig Pure move, no behaviour change (acme keeps dump and load in rows.c): dumpState, restore, initFromDump and initDump go verbatim to the end of dump.zig, after the dump format they read and write. Inside dump.zig the moved code's `dump.` prefix drops, so `Pane` there is the dump record; the one editor pane it names is spelled `pardes.panes.Pane`, and its other `panes.X` references become `pardes.panes.X` because dump.zig's own tests use `panes` as a local name. The methods become free functions taking `p: *Pardes`: `p.dumpState()` becomes `dump.dumpState(p)`, `core.restore(bytes)` becomes `dump.restore(core, bytes)` and `Pardes.initFromDump(..)` becomes `dump.initFromDump(..)`, in pardes.zig, the shells, layout.zig, Terminal.zig, builtins.zig and the tests (38 receiver rewrites plus the initFromDump calls). The tag-tail restore helpers stay with the tag code. Co-Authored-By: Claude Opus 5.5 --- src/Terminal.zig | 4 +- src/builtins.zig | 3 +- src/detached/client.zig | 3 +- src/detached/server.zig | 7 +- src/dump.zig | 238 ++++++++++++++++++++++++++++++++++++++++++++ src/gui/gui.zig | 11 +- src/layout.zig | 5 +- src/macos.zig | 7 +- src/pardes.zig | 260 ++++-------------------------------------------- src/tty/tty.zig | 5 +- src/web.zig | 2 +- test/fs_namespace.zig | 21 ++-- test/output.zig | 12 +-- test/panes.zig | 10 +- test/pdf.zig | 6 +- 15 files changed, 312 insertions(+), 282 deletions(-) (limited to 'src/dump.zig') diff --git a/src/Terminal.zig b/src/Terminal.zig index a8588952..cb752613 100644 --- a/src/Terminal.zig +++ b/src/Terminal.zig @@ -628,8 +628,8 @@ test "a restored terminal keeps its history above a marker and gets a shell wher const pane = p.panes[0].?; feedOutput(p, pane, "old output\r\n$ ls\r\n"); try pane.setOwnedCwd("/tmp"); - try p.dumpState(); - const restored = try Pardes.initFromDump(gpa, .{ .tty_only = true, .cols = 40, .rows = 12 }, p.dump_out.?); + 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) { diff --git a/src/builtins.zig b/src/builtins.zig index 19be62e2..743573e4 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1,6 +1,7 @@ //! Command structs and runtime settings form the builtin registry; bindings live in config.zig. const std = @import("std"); const pardes = @import("pardes.zig"); +const dump = @import("dump.zig"); const exec = @import("exec.zig"); const look = @import("look.zig"); const edit = @import("edit.zig"); @@ -239,7 +240,7 @@ pub const Kill = struct { pub const Dump = struct { pub fn run(c: Ctx) void { - c.p.dumpState() catch {}; + dump.dumpState(c.p) catch {}; } }; diff --git a/src/detached/client.zig b/src/detached/client.zig index a027c0bb..7cee790a 100644 --- a/src/detached/client.zig +++ b/src/detached/client.zig @@ -59,6 +59,7 @@ const std = @import("std"); const libc = std.c; const pardes = @import("../pardes.zig"); +const dump = @import("../dump.zig"); const server = @import("server.zig"); const wire = @import("wire.zig"); @@ -842,7 +843,7 @@ test "detached Restore keeps attached frontends and follows queued frames with a try testing.expectEqual(fd, h.session.clients[c.slot].fd); try testing.expect(h.session.clients[c.slot].attached); - try h.core.dumpState(); + try dump.dumpState(h.core); const saved = try testing.allocator.dupe(u8, h.core.dump_out.?); defer testing.allocator.free(saved); while (h.core.nextEffect()) |_| {} diff --git a/src/detached/server.zig b/src/detached/server.zig index e33354cf..b75fa5ad 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -4,6 +4,7 @@ const builtin = @import("builtin"); const libc = std.c; const posix = std.posix; const pardes = @import("../pardes.zig"); +const dump = @import("../dump.zig"); const wire = @import("wire.zig"); const host_io = @import("../host_io.zig"); @@ -233,7 +234,7 @@ pub const Session = struct { } pub fn restore(s: *Session, bytes: []const u8) !void { - const replacement = try s.core.restore(bytes); + const replacement = try dump.restore(s.core, bytes); s.cancelWorkers(); for (0..s.ptys.len) |pane| s.closePty(@intCast(pane)); s.harvest(); @@ -1129,7 +1130,7 @@ pub fn run(init: std.process.Init, opts: pardes.Options, name: []const u8) !void const core = if (options.load_path) |lp| blk: { const bytes = try filesystem.readFile(gpa, lp); defer gpa.free(bytes); - break :blk try pardes.Pardes.initFromDump(allocs.pardes, options, bytes); + break :blk try pardes.dump.initFromDump(allocs.pardes, options, bytes); } else try pardes.Pardes.init(allocs.pardes, options); var session: Session = .{ .gpa = gpa, @@ -1197,7 +1198,7 @@ test "detached queued results preserve current requests and are discarded before try std.testing.expectEqual(current_id, s.lsp_task.?.id); try std.testing.expectEqual(current_id, s.core.lsp_wait.?.id); - try s.core.dumpState(); + try dump.dumpState(s.core); const saved = try gpa.dupe(u8, s.core.dump_out.?); defer gpa.free(saved); while (s.core.nextEffect()) |_| {} diff --git a/src/dump.zig b/src/dump.zig index ff5d2166..0ce2d10e 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -6,6 +6,26 @@ const limits = @import("memory.zig").limits; // wholesale (ghostty and uucode log there too), and a corrupt dump's parse // diagnostic is the only thing that says WHICH field went bad. const log = std.log.scoped(.dump); +const pardes = @import("pardes.zig"); +const layout = @import("layout.zig"); +const filesystem = @import("fs.zig"); +const ctlfs = @import("ninep/tree.zig"); +const exec = @import("exec.zig"); +const body_layer = @import("body_layer.zig"); +const colors = @import("colors.zig"); +const themes = colors.themes; +const config = @import("config.zig"); +const pdf_enabled = pardes.pdf_enabled; +const platform = pardes.platform; +const isolated = pardes.isolated; +const terminal_panes = pardes.terminal_panes; +const MAX_PANES = pardes.MAX_PANES; +const MAX_COLS = pardes.MAX_COLS; +const column_weight_unit = layout.column_weight_unit; +const max_column_weight = layout.max_column_weight; +const effect_path_cap = pardes.effect_path_cap; +const Options = pardes.Options; +const Pardes = pardes.Pardes; /// Where the next dump goes. $PARDES_DUMP wins verbatim (the snapshot harness /// pins it for deterministic goldens); else $XDG_DATA_HOME|~/.local/share @@ -570,3 +590,221 @@ test "validation bounds pane restore state" { panes[0].tag_tail = oversized_tail[0..limits.max_tag_tail]; try validate(state); } + +// ---- a whole editor to and from a dump (acme keeps this in rows.c) ---- + +pub fn dumpState(p: *Pardes) !void { + const arena = p.scratch.allocator(); + var slot_to_pane: [MAX_PANES]?usize = @splat(null); + var dump_panes: [MAX_PANES]Pane = undefined; + var panes_len: usize = 0; + for (p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + slot_to_pane[id] = panes_len; + const tag = try p.tagText(arena, pane); + 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( + arena, + pane, + f, + tag, + body, + scroll, + if (f.output) |o| pardes.panes.Output.word(o.from) else "", + if (f.output) |*o| o.arg() else "", + ) else if (pane.hasPdf()) blk: { + if (comptime !pdf_enabled) unreachable; + const pv = &pane.pdf.?; + break :blk try pardes.panes.Image.dumpPane(p, arena, pane, tag, body, pv.page, pv.path, &.{}); + } 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); + dp.tag_tail = if (pane.tag_init) pane.tagSlice() else null; + dump_panes[panes_len] = dp; + panes_len += 1; + } + + var columns: [MAX_COLS]Column = undefined; + var columns_len: usize = 0; + var column_ids: [MAX_COLS][MAX_PANES]usize = undefined; + for (0..p.ncol) |c| { + var ids_len: usize = 0; + for (0..p.col_n[c]) |k| if (slot_to_pane[p.col_panes[c][k]]) |compact| { + column_ids[c][ids_len] = compact; + ids_len += 1; + }; + if (ids_len > 0) { + columns[columns_len] = .{ + .tag = if (p.col_tags[c].custom) p.columnTag(c) else null, + .weight = @as(f32, @floatFromInt(p.col_weight[c])) / @as(f32, @floatFromInt(column_weight_unit)), + .panes = column_ids[c][0..ids_len], + }; + columns_len += 1; + } + } + + var mounts: [filesystem.max_mounts]Mount = undefined; + for (p.fs.mounts.items, 0..) |mount, i| mounts[i] = .{ .name = mount.name, .dial = mount.dial }; + const state: State = .{ + .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, + .theme = p.theme().name, + .locations_config = p.locations_config, + .tree_context_tag_style = p.settings.tree_context_tag_style, + .columns = columns[0..columns_len], + .panes = dump_panes[0..panes_len], + .mounts = mounts[0..p.fs.mounts.items.len], + }; + try validate(state); + var out: std.Io.Writer.Allocating = .init(p.gpa); + errdefer out.deinit(); + try std.zon.stringify.serialize(state, .{ .whitespace = true }, &out.writer); + if (p.dump_out) |d| p.gpa.free(d); + p.dump_out = try out.toOwnedSlice(); + p.emit(.write_dump); +} + +pub fn restore(p: *Pardes, zon_bytes: []const u8) !*Pardes { + var opts = p.opts; + opts.cols = p.screen_w; + opts.rows = p.screen_h; + return initDump(p.gpa, opts, zon_bytes, p); +} + +pub fn initFromDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8) !*Pardes { + return initDump(gpa, opts, zon_bytes, null); +} + +fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previous: ?*const Pardes) !*Pardes { + const image_gpa = opts.image_allocator orelse gpa; + const pdf_gpa = opts.pdf_allocator orelse gpa; + const tree_sitter_gpa = opts.tree_sitter_allocator orelse gpa; + const p = try gpa.create(Pardes); + p.* = .{ + .gpa = gpa, + .image_gpa = image_gpa, + .pdf_gpa = pdf_gpa, + .tree_sitter_gpa = tree_sitter_gpa, + .opts = opts, + .fs = .{}, + .screen_w = opts.cols, + .screen_h = opts.rows, + .scratch = .init(gpa), + .frame_arena = .init(opts.frame_allocator orelse gpa), + .fallback = .{ .gpa = gpa }, + }; + errdefer p.deinit(); + if (previous) |old| { + p.next_serial = old.next_serial; + p.lsp_seq = old.lsp_seq; + p.pipe_seq = old.pipe_seq; + p.cell_pixels = old.cell_pixels; + p.row_metrics = old.row_metrics; + p.native_images = old.native_images; + } + for (opts.mounts) |mount| try p.fs.mount(gpa, mount.name, mount.dial); + p.opts.mounts = &.{}; + var parsed = try readZon(gpa, zon_bytes, "load"); + defer parsed.deinit(); + const st = parsed.value; + p.locations_config = st.locations_config; + p.settings.tree_context_tag_style = st.tree_context_tag_style; + for (st.mounts) |mount| { + var already_mounted = false; + for (p.fs.mounts.items) |existing| { + if (!std.mem.eql(u8, mount.name, existing.name)) continue; + if (!std.mem.eql(u8, mount.dial, existing.dial)) return error.MountConflict; + already_mounted = true; + break; + } + if (!already_mounted) try p.fs.mount(gpa, mount.name, mount.dial); + } + + for (themes, 0..) |t, i| { + if (std.mem.eql(u8, t.name, st.theme)) p.settings.theme = @intCast(i); + } + for (st.panes, 0..) |src, i| { + if (i >= MAX_PANES) break; + const pane: *pardes.panes.Pane = switch (src.kind) { + .terminal => terminal: { + const t = src.terminal.?; + // A host that runs shells gets them back: the old history + // above a new shell in the directory it was in. The web + // shell and an isolated build only ever replay it. + const live = comptime (terminal_panes and platform != .web and !isolated); + const revive = live and t.cwd.len <= effect_path_cap; + 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 (revive) p.emit(.{ .spawn = .{ .pane = @intCast(i), .cwd = .from(t.cwd) } }); + break :terminal restored; + }, + .file => try pardes.panes.File.restore(p, i, src), + .image => restore_image: { + const im = src.image.?; + if (pardes.panes.Pdf.isPath(im.path)) { + var raw: []u8 = if (im.bytes_b64.len > 0) + try decodeBytes(gpa, im.bytes_b64) + else + &.{}; + errdefer if (raw.len > 0) gpa.free(raw); + if (comptime pdf_enabled) { + if (pardes.panes.Pdf.openPane(p, i, im.path, src.scroll + 1) catch null) |restored| { + if (raw.len > 0) gpa.free(raw); + raw = &.{}; + restored.cols = @max(1, src.cols); + restored.rows = @max(1, src.rows); + break :restore_image restored; + } + } + // If the source path is unavailable, retain its bytes + // as an ordinary file rather than dropping the pane. + const path = try gpa.dupe(u8, im.path); + errdefer gpa.free(path); + const content = if (raw.len > 0) raw else try gpa.dupe(u8, ""); + raw = &.{}; + errdefer if (content.len > 0) gpa.free(content); + const history = try pardes.panes.File.History.create(gpa); + errdefer gpa.destroy(history); + const restored = try p.newDocPane(i); + restored.file = .{ .path = path, .content = content, .history = history }; + restored.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 } }); + break :restore_image restored; + } + break :restore_image try pardes.panes.Image.restore(p, i, src); + }, + }; + p.restoreDumpTail(pane, src); + pane.vweight = src.vweight; + pane.collapsed = src.collapsed; + } + p.ncol = @min(st.columns.len, MAX_COLS); + p.col_serial = @splat(0); + if (st.topbar_custom) |bar| _ = p.global_tag.set(bar); + for (st.columns[0..p.ncol], 0..) |col, c| { + if (col.tag) |bar| _ = p.col_tags[c].set(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)))); + p.col_n[c] = @min(col.panes.len, MAX_PANES); + for (col.panes[0..p.col_n[c]], 0..) |pid, k| p.col_panes[c][k] = pid; + } + p.active = @min(st.active, MAX_PANES - 1); + p.sync(); + exec.applyStartupConfig(p); + colors.finishThemeInitialization(p); + p.sync(); + p.presentation.enabled = true; + _ = p.takeHaptic(); // see init: a restored session is not a gesture + try p.fs.log.buf.ensureTotalCapacityPrecise(p.gpa, p.fs.log.cap); + ctlfs.events.announce(p); + return p; +} diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 86c69ff6..f044ca17 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -6,6 +6,7 @@ const libc = std.c; const vaxis = @import("vaxis"); // test modes only: the stdin escape-seq parser const ghostty_vt = @import("ghostty-vt"); // 256-color palette for .index cells const pardes = @import("../pardes.zig"); +const dump = @import("../dump.zig"); const config = @import("../config.zig"); const look = @import("../look.zig"); const message = pardes.Messages.Message; @@ -1298,7 +1299,7 @@ test "GUI PTY Restore joins a real reader waiting for queue space" { const gpa = std.testing.allocator; var core = try pardes.Pardes.init(gpa, .{ .tty_only = true }); defer core.deinit(); - try core.dumpState(); + try dump.dumpState(core); var workers: LspWorkers = .{}; var queue: Queue = .{ .gpa = gpa, .lsp_allocator = gpa, .lsp_workers = &workers, .sdl_wake = false }; defer queue.deinit(); @@ -1321,7 +1322,7 @@ test "GUI PTY Restore joins a real reader waiting for queue space" { try std.testing.expect(host_io.writeFd(child.file.handle, "printf 'after-full'; exit\n")); try PtyTests.waitBlocked(&queue); const old_serial = core.panes[0].?.serial; - const replacement = try core.restore(core.dump_out.?); + const replacement = try dump.restore(core, core.dump_out.?); shell.stopPtys(); core.deinit(); core = replacement; @@ -2453,7 +2454,7 @@ fn localSession( var core = if (opts.load_path) |lp| blk: { const bytes = try @import("../fs.zig").readFile(gpa, lp); defer gpa.free(bytes); - break :blk try pardes.Pardes.initFromDump(allocs.pardes, opts, bytes); + break :blk try pardes.dump.initFromDump(allocs.pardes, opts, bytes); } else try pardes.Pardes.init(allocs.pardes, opts); defer core.deinit(); core.native_images = true; @@ -2559,7 +2560,7 @@ fn localSession( break :blk; }; defer gpa.free(bytes); - const nc = core.restore(bytes) catch |err| { + const nc = dump.restore(core, bytes) catch |err| { core.reportError(core.active, "Restore", err); break :blk; }; @@ -2772,7 +2773,7 @@ fn runGrid(init: std.process.Init, opts_in: pardes.Options) !void { const core = if (opts.load_path) |lp| blk: { const bytes = try @import("../fs.zig").readFile(gpa, lp); defer gpa.free(bytes); - break :blk try pardes.Pardes.initFromDump(allocs.pardes, opts, bytes); + break :blk try pardes.dump.initFromDump(allocs.pardes, opts, bytes); } else try pardes.Pardes.init(allocs.pardes, opts); defer core.deinit(); if (opts.load_path == null) diff --git a/src/layout.zig b/src/layout.zig index 116a64b8..3d8932a8 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -1,5 +1,6 @@ const std = @import("std"); const pardes = @import("pardes.zig"); +const dump = @import("dump.zig"); const config = @import("config.zig"); const panes = @import("panes.zig"); const Pardes = pardes.Pardes; @@ -1442,8 +1443,8 @@ test "collapse dump restores folded state and retained expansion weight" { compute(p); const original_height = p.rects[0].h; toggleCollapse(p, 0); - try p.dumpState(); - const restored = try Pardes.initFromDump(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 32 }, p.dump_out.?); + try dump.dumpState(p); + const restored = try dump.initFromDump(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 32 }, p.dump_out.?); defer restored.deinit(); try std.testing.expect(restored.panes[0].?.collapsed); try std.testing.expectEqual(@as(f32, @floatFromInt(original_height)), restored.panes[0].?.vweight); diff --git a/src/macos.zig b/src/macos.zig index f83fb8b4..78356810 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -6,6 +6,7 @@ const builtin = @import("builtin"); const posix = std.posix; const libc = std.c; const pardes = @import("pardes.zig"); +const dump = @import("dump.zig"); const mouse = @import("mouse.zig"); const colors = @import("colors.zig"); const look = @import("look.zig"); @@ -1344,7 +1345,7 @@ fn restoreCore(st: *State) bool { return false; }; defer st.gpa.free(bytes); - const replacement = st.core.restore(bytes) catch |err| { + const replacement = dump.restore(st.core, bytes) catch |err| { st.core.reportError(st.core.active, "Restore", err); return false; }; @@ -1411,7 +1412,7 @@ test "mac Restore keeps host state and rejects callbacks from the old core" { const old_serial = core.panes[0].?.serial; st.gens[0] = 23; const old_watch = try st.file_watches.replace(gpa, 0, "/test.txt", old_serial, .{ .text = 0 }); - try core.dumpState(); + try dump.dumpState(core); try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "restore.zon", .data = core.dump_out.? }); while (core.nextEffect()) |_| {} @@ -1501,7 +1502,7 @@ test "mac Restore cancels a PTY reader waiting for output capacity" { defer st.config_arena.deinit(); defer st.file_watches.deinit(gpa); defer st.inbox.close(gpa, io); - try st.core.dumpState(); + try dump.dumpState(st.core); try tmp.dir.writeFile(io, .{ .sub_path = "restore.zon", .data = st.core.dump_out.? }); while (st.core.nextEffect()) |_| {} for (0..inbox_output_limit) |_| try st.inbox.pushOutput(gpa, io, .{ diff --git a/src/pardes.zig b/src/pardes.zig index 75766827..44f0d2ea 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -779,8 +779,8 @@ test "LocationsConfig command reports partial updates and survives restore" { try std.testing.expectEqualStrings("LocationsConfig context:5 tscontext:on tslocations:off layout:stacked\n", file.content); } try std.testing.expectEqual(@as(usize, 1), reports); - try p.dumpState(); - const restored = try Pardes.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); + try dump.dumpState(p); + const restored = try dump.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); defer restored.deinit(); try std.testing.expectEqual(expected, restored.locations_config); } @@ -829,8 +829,8 @@ test "TreeContext tag style preserves message rows and its opt-out survives rest 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 p.dumpState(); - const restored = try Pardes.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); + try dump.dumpState(p); + const restored = try dump.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); defer restored.deinit(); try std.testing.expect(!restored.settings.tree_context_tag_style); } @@ -858,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(pane.appendTag(" Save Keep Del")); pane.tag_init = true; - try p.dumpState(); - const restored = try Pardes.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); + try dump.dumpState(p); + const restored = try dump.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); defer restored.deinit(); const saved = restored.panes[0].?; try std.testing.expect(saved.file.?.tree_context); @@ -1397,7 +1397,7 @@ test "image dump restores source bytes renderer choices and exact custom tail" { pane.image.?.ascii = false; try std.testing.expect(pane.appendTag(" Keep Del")); pane.tag_init = true; - try p.dumpState(); + try dump.dumpState(p); var first_dump = try dump.readZon(gpa, p.dump_out.?, "image-first-dump"); defer first_dump.deinit(); @@ -1407,7 +1407,7 @@ test "image dump restores source bytes renderer choices and exact custom tail" { try std.testing.expect(!first.panes[0].image.?.ascii); try std.testing.expectEqualStrings(" Keep Del", first.panes[0].tag_tail.?); - const restored = try Pardes.initFromDump(gpa, .{ .tty_only = true }, p.dump_out.?); + const restored = try dump.initFromDump(gpa, .{ .tty_only = true }, p.dump_out.?); defer restored.deinit(); const restored_pane = restored.panes[0].?; try std.testing.expect(restored_pane.image.?.glyph_art); @@ -1417,7 +1417,7 @@ test "image dump restores source bytes renderer choices and exact custom tail" { try std.testing.expectEqualStrings(" Keep Del", restored_pane.tagSlice()); try std.testing.expectEqualSlices(u8, source, restored_pane.image.?.raw); - try restored.dumpState(); + try dump.dumpState(restored); var parsed = try dump.readZon(gpa, restored.dump_out.?, "image-redump"); defer parsed.deinit(); const redump = parsed.value; @@ -1767,13 +1767,13 @@ test "owned cwd restore either copies the directory or preserves the old core" { const p = try Pardes.init(allocator.allocator(), .{ .tty_only = true }); defer p.deinit(); p.setCwd(0, "/retained/terminal/directory"); - try p.dumpState(); + try dump.dumpState(p); const original = p.panes[0].?; var completed = false; for (0..256) |failure| { allocator.has_induced_failure = false; allocator.fail_index = allocator.alloc_index + failure; - const replacement = p.restore(p.dump_out.?) catch { + const replacement = dump.restore(p, p.dump_out.?) catch { try std.testing.expect(allocator.has_induced_failure); try std.testing.expectEqual(original, p.panes[0].?); try std.testing.expectEqualStrings("/retained/terminal/directory", original.cwdSlice()); @@ -2305,9 +2305,9 @@ test "startup config overrides restored styling before initFromDump returns" { const source = try Pardes.init(std.testing.allocator, .{ .startup_config = "Theme dark\n" }); defer source.deinit(); try std.testing.expectEqualStrings("dark", source.theme().name); - try source.dumpState(); + try dump.dumpState(source); - const restored = try Pardes.initFromDump( + const restored = try dump.initFromDump( std.testing.allocator, .{ .startup_config = "Theme acme\n" }, source.dump_out.?, @@ -2324,9 +2324,9 @@ test "restored sessions animate layout changes after bootstrap" { if (platform == .web) return; const source = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 16 }); defer source.deinit(); - try source.dumpState(); + try dump.dumpState(source); - const restored = try Pardes.initFromDump( + const restored = try dump.initFromDump( std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 16, .startup_config = "PanelSlide\n" }, source.dump_out.?, @@ -2355,9 +2355,9 @@ test "restored terminals keep monotonic nonzero pane identities" { // Filter is a fresh presentation default, not emulator/dump state. Even a // pane toggled off in the source session comes back with the default on. source.panes[1].?.tty_filter = false; - try source.dumpState(); + try dump.dumpState(source); - const restored = try Pardes.initFromDump(gpa, .{}, source.dump_out.?); + const restored = try dump.initFromDump(gpa, .{}, source.dump_out.?); defer restored.deinit(); var ids: [MAX_PANES]usize = undefined; @@ -2721,14 +2721,14 @@ test "editable workspace and column tags replace selections and persist" { p.update(.{ .paste = "Grep " }); try std.testing.expect(std.mem.startsWith(u8, p.columnTag(0), "Grep New")); try std.testing.expectEqualStrings("untouched\n", p.panes[0].?.file.?.content); - try p.dumpState(); - const restored = try p.restore(p.dump_out.?); + 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.columnTag(0), restored.columnTag(0)); try std.testing.expect(p.col_tags[0].set("")); - try p.dumpState(); - const empty = try p.restore(p.dump_out.?); + try dump.dumpState(p); + const empty = try dump.restore(p, p.dump_out.?); defer empty.deinit(); try std.testing.expectEqualStrings("", empty.columnTag(0)); } @@ -5819,223 +5819,7 @@ pub const Pardes = struct { // ---- dump / load (acme-style: `pardes -l state.zon` restores a session) ---- - pub fn dumpState(p: *Pardes) !void { - const arena = p.scratch.allocator(); - var slot_to_pane: [MAX_PANES]?usize = @splat(null); - var dump_panes: [MAX_PANES]dump.Pane = undefined; - var panes_len: usize = 0; - for (p.panes, 0..) |slot, id| { - const pane = slot orelse continue; - slot_to_pane[id] = panes_len; - const tag = try p.tagText(arena, pane); - const body = try body_layer.bodyText(p, arena, pane); - const scroll: usize = @intCast(@max(0, pane.scroll())); - var dp: dump.Pane = if (pane.file) |*f| try panes.File.dumpPane( - arena, - pane, - f, - tag, - body, - scroll, - if (f.output) |o| panes.Output.word(o.from) else "", - if (f.output) |*o| o.arg() else "", - ) else if (pane.hasPdf()) blk: { - if (comptime !pdf_enabled) unreachable; - const pv = &pane.pdf.?; - break :blk try panes.Image.dumpPane(p, arena, pane, tag, body, pv.page, pv.path, &.{}); - } else if (pane.image) |iv| - try panes.Image.dumpPane(p, arena, pane, tag, body, scroll, iv.path, iv.raw) - else - try panes.Terminal.dumpPane(pane, arena, tag, body, scroll); - dp.tag_tail = if (pane.tag_init) pane.tagSlice() else null; - dump_panes[panes_len] = dp; - panes_len += 1; - } - - var columns: [MAX_COLS]dump.Column = undefined; - var columns_len: usize = 0; - var column_ids: [MAX_COLS][MAX_PANES]usize = undefined; - for (0..p.ncol) |c| { - var ids_len: usize = 0; - for (0..p.col_n[c]) |k| if (slot_to_pane[p.col_panes[c][k]]) |compact| { - column_ids[c][ids_len] = compact; - ids_len += 1; - }; - if (ids_len > 0) { - columns[columns_len] = .{ - .tag = if (p.col_tags[c].custom) p.columnTag(c) else null, - .weight = @as(f32, @floatFromInt(p.col_weight[c])) / @as(f32, @floatFromInt(column_weight_unit)), - .panes = column_ids[c][0..ids_len], - }; - columns_len += 1; - } - } - - var mounts: [filesystem.max_mounts]dump.Mount = undefined; - for (p.fs.mounts.items, 0..) |mount, i| mounts[i] = .{ .name = mount.name, .dial = mount.dial }; - const state: dump.State = .{ - .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, - .theme = p.theme().name, - .locations_config = p.locations_config, - .tree_context_tag_style = p.settings.tree_context_tag_style, - .columns = columns[0..columns_len], - .panes = dump_panes[0..panes_len], - .mounts = mounts[0..p.fs.mounts.items.len], - }; - try dump.validate(state); - var out: std.Io.Writer.Allocating = .init(p.gpa); - errdefer out.deinit(); - try std.zon.stringify.serialize(state, .{ .whitespace = true }, &out.writer); - if (p.dump_out) |d| p.gpa.free(d); - p.dump_out = try out.toOwnedSlice(); - p.emit(.write_dump); - } - - pub fn restore(p: *Pardes, zon_bytes: []const u8) !*Pardes { - var opts = p.opts; - opts.cols = p.screen_w; - opts.rows = p.screen_h; - return initDump(p.gpa, opts, zon_bytes, p); - } - - pub fn initFromDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8) !*Pardes { - return initDump(gpa, opts, zon_bytes, null); - } - - fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previous: ?*const Pardes) !*Pardes { - const image_gpa = opts.image_allocator orelse gpa; - const pdf_gpa = opts.pdf_allocator orelse gpa; - const tree_sitter_gpa = opts.tree_sitter_allocator orelse gpa; - const p = try gpa.create(Pardes); - p.* = .{ - .gpa = gpa, - .image_gpa = image_gpa, - .pdf_gpa = pdf_gpa, - .tree_sitter_gpa = tree_sitter_gpa, - .opts = opts, - .fs = .{}, - .screen_w = opts.cols, - .screen_h = opts.rows, - .scratch = .init(gpa), - .frame_arena = .init(opts.frame_allocator orelse gpa), - .fallback = .{ .gpa = gpa }, - }; - errdefer p.deinit(); - if (previous) |old| { - p.next_serial = old.next_serial; - p.lsp_seq = old.lsp_seq; - p.pipe_seq = old.pipe_seq; - p.cell_pixels = old.cell_pixels; - p.row_metrics = old.row_metrics; - p.native_images = old.native_images; - } - for (opts.mounts) |mount| try p.fs.mount(gpa, mount.name, mount.dial); - p.opts.mounts = &.{}; - var parsed = try dump.readZon(gpa, zon_bytes, "load"); - defer parsed.deinit(); - const st = parsed.value; - p.locations_config = st.locations_config; - p.settings.tree_context_tag_style = st.tree_context_tag_style; - for (st.mounts) |mount| { - var already_mounted = false; - for (p.fs.mounts.items) |existing| { - if (!std.mem.eql(u8, mount.name, existing.name)) continue; - if (!std.mem.eql(u8, mount.dial, existing.dial)) return error.MountConflict; - already_mounted = true; - break; - } - if (!already_mounted) try p.fs.mount(gpa, mount.name, mount.dial); - } - - for (themes, 0..) |t, i| { - if (std.mem.eql(u8, t.name, st.theme)) p.settings.theme = @intCast(i); - } - for (st.panes, 0..) |src, i| { - if (i >= MAX_PANES) break; - const pane: *Pane = switch (src.kind) { - .terminal => terminal: { - const t = src.terminal.?; - // A host that runs shells gets them back: the old history - // above a new shell in the directory it was in. The web - // shell and an isolated build only ever replay it. - const live = comptime (terminal_panes and platform != .web and !isolated); - const revive = live and t.cwd.len <= effect_path_cap; - const restored = try 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 (revive) p.emit(.{ .spawn = .{ .pane = @intCast(i), .cwd = .from(t.cwd) } }); - break :terminal restored; - }, - .file => try panes.File.restore(p, i, src), - .image => restore_image: { - const im = src.image.?; - if (panes.Pdf.isPath(im.path)) { - var raw: []u8 = if (im.bytes_b64.len > 0) - try dump.decodeBytes(gpa, im.bytes_b64) - else - &.{}; - errdefer if (raw.len > 0) gpa.free(raw); - if (comptime pdf_enabled) { - if (panes.Pdf.openPane(p, i, im.path, src.scroll + 1) catch null) |restored| { - if (raw.len > 0) gpa.free(raw); - raw = &.{}; - restored.cols = @max(1, src.cols); - restored.rows = @max(1, src.rows); - break :restore_image restored; - } - } - // If the source path is unavailable, retain its bytes - // as an ordinary file rather than dropping the pane. - const path = try gpa.dupe(u8, im.path); - errdefer gpa.free(path); - const content = if (raw.len > 0) raw else try gpa.dupe(u8, ""); - raw = &.{}; - errdefer if (content.len > 0) gpa.free(content); - const history = try panes.File.History.create(gpa); - errdefer gpa.destroy(history); - const restored = try p.newDocPane(i); - restored.file = .{ .path = path, .content = content, .history = history }; - restored.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 } }); - break :restore_image restored; - } - break :restore_image try panes.Image.restore(p, i, src); - }, - }; - p.restoreDumpTail(pane, src); - pane.vweight = src.vweight; - pane.collapsed = src.collapsed; - } - p.ncol = @min(st.columns.len, MAX_COLS); - p.col_serial = @splat(0); - if (st.topbar_custom) |bar| _ = p.global_tag.set(bar); - for (st.columns[0..p.ncol], 0..) |col, c| { - if (col.tag) |bar| _ = p.col_tags[c].set(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)))); - p.col_n[c] = @min(col.panes.len, MAX_PANES); - for (col.panes[0..p.col_n[c]], 0..) |pid, k| p.col_panes[c][k] = pid; - } - p.active = @min(st.active, MAX_PANES - 1); - p.sync(); - exec.applyStartupConfig(p); - colors.finishThemeInitialization(p); - p.sync(); - p.presentation.enabled = true; - _ = p.takeHaptic(); // see init: a restored session is not a gesture - try p.fs.log.buf.ensureTotalCapacityPrecise(p.gpa, p.fs.log.cap); - ctlfs.events.announce(p); - return p; - } - - fn restoreDumpTail(p: *Pardes, pane: *Pane, src: dump.Pane) void { + 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; diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 89a476f2..fe968650 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -5,6 +5,7 @@ const posix = std.posix; const libc = std.c; const vaxis = @import("vaxis"); const pardes = @import("../pardes.zig"); +const dump = @import("../dump.zig"); const tracy = @import("../tracy.zig"); const look = @import("../look.zig"); const message = pardes.Messages.Message; @@ -700,7 +701,7 @@ fn localSession( var core = if (options.load_path) |lp| blk: { const bytes = try filesystem.readFile(gpa, lp); defer gpa.free(bytes); - break :blk try pardes.Pardes.initFromDump(allocs.pardes, options, bytes); + break :blk try pardes.dump.initFromDump(allocs.pardes, options, bytes); } else try pardes.Pardes.init(allocs.pardes, options); defer core.deinit(); @@ -802,7 +803,7 @@ fn localSession( break :blk; }; defer gpa.free(bytes); - const nc = core.restore(bytes) catch |err| { + const nc = dump.restore(core, bytes) catch |err| { core.reportError(core.active, "Restore", err); break :blk; }; diff --git a/src/web.zig b/src/web.zig index 4c2a9db8..b77d07a6 100644 --- a/src/web.zig +++ b/src/web.zig @@ -117,7 +117,7 @@ const State = struct { pardes.syntax.start(allocs.tree_sitter); errdefer pardes.syntax.stop(); - const core = try pardes.Pardes.initFromDump(allocs.pardes, .{ + const core = try pardes.dump.initFromDump(allocs.pardes, .{ .cols = cols, .rows = rows, .frame_allocator = allocs.frame, diff --git a/test/fs_namespace.zig b/test/fs_namespace.zig index 470615c9..ffdc084c 100644 --- a/test/fs_namespace.zig +++ b/test/fs_namespace.zig @@ -40,8 +40,8 @@ test "mounts survive dumps without borrowing inputs or silently overriding a sav file.file.?.revision = 3; gpa.free(file.file.?.path); file.file.?.path = try gpa.dupe(u8, "/n/peer/os/file.txt"); - try p.dumpState(); - const restored = try pardes.Pardes.initFromDump(gpa, .{}, p.dump_out.?); + try pardes.dump.dumpState(p); + const restored = try pardes.dump.initFromDump(gpa, .{}, p.dump_out.?); defer restored.deinit(); try std.testing.expectEqual(@as(usize, 1), restored.fs.mounts.items.len); try std.testing.expectEqualStrings("peer", restored.fs.mounts.items[0].name); @@ -50,13 +50,13 @@ test "mounts survive dumps without borrowing inputs or silently overriding a sav try std.testing.expectEqualStrings("saved remote body\n", restored.panes[0].?.file.?.content); try std.testing.expect(restored.panes[0].?.file.?.revision != restored.panes[0].?.file.?.saved_revision); try std.testing.expectError(error.MountInUse, filesystem.unmount(restored, "peer")); - const same = try pardes.Pardes.initFromDump(gpa, .{ .mounts = &.{.{ .name = "peer", .dial = "/tmp/peer.sock" }} }, p.dump_out.?); + const same = try pardes.dump.initFromDump(gpa, .{ .mounts = &.{.{ .name = "peer", .dial = "/tmp/peer.sock" }} }, p.dump_out.?); defer same.deinit(); try std.testing.expectEqual(@as(usize, 1), same.fs.mounts.items.len); - try std.testing.expectError(error.MountConflict, pardes.Pardes.initFromDump(gpa, .{ + try std.testing.expectError(error.MountConflict, pardes.dump.initFromDump(gpa, .{ .mounts = &.{.{ .name = "peer", .dial = "/tmp/different.sock" }}, }, p.dump_out.?)); - const added = try pardes.Pardes.initFromDump(gpa, .{ .mounts = &.{.{ .name = "other", .dial = "/tmp/other.sock" }} }, p.dump_out.?); + const added = try pardes.dump.initFromDump(gpa, .{ .mounts = &.{.{ .name = "other", .dial = "/tmp/other.sock" }} }, p.dump_out.?); defer added.deinit(); try std.testing.expectEqual(@as(usize, 2), added.fs.mounts.items.len); } @@ -69,8 +69,8 @@ test "removed startup mounts are not resurrected by dump restore" { }); defer p.deinit(); try filesystem.unmount(p, "peer"); - try p.dumpState(); - const restored = try pardes.Pardes.initFromDump(gpa, p.opts, p.dump_out.?); + try pardes.dump.dumpState(p); + const restored = try pardes.dump.initFromDump(gpa, p.opts, p.dump_out.?); defer restored.deinit(); try std.testing.expectEqual(@as(usize, 0), restored.fs.mounts.items.len); } @@ -87,8 +87,8 @@ test "transactional restore preserves host capabilities and advances pane identi p.fs.socket_path = "/tmp/session.sock"; p.fs.tcp_address = .{ .ip4 = .loopback(5640) }; p.fs.quic_address = .{ .ip6 = .loopback(5641) }; - try p.dumpState(); - const restored = try p.restore(p.dump_out.?); + try pardes.dump.dumpState(p); + const restored = try pardes.dump.restore(p, p.dump_out.?); defer restored.deinit(); try std.testing.expectEqual(@as(u32, 41), restored.lsp_seq); try std.testing.expectEqual(@as(u32, 73), restored.pipe_seq); @@ -100,7 +100,8 @@ test "transactional restore preserves host capabilities and advances pane identi try std.testing.expectEqual(p.screen_h, restored.screen_h); try std.testing.expect(p.panes[0] == pane); try std.testing.expectEqualStrings("before\n", pane.file.?.content); - try std.testing.expectError(error.BadDumpMagic, p.restore( + try std.testing.expectError(error.BadDumpMagic, pardes.dump.restore( + p, ".{ .magic = \"wrong\", .screen = .{.cols = 80, .rows = 24} }", )); try std.testing.expect(p.panes[0] == pane); diff --git a/test/output.zig b/test/output.zig index b4c018db..7c5f7f9b 100644 --- a/test/output.zig +++ b/test/output.zig @@ -438,9 +438,9 @@ test "Mini dump preserves its exact virtual snapshot and body writes detach colo const id = p.active; const before = p.panes[id].?.file.?; try std.testing.expect(before.mini != null); - try p.dumpState(); + try pardes.dump.dumpState(p); panes.File.setContent(p, &source.file.?, try p.gpa.dupe(u8, "changed\n")); - const restored = try Pardes.initFromDump(std.testing.allocator, .{ .tty_only = true }, p.dump_out.?); + const restored = try pardes.dump.initFromDump(std.testing.allocator, .{ .tty_only = true }, p.dump_out.?); defer restored.deinit(); const mini = restored.panes[restored.active].?; try std.testing.expectEqualStrings(before.content, mini.file.?.content); @@ -793,8 +793,8 @@ test "n/N skips formatted context and selects comment match locations" { try std.testing.expectEqualStrings(line[0..file.location_rows[row].location_end], selectedOutputText(result) orelse ""); try std.testing.expectEqual(available, p.freeSlot()); } - try p.dumpState(); - const restored = try Pardes.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); + try pardes.dump.dumpState(p); + const restored = try pardes.dump.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); defer restored.deinit(); pardes.look.armLookWalk(restored, id); const restored_result = restored.panes[id].?; @@ -1570,8 +1570,8 @@ test "stacked search and LSP results retain source tint navigation and dump owne const line = modal.lineSlice(file.content, matches[step.match]); try std.testing.expectEqualStrings(line[0..row.location_end], selectedOutputText(pane) orelse ""); } - try p.dumpState(); - const restored = try Pardes.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); + try pardes.dump.dumpState(p); + const restored = try pardes.dump.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); defer restored.deinit(); const restored_file = &restored.panes[id].?.file.?; try std.testing.expectEqualStrings(file.content, restored_file.content); diff --git a/test/panes.zig b/test/panes.zig index f99f9d56..1c861070 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -2039,7 +2039,7 @@ test "file history survives PDF fallback restoration and allocation failures" { var succeeded = false; for (0..256) |failure| { var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = failure }); - if (Pardes.initFromDump(failing.allocator(), .{ .tty_only = true }, saved)) |p| { + if (pardes.dump.initFromDump(failing.allocator(), .{ .tty_only = true }, saved)) |p| { defer p.deinit(); const pane = p.panes[0].?; try std.testing.expect(pane.file != null); @@ -2416,8 +2416,8 @@ const OutputTests = struct { neighbor_colored = neighbor_colored or style != 0; try std.testing.expect(neighbor_colored); - try p.dumpState(); - const restored = try Pardes.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); + try pardes.dump.dumpState(p); + const restored = try pardes.dump.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); defer restored.deinit(); const restored_source = restored.panes[0].?; const restored_id = pane.search_pane.?; @@ -2520,8 +2520,8 @@ const OutputTests = struct { try std.testing.expectEqual(.match, file.location_rows[next].kind); const wrapped = panes.Output.nextResult(file.content, file.location_rows, path, .{ .line = 99 }); try std.testing.expectEqual(@as(usize, 2), file.location_rows[wrapped].at.line); - try p.dumpState(); - const restored = try Pardes.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); + try pardes.dump.dumpState(p); + const restored = try pardes.dump.initFromDump(p.gpa, .{ .tty_only = true }, p.dump_out.?); defer restored.deinit(); const restored_file = &restored.panes[pane.search_pane.?].?.file.?; try std.testing.expectEqualStrings(file.content, restored_file.content); diff --git a/test/pdf.zig b/test/pdf.zig index dde58df8..8e87dfb1 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -301,7 +301,7 @@ test "PDF dump fallback remains a byte-preserving file" { defer out.deinit(); try std.zon.stringify.serialize(state, .{ .whitespace = true }, &out.writer); - const restored = try Pardes.initFromDump(gpa, .{ .tty_only = true }, out.written()); + const restored = try pardes.dump.initFromDump(gpa, .{ .tty_only = true }, out.written()); defer restored.deinit(); const pane = restored.panes[0].?; try std.testing.expect(pane.file != null); @@ -921,8 +921,8 @@ test "MuPDF pane renders, navigates, searches, and round-trips its page" { @memcpy(pane.tag_tail[0..custom_tail.len], custom_tail); pane.tag_tail_len = custom_tail.len; pane.tag_init = true; - try p.dumpState(); - const restored = try Pardes.initFromDump(gpa, .{}, p.dump_out.?); + try pardes.dump.dumpState(p); + const restored = try pardes.dump.initFromDump(gpa, .{}, p.dump_out.?); defer restored.deinit(); try std.testing.expect(hasPdf(restored.panes[0].?)); try std.testing.expectEqual(pane.pdf.?.page, restored.panes[0].?.pdf.?.page); -- cgit v1.3 From 71a9f04342493325c10b1b9bc122a88d41143782 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sun, 27 Sep 2026 22:46:26 -0300 Subject: Give the pipe its own fields in Pipe Not a pure move: state moves. Pardes's `pipe_seq` and `pipe_wait` become Pipe.zig's own fields `seq` and `wait`, and Pardes embeds one as `pipe: Pipe = .{}`. pipeRequest reads only the request in flight, so it now takes `pipe: *const Pipe` and the four shells call `core.pipe.pipeRequest(id)` (their Pipe imports go away again); the other pipe functions still need the panes and keep `p: *Pardes`, writing `p.pipe.seq/wait`. Field reads in dump.zig, the shells' tests and two test files follow (`core.pipe_wait` becomes `core.pipe.wait`). No behaviour change. Co-Authored-By: Claude Opus 5.5 --- src/Pipe.zig | 32 +++++++++++++++++++------------- src/detached/client.zig | 2 +- src/detached/server.zig | 7 +++---- src/dump.zig | 2 +- src/gui/gui.zig | 7 +++---- src/macos.zig | 11 +++++------ src/pardes.zig | 5 ++--- src/tty/tty.zig | 7 +++---- test/fs_namespace.zig | 4 ++-- test/panes.zig | 2 +- 10 files changed, 40 insertions(+), 39 deletions(-) (limited to 'src/dump.zig') diff --git a/src/Pipe.zig b/src/Pipe.zig index 0fde654a..c01098ff 100644 --- a/src/Pipe.zig +++ b/src/Pipe.zig @@ -11,6 +11,12 @@ const edit = @import("edit.zig"); const Pane = panes.Pane; const Key = pardes.Key; const Pardes = pardes.Pardes; +const Pipe = @This(); + +/// Bumped for every request, so a late answer to an older one is ignored. +seq: u32 = 0, +/// The request in flight, and what it needs to apply its answer. +wait: ?PendingPipe = null, fn nextPipeEffect(p: *Pardes) ?u32 { while (p.nextEffect()) |effect| switch (effect) { @@ -112,10 +118,10 @@ pub fn submitPipe(p: *Pardes, id: usize) void { return; }; - p.pipe_seq +%= 1; - if (p.pipe_wait) |*old| old.deinit(p.gpa); - p.pipe_wait = .{ - .id = p.pipe_seq, + p.pipe.seq +%= 1; + if (p.pipe.wait) |*old| old.deinit(p.gpa); + p.pipe.wait = .{ + .id = p.pipe.seq, .pane = id, .serial = pane.serial, .revision = f.revision, @@ -128,13 +134,13 @@ pub fn submitPipe(p: *Pardes, id: usize) void { .how = prompt.how, .nranges = @intCast(got.n), }; - p.emit(.{ .pipe = .{ .id = p.pipe_seq } }); + p.emit(.{ .pipe = .{ .id = p.pipe.seq } }); } /// Frontends call this while draining a .pipe effect, then immediately /// copy the borrowed view into a worker-owned selection_pipe.Job. -pub fn pipeRequest(p: *const Pardes, id: u32) ?selection_pipe.Request { - if (p.pipe_wait) |*wait| { +pub fn pipeRequest(pipe: *const Pipe, id: u32) ?selection_pipe.Request { + if (pipe.wait) |*wait| { if (wait.id == id) return wait.request(); } return null; @@ -215,9 +221,9 @@ pub fn pipeResponse( ) void { // A SUPERSEDED OR UNKNOWN id is the one silence worth keeping: it is // the answer to a question nobody is still asking. - if (p.pipe_wait == null or p.pipe_wait.?.id != id) return; - var wait = p.pipe_wait.?; - p.pipe_wait = null; + if (p.pipe.wait == null or p.pipe.wait.?.id != id) return; + var wait = p.pipe.wait.?; + p.pipe.wait = null; defer wait.deinit(p.gpa); if (!success or outputs.len != wait.inputs.len) return pipeFailed(p, &wait, failure); @@ -296,7 +302,7 @@ test "selection pipe prompt submits exact request and Escape cancels" { p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expect(!pane.tag_edit and pane.prompt != .pipe); const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; - const request = pipeRequest(p, id) orelse return error.MissingPipeRequest; + const request = p.pipe.pipeRequest(id) orelse return error.MissingPipeRequest; try std.testing.expectEqualStrings("tr a-z A-Z", request.command); try std.testing.expectEqualStrings("/", request.cwd); try std.testing.expectEqual(@as(usize, 1), request.inputs.len); @@ -327,7 +333,7 @@ test "selection pipe replaces all ranges atomically and undo restores them" { p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); p.update(.{ .key = .{ .cp = Key.enter } }); const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; - const request = pipeRequest(p, id) orelse return error.MissingPipeRequest; + const request = p.pipe.pipeRequest(id) orelse return error.MissingPipeRequest; try std.testing.expectEqual(@as(usize, 2), request.inputs.len); try std.testing.expectEqualSlices(u8, "aa", request.inputs[0].bytes); try std.testing.expectEqualSlices(u8, "cc", request.inputs[1].bytes); @@ -399,7 +405,7 @@ test "a command with no stdin runs once and every cursor gets that one answer" { for ("date") |c| p.update(.{ .key = .{ .cp = c, .text = &.{c} } }); p.update(.{ .key = .{ .cp = Key.enter } }); const id = nextPipeEffect(p) orelse return error.MissingPipeEffect; - const request = pipeRequest(p, id) orelse return error.MissingPipeRequest; + const request = p.pipe.pipeRequest(id) orelse return error.MissingPipeRequest; try std.testing.expectEqual(@as(usize, 1), request.inputs.len); try std.testing.expectEqualSlices(u8, "", request.inputs[0].bytes); diff --git a/src/detached/client.zig b/src/detached/client.zig index 7cee790a..6476d521 100644 --- a/src/detached/client.zig +++ b/src/detached/client.zig @@ -884,7 +884,7 @@ test "detached selection pipe runs off the loop and returns through the attached while (try client.next()) |_| {} if (std.mem.eql(u8, pane.file.?.content, "ONE\ntwo\n")) break; } else return error.PipeDidNotComplete; - try testing.expect(h.core.pipe_wait == null); + try testing.expect(h.core.pipe.wait == null); try testing.expectEqual(@as(usize, 0), h.session.pipe_tasks.len); try h.pumpUntilShowsCore(&client); } diff --git a/src/detached/server.zig b/src/detached/server.zig index 9b23f8d6..2b9c9247 100644 --- a/src/detached/server.zig +++ b/src/detached/server.zig @@ -9,7 +9,6 @@ const wire = @import("wire.zig"); const host_io = @import("../host_io.zig"); const selection_pipe = @import("../selection_pipe.zig"); -const Pipe = @import("../Pipe.zig"); const file_watch = @import("../file_watch.zig"); @@ -412,7 +411,7 @@ pub const Session = struct { s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); return; } - const request = Pipe.pipeRequest(s.core, id) orelse return; + const request = s.core.pipe.pipeRequest(id) orelse return; const job = selection_pipe.Job.copy(s.worker_gpa, request) catch |err| { s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); return s.core.reportError(s.core.active, "pipe", err); @@ -1257,9 +1256,9 @@ test "detached worker setup failure completes requests without changing document 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 } }); - try std.testing.expect(s.core.pipe_wait != null); + try std.testing.expect(s.core.pipe.wait != null); while (s.core.nextEffect()) |effect| s.core.perform(effect); - try std.testing.expect(s.core.pipe_wait == null); + try std.testing.expect(s.core.pipe.wait == null); try std.testing.expectEqual(@as(usize, 0), s.pipe_tasks.len); try std.testing.expectEqualStrings("one\n", pane.file.?.content); try std.testing.expect(failing.has_induced_failure); diff --git a/src/dump.zig b/src/dump.zig index 0ce2d10e..46cf6001 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -701,7 +701,7 @@ fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previo if (previous) |old| { p.next_serial = old.next_serial; p.lsp_seq = old.lsp_seq; - p.pipe_seq = old.pipe_seq; + p.pipe.seq = old.pipe.seq; p.cell_pixels = old.cell_pixels; p.row_metrics = old.row_metrics; p.native_images = old.native_images; diff --git a/src/gui/gui.zig b/src/gui/gui.zig index ef94d5b3..a11b22c7 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -16,7 +16,6 @@ const crt = @import("crt.zig"); const pet = @import("pet.zig"); const fonts = @import("../fonts.zig"); // the Font builtin's half of the seam const selection_pipe = @import("../selection_pipe.zig"); -const Pipe = @import("../Pipe.zig"); const c_heap = @import("c_heap"); const ninep_io = @import("../9p_io.zig"); @@ -1704,7 +1703,7 @@ fn spawnPipe( core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); return; } - const view = Pipe.pipeRequest(core, id) orelse return; + const view = core.pipe.pipeRequest(id) orelse return; const job = selection_pipe.Job.copy(gpa, view) catch |err| { core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); return core.reportError(core.active, "pipe", err); @@ -1768,9 +1767,9 @@ test "GUI worker setup failures finish matching LSP and pipe requests" { core.update(.{ .key = .{ .cp = '|' } }); core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); core.update(.{ .key = .{ .cp = pardes.Key.enter } }); - const pipe_id = core.pipe_wait.?.id; + const pipe_id = core.pipe.wait.?.id; spawnPipe(core, failing_io, failing.allocator(), &queue, &tasks, pipe_id); - try std.testing.expect(core.pipe_wait == null); + 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.expectEqual(@as(usize, 0), tasks.len); diff --git a/src/macos.zig b/src/macos.zig index dc5b79d0..ccbb5dd5 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -18,7 +18,6 @@ const host_io = @import("host_io.zig"); const fonts = @import("fonts.zig"); // the shared fallback preference order const tracy = @import("tracy.zig"); // no-op unless -Dtracy names a checkout const selection_pipe = @import("selection_pipe.zig"); // Job, runJob and Tasks -const Pipe = @import("Pipe.zig"); const crash = @import("crash.zig"); pub const panic = std.debug.FullPanic(struct { @@ -344,9 +343,9 @@ test "mac worker setup failures finish matching LSP and pipe requests" { core.update(.{ .key = .{ .cp = '|' } }); core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); core.update(.{ .key = .{ .cp = pardes.Key.enter } }); - const pipe_id = core.pipe_wait.?.id; + const pipe_id = core.pipe.wait.?.id; pipeRequest(&st, pipe_id); - try std.testing.expect(core.pipe_wait == null); + try std.testing.expect(core.pipe.wait == null); try std.testing.expectEqualStrings("abc", pane.file.?.content); try std.testing.expect(st.lsp_task == null); try std.testing.expectEqual(@as(usize, 0), st.pipe_tasks.len); @@ -1471,7 +1470,7 @@ test "mac Restore keeps host state and rejects callbacks from the old core" { 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 } }); - const pipe_id = st.core.pipe_wait.?.id; + const pipe_id = st.core.pipe.wait.?.id; try std.testing.expect(st.pipe_tasks.add(.{ .id = pipe_id, .future = .{ .any_future = null, .result = {} } })); const output = try gpa.dupe(u8, "FRESH"); const outputs = gpa.dupe([]u8, &.{output}) catch |err| { @@ -1480,7 +1479,7 @@ test "mac Restore keeps host state and rejects callbacks from the old core" { }; st.inbox.push(gpa, std.testing.io, .{ .pipe = .{ .id = pipe_id, .success = true, .outputs = outputs } }); try std.testing.expect(drainInbox(&st)); - try std.testing.expect(st.core.pipe_wait == null); + try std.testing.expect(st.core.pipe.wait == null); try std.testing.expectEqual(@as(usize, 0), st.pipe_tasks.len); try std.testing.expectEqualStrings("FRESH body\n", pane.file.?.content); } @@ -2352,7 +2351,7 @@ fn pipeRequest(ctx: ?*anyopaque, id: u32) void { st.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); return; } - const view = Pipe.pipeRequest(st.core, id) orelse return; + const view = st.core.pipe.pipeRequest(id) orelse return; const job = selection_pipe.Job.copy(st.gpa, view) catch |err| { st.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); return st.core.reportError(st.core.active, "pipe", err); diff --git a/src/pardes.zig b/src/pardes.zig index 00439a36..97860cfe 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -3746,8 +3746,7 @@ pub const Pardes = struct { col: i32 = 0, } = null, - pipe_seq: u32 = 0, - pipe_wait: ?Pipe.PendingPipe = null, + pipe: Pipe = .{}, fs: filesystem.Namespace = .{}, boot: Boot = .shell, @@ -3958,7 +3957,7 @@ pub const Pardes = struct { if (p.last_dump) |d| gpa.free(d); if (p.custom_theme) |theme_value| std.zon.parse.free(gpa, theme_value); if (p.chord_arg) |a| gpa.free(a); - if (p.pipe_wait) |*wait| wait.deinit(gpa); + if (p.pipe.wait) |*wait| wait.deinit(gpa); p.locations_cache.deinit(p.tree_sitter_gpa); p.fs.deinit(gpa); p.shell_rows.reset(gpa); diff --git a/src/tty/tty.zig b/src/tty/tty.zig index 24403ba8..e3378f5b 100644 --- a/src/tty/tty.zig +++ b/src/tty/tty.zig @@ -11,7 +11,6 @@ const look = @import("../look.zig"); const message = pardes.Messages.Message; const file_watch = @import("../file_watch.zig"); const selection_pipe = @import("../selection_pipe.zig"); -const Pipe = @import("../Pipe.zig"); const ninep_io = @import("../9p_io.zig"); const panel_compositor = @import("panel_compositor.zig"); const detached_client = @import("../detached/client.zig"); @@ -1326,7 +1325,7 @@ const Shell = struct { s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); return; } - const view = Pipe.pipeRequest(s.core, id) orelse return; + const view = s.core.pipe.pipeRequest(id) orelse return; const job = selection_pipe.Job.copy(s.gpa, view) catch |err| { s.core.update(.{ .pipe_resp = .{ .id = id, .success = false, .outputs = &.{} } }); return s.core.reportError(s.core.active, "pipe", err); @@ -1424,9 +1423,9 @@ test "TTY worker setup failures finish matching LSP and pipe requests" { core.update(.{ .key = .{ .cp = '|' } }); core.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); core.update(.{ .key = .{ .cp = pardes.Key.enter } }); - const pipe_id = core.pipe_wait.?.id; + const pipe_id = core.pipe.wait.?.id; Shell.pipe(&shell, pipe_id); - try std.testing.expect(core.pipe_wait == null); + try std.testing.expect(core.pipe.wait == null); try std.testing.expectEqualStrings("abc", pane.file.?.content); try std.testing.expect(shell.lsp_task == null); try std.testing.expectEqual(@as(usize, 0), shell.pipe_tasks.len); diff --git a/test/fs_namespace.zig b/test/fs_namespace.zig index ffdc084c..822577d8 100644 --- a/test/fs_namespace.zig +++ b/test/fs_namespace.zig @@ -81,7 +81,7 @@ test "transactional restore preserves host capabilities and advances pane identi defer p.deinit(); const pane = try p.setTestFile("before\n"); p.lsp_seq = 41; - p.pipe_seq = 73; + p.pipe.seq = 73; if (@hasField(pardes.CellPixels, "w")) p.cell_pixels = .{ .w = 9, .h = 18 }; p.native_images = true; p.fs.socket_path = "/tmp/session.sock"; @@ -91,7 +91,7 @@ test "transactional restore preserves host capabilities and advances pane identi const restored = try pardes.dump.restore(p, p.dump_out.?); defer restored.deinit(); try std.testing.expectEqual(@as(u32, 41), restored.lsp_seq); - try std.testing.expectEqual(@as(u32, 73), restored.pipe_seq); + try std.testing.expectEqual(@as(u32, 73), restored.pipe.seq); try std.testing.expectEqual(p.cell_pixels, restored.cell_pixels); try std.testing.expect(restored.native_images); try std.testing.expect(restored.panes[0].?.serial > p.next_serial); diff --git a/test/panes.zig b/test/panes.zig index 1c861070..60dabb8a 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -1749,7 +1749,7 @@ test "tag prompt owns the pipe behavior through cancellation and submission" { try std.testing.expectEqual(how, pane.prompt.pipe.how); p.update(.{ .key = .{ .cp = 'c', .text = "cat" } }); p.update(.{ .key = .{ .cp = Key.enter } }); - const pending = p.pipe_wait orelse return error.MissingPipe; + const pending = p.pipe.wait orelse return error.MissingPipe; try std.testing.expectEqual(how, pending.how); try std.testing.expectEqualStrings("cat", pending.command); try std.testing.expectEqual(@as(usize, 1), pending.inputs.len); -- 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/dump.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 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/dump.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/dump.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 425d9beb9c977df364ed83743cb2efdef9429478 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 00:42:04 -0300 Subject: File the tag code into tagline.zig and draw tags beside bodies With tags reduced to Texts, what is left of them is the computed prefix, the default and saved tails, entering and leaving a tag and the headers: that goes to tagline.zig, as acme keeps the tag half of a window in wind.c. Tag and header drawing moves next to body drawing in body_layer.zig, and the tag hit helpers go to tag_layer.zig with the Hit they read, where sameCell now also tells the lines of a taller tag apart. The docs describe the tag as a Text. Co-Authored-By: Claude Opus 5.5 --- docs/design.typ | 50 +-- docs/fs.md | 7 +- docs/helix-keys.md | 8 +- docs/tags.md | 64 ++-- src/body_layer.zig | 457 +++++++++++++++++++++- src/builtins.zig | 15 +- src/colors.zig | 3 +- src/dump.zig | 5 +- src/edit.zig | 14 +- src/exec.zig | 5 +- src/fs-help.txt | 2 +- src/fs.zig | 2 + src/gui/gui.zig | 2 +- src/layout.zig | 9 +- src/look.zig | 7 +- src/mouse.zig | 62 +-- src/ninep/pane.zig | 11 +- src/normal.zig | 7 +- src/panes.zig | 2 +- src/pardes.zig | 1025 ++++++-------------------------------------------- src/tag_layer.zig | 25 ++ src/tagline.zig | 360 ++++++++++++++++++ test/column_drag.zig | 18 +- test/fs_bench.zig | 2 +- test/mode.zig | 6 +- test/panes.zig | 50 +-- test/pdf.zig | 10 +- 27 files changed, 1153 insertions(+), 1075 deletions(-) create mode 100644 src/tagline.zig (limited to 'src/dump.zig') diff --git a/docs/design.typ b/docs/design.typ index 82bafb49..8e5f7e6e 100644 --- a/docs/design.typ +++ b/docs/design.typ @@ -530,9 +530,9 @@ Each pane kind keeps its storage and operations together in its own file 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 -is split by thing as acme is: `edit.zig`, `normal.zig`, `look.zig`, `exec.zig`, -`mouse.zig`, `Messages.zig`, `Pipe.zig`, `colors.zig`, `surface.zig`, -`body_layer.zig` and `dump.zig`. Integration fixtures live +is split by thing as acme is: `Text.zig`, `edit.zig`, `normal.zig`, `tagline.zig`, +`look.zig`, `exec.zig`, `mouse.zig`, `Messages.zig`, `Pipe.zig`, `colors.zig`, +`surface.zig`, `body_layer.zig`, `tag_layer.zig` and `dump.zig`. Integration fixtures live in `test/panes.zig`, `test/output.zig`, and `test/pdf.zig`. = State @@ -770,33 +770,35 @@ pair per theme, and the three per-button tints and the dimmed extra cursors are mixed off it, so what stays fixed is the distinction between buttons and not the colours. -`Drag` is a `union(enum)` with six arms (`pardes.Drag`): `none`, -`border_v`, `border_h`, `move`, `tag`, `select`. `border_v` carries an optional +`Drag` is a `union(enum)` with six arms (`mouse.Drag`): `none`, +`border_v`, `border_h`, `move`, `column_move`, `select`. `border_v` carries an optional `corner`: when the press lands on a cell that is both a column's vertical border and one of the two adjoining columns' own horizontal borders, the one drag moves *both* boundaries — never three, and when both columns happen to be split at the grabbed row the left one wins, so the gesture that existed before is bit-for-bit unchanged. -== The tag is a command line - -A tag is one line: a live prefix (mode indicator, cwd or path) plus an editable -tail, and the tail gets the full modal editor. The coordinate space is UTF-8 byte -offsets into the *whole* rendered tag, prefix ++ tail, always on grapheme -boundaries (`Pane.tag_col`). The prefix is live chrome, so it is -selectable, yankable and executable but READ-ONLY: every edit op measures from -`edit0` — the first editable byte — and does nothing left of it. - -`tag_tail` is a fixed `[max_tag_tail]u8`, and the bound IS the storage -(`limits.max_tag_tail`): every writer — `appendTag`, `tagInsert`, -`restoreDumpTail`, the 9P `tag` file — refuses input that does not fit -rather than truncating it. The schema limit and the buffer therefore can never -disagree, which is what lets a dump reader reject data before copying it into a -pane. - -A tag edit is always insert mode, so it hijacks the body's mode; `tag_mode` -remembers what it hijacked and terminals restore it on exit, which is why -clicking a tag never changes a pane's mode. +== The tag is a text + +A tag is a `Text` (`Text.zig`), as a body is: acme's `Text`, one per +`what` — the body, the pane's tag, the prompt line, a column's tag and the +workspace tag. Each holds its own cursor, selections, mode and undo, so tags +are edited by the same `edit.zig` and `normal.zig` code as bodies, and the one +key they do not share is `:`, which moves between a pane's body and its tag. +A tag holds any number of lines; a pane's tag takes a row per line up to +`MAX_TAG_ROWS`, each drawn as a tag layer of its own. + +A pane's tag shows a live prefix (path, dirty marker, PDF page) before the text +it owns, and that prefix is computed at every read, never stored +(`tagline.tagPrefix`). The Text's coordinates are offsets into its own text +alone, so a rename or a save never moves its cursor. The one translation +point is the whole line as shown: render, the mouse, Look, Exec and the 9P +`tag` file see prefix ++ text, while keyboard motions and edits see only the +text. Editing the path is a separate draft (`Pane.prompt = .name`) committed +by Enter, since a buffer's name is not text it owns. + +The tag's text is bounded by `limits.max_tag_tail`: the 9P `tag` file and a +dump reader refuse input that does not fit rather than truncating it. = Diffing and presenting a frame diff --git a/docs/fs.md b/docs/fs.md index da4f4e68..c43034f6 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -180,7 +180,12 @@ back evaluates it, which is what acme(4) promises of its own `addr`. The three flag files `dirty`, `mark` and `scroll` read `0` or `1` and take `0` or `1`: whether the buffer differs from its file, whether a write pushes an undo point (writing `1` pushes one now), and whether a write scrolls the -pane. Truncating `tag` clears the part of the tag you may edit. +pane. + +`tag` reads the whole tag as the pane shows it: the computed path, dirty +marker or PDF page, then the text you may edit. A write appends to that text, +newlines included, and a tag with more than one line takes a row per line on +screen; truncating `tag` clears it, as acme's `cleartag` does. Stats report real lengths for `index`, `status`, `look`, `exec`, `listeners`, `name`, `body`, `tag`, `sel`, `ctl`, the range files and the flag files, and diff --git a/docs/helix-keys.md b/docs/helix-keys.md index 0813c193..64fa2e24 100644 --- a/docs/helix-keys.md +++ b/docs/helix-keys.md @@ -117,15 +117,15 @@ language-backend queries, and the shell pipe. | `Esc` (insert) | back to normal mode, cursor right after the insertion (no vim left-step) | | helix-verified | | `Enter` (normal) | acme **look** chord: EXPLICIT selection, else file-ish word under cursor | pardes-specific, keep (helix normal-mode Enter unbound). Covers helix `gf`. Implicit motion residue falls back to the cursor word | pardes-specific | | `Tab` (normal) | acme **execute** chord | pardes-specific, keep; explicit-selection rule as Enter | pardes-specific | -| `:` (normal, body) | focuses the pane's tag in normal mode at its remembered cursor position (first entry starts at the commands). `h`/`l`, arrows, word motions and `0`/`$`/`^` move within the tag; `k` stays on its single line; `j` or `Esc` returns to the body. Uppercase `H`/`J`/`K`/`L` run `Left`/`Down`/`Up`/`Right` and enter the neighboring pane's tag. `K` beyond the top pane reaches the headers below. `y` yanks; Enter/Tab Look/Exec; `i`/`a`/`I`/`A` enter insert mode, where letters type normally. Explicit mouse clicks choose a new cursor position. | Each tag keeps its own cursor position during the session. Positions are UTF-8 byte offsets in the rendered prefix plus editable tail; file-name changes are staged as described in [editable tags](tags.md). | pardes-specific | -| `K` (tag normal, topmost tagline) | focuses the column tag, then another `K` reaches the workspace tag. With `ColumnTags` disabled it goes directly to the workspace. `J` walks back down. Header arrows and `h`/`l` move by grapheme; word motions and `0`/`$`/`^` work too. `j`/`Esc` returns to the panel; lowercase `k` stays put. Enter/Tab executes in normal mode; `i`/`a`/`I`/`A` enter editing, where Enter is Look and Tab is Exec. | 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, while the bare letters `h/j/k/l` there move to its TAGLINE (next row) | pardes-specific | +| `:` (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, `0` meaning the start of the editable text. Enter/Tab Look/Exec the word under the cursor or the selection, and executing 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. Cursor, selections and undo are offsets in the tag's own text; the computed path/marker/page before it is seen by the mouse, Look and Exec but not by keyboard motions. 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-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`. 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 ONLY five words in pardes that touch the desktop's clipboard — `y`/`d`/`c`/`p`/`P`/`R` and the acme cut/paste chords are the internal register alone. 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. One divergence: pardes keeps a single register VALUE where helix keeps one per range, so `SPC y` at N cursors joins them with newlines (`Pardes.setYank`, the divergence `msel-yank-paste` already waives). 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 | | a paste from the OUTER terminal | one `Event.paste`, spliced in at the cursor | the tty shell enables bracketed paste and coalesces `paste_start`..`paste_end` into a single event; before that the bytes arrived as individual key presses and normal mode RAN them, which is how a pasted `d` deleted a line. The bytes deliberately never enter the yank register — clipboard and default register are separate stores in both directions | pardes-specific | -| `/` (any pane) | pardes' own plain-substring search into a `+Search` output buffer: the tag takes the pattern, Enter fills the buffer, and its rows are ordinary look targets. Enter also GOES to the first row — the buffer is focused and then the step `n` is and the look Enter is run in it (`Pardes.lookFirstHit`), so `/foo` lands on the first hit with the matched span selected. A pattern that matched nothing opens its empty buffer and moves nothing | KEEP, do not touch; not in the corpus (helix `/` is regex search). Find and Grep answer with OTHER files and deliberately do NOT jump. The stepping half is the next row | pardes-specific | +| `/` (any pane) | pardes' own plain-substring search into a `+Search` output buffer: the pattern is typed on a line of its own on the pane's notice band, Enter fills the buffer, and its rows are ordinary look targets. Enter also GOES to the first row — the buffer is focused and then the step `n` is and the look Enter is run in it (`Pardes.lookFirstHit`), so `/foo` lands on the first hit with the matched span selected. A pattern that matched nothing opens its empty buffer and moves nothing | KEEP, do not touch; not in the corpus (helix `/` is regex search). Find and Grep answer with OTHER files and deliberately do NOT jump. The stepping half is the next row | pardes-specific | | `n` / `N` (any pane) | MOTION, not a jump: move the SELECTION to the next / previous look-able text and open NOTHING. Enter — the look chord — on what it leaves selected is what opens it | KEEP, do not touch; not in the corpus (helix's `n`/`N` walk regex search hits). What a step selects is the pane's GRAIN (`output_pane.Grain`, read in `Pardes.lookSpanIn`): in FREE TEXT — a terminal, a file, a PDF, a prose answer buffer — the largest whitespace-delimited run `look.resolve` can act on (`look.lookableSpan`, wrapper punctuation peeled off both ends), several to a line; in a RESULTS BUFFER one stop per ROW, the largest run its head resolves as (`look.lookableLineSpan`), because a row there IS one location and the words after it are the match rather than a second place to go; in a COMMAND list the whole line. The walk is a RING across PANES: every pane that has performed a Look, most recent first (`Pardes.look_src`), then the output buffers that have not, newest first, and only when both are empty the active pane. Exhausting a pane enters the next at its first (forward) / last (backward) span and the end wraps to the start, so `N` is the exact inverse of `n`. What it lands on becomes an EXPLICIT `vsel` with the cursor on its FIRST column, in the pane the walk focuses. ONE motion in every pane kind and every buffer kind — a PDF steps the `+Search` buffer its own search filled, `n` to select the row and Enter to jump. The single thing a buffer may change is that grain, and it changes it by BEING a kind of buffer rather than by a branch: `output_pane.Traits.steps` (a list of locations) makes a step take one row at a time, and `Traits.commands` makes it take the WHOLE LINE, because a command list (`ThemeSel`/`FontSel`) holds words to run and there is no path inside `Theme gruvbox` to pick out. Tab on what `n` selected wears the theme, which is the same middle click on the row is. `]d`/`[d` are helix's diagnostic motions, a different binding, and they do still jump to each diagnostic (`docs/lsp.md`) | pardes-specific | | insert: printable text | file: real edit; terminal: typed run splice | | helix-verified (file) | | insert: `Enter` | newline; keeps the current full indent levels and adds one 4-space logical tab when the text before the cursor ends in `(`, `[`, `{`, or `)` (including `})`) | plain lines match `insert_newline`; delimiter heuristic is pardes-specific | helix-verified (plain) / pardes-specific (delimiter) | diff --git a/docs/tags.md b/docs/tags.md index f299c859..ecca046a 100644 --- a/docs/tags.md +++ b/docs/tags.md @@ -44,34 +44,54 @@ asks; there bare `Del` gives the rows to the nearest document above, as it always has. A collapsed pane is never asked about, and collapsed neighbors are passed over: they only keep a weight for later. -Left-click a tag to place its caret; drag to select text, then type to -replace it. Arrow keys, Home, End, Backspace and Delete edit the line. -Tags reveal the caret horizontally when text is wider than their column. -Escape returns to the body, keeping command-text edits. The existing Exec -and Look gestures still apply; the workspace tag is no longer an inert -left-click target. Pasted text goes to the focused tag, not to the file or -embedded shell beneath it. - -Keyboard entry returns to the tag's last cursor position. The first entry into -a pane tag starts at its commands; clicking always chooses a new position. -Each pane, column and workspace tag remembers its own position during the -session. Shortened text clamps the saved cursor to a valid character boundary. - -In normal mode, `h` and `l` move within the tag, `k` stays on the single line, -and `j` returns to the panel like Escape. Uppercase `HJKL` move between pane -tags. From the top pane's `:` tag, `K` reaches the column and another `K` reaches -the workspace; `J` walks back down. Enter or Tab on a header command in -normal mode executes it, as before. `i`/`a`/`I`/`A` switch to editing the -header. In insert mode, letters type normally, Enter is Look and Tab is Exec, -as in pane tags. +A tag is a text like a pane's body: pane tags, column tags and the +workspace tag all edit with the body's own normal and insert modes, undo +included, and may hold more than one line. A tag with a newline in it takes +a row per line, up to eight: a pane's tag leaves its body at least one row +and a collapsed pane shows only the first line; the column and workspace +tags take no more than a third of the screen, and the panes below move down +to make room. The path, the dirty marker and a PDF's page at the start of a +pane tag are computed, never stored: the tag's cursor, selections and undo +live in the text after them, so a rename or a save never moves the cursor. +The mouse still sees the whole line -- a sweep selects across the path and +the commands, and Look and Exec work on either -- but the keyboard moves only +in the tag's own text: `0` goes to its start, not the path's. + +Left-click a tag or a header to type into it at the click, in insert mode; +tags reveal the caret horizontally when text is wider than their column. +Esc is normal mode, where everything a body's normal mode does works, and +Enter looks up and Tab executes the word under the cursor (or an explicit +selection), in either mode. Executing gives the keyboard back to the body +first, so `Del`, `Kill` and `Restore` never return into a tag that is gone. +Pasted text goes to the focused tag, not to the file or embedded shell +beneath it. + +`:` is the one key a tag and a body do not share: in the body's normal mode +it focuses the pane's tag in normal mode, and in the tag's normal mode it +goes back to the body; in a column or workspace tag it goes back to the +active pane. Each pane, column and workspace tag remembers its own cursor +during the session; the first `:` into a pane tag starts on its `Save`. A +tag's text changing under it (a 9P write, a shorter tag) pulls the cursor +back inside it. + +Moving between tags is the window keys' job, as it is between bodies +(`Ctrl-w` or `SPC w` with `h/j/k/l`): they move to the neighbouring pane's +body. Up from a pane with nothing above it reaches its column's tag, then +the workspace's; Down comes back the same way, and Left and Right walk the +column tags. + +Search (`/`), pipe (`|`) and Save's path prompt are not typed into the tag: +each gets a line of its own on the pane's notice band, with the body's +insert-mode keys, and leaves the tag as it was. Pane filenames and commands now have a single separator space rather than generated right-alignment padding. Intentionally customized spacing is kept. ## File names -Editing a file pane's name creates a draft. Enter confirms the new buffer -name; Escape or leaving the tag cancels the draft. Confirmation changes the +Clicking a file pane's name starts a draft of it, typed into at the click. +Enter or Tab confirms the new buffer name; Escape or leaving the pane +cancels the draft. Confirmation changes the buffer's save target and marks it unsaved. It does **not** rename, create or overwrite a disk file. A subsequent explicit `Save` writes the buffer to its committed name. Executing a pane-tag command confirms a valid name draft diff --git a/src/body_layer.zig b/src/body_layer.zig index 2b2c8a74..ab000795 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -2,7 +2,8 @@ //! outnumber its physical grid rows: hosts place the compact declaration rows //! first and clip the remaining body rows. After the layer types come the //! functions that draw a body into the surface: its text, colours, selections -//! and cursor. +//! and cursor; then the tags drawn beside it, a pane's and the column and +//! workspace ones, each line a tag layer of its own. const std = @import("std"); const pardes = @import("pardes.zig"); const normal = @import("normal.zig"); @@ -24,6 +25,20 @@ const BOX_H = pardes.BOX_H; 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("tag_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; pub const Metrics = struct { body_w: u16 = 1, @@ -540,3 +555,443 @@ pub fn bodyText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]const u8 { if (pane.file) |*f| return panes.File.bodyText(arena, pane, f, p.settings.wrap); return panes.Terminal.bodyText(arena, pane); } + +/// 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; + const chrome = p.chromeTheme(); + const th = p.theme(); + // global tagbar: full width, top rows — unless a native shell has + // taken its commands over, in which case the rows are not ours to draw + tagline.revealHeader(p); + const global = tagline.topbar(p); + const global_rows = p.topBarHeight(); + 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, global_rows, .{ + .bg = .{ .rgb = chrome.tag_bg }, + .font_role = .tagline, + }); + for (0..global_rows) |row| { + const line = modal.lineSlice(global, row); + _ = s.print(0, @intCast(row), s.cols, line[panes.File.rawAtDisplay(line, global_scroll)..], .{ + .fg = .{ .rgb = chrome.tag_fg }, + .bg = .{ .rgb = chrome.tag_bg }, + .font_role = .tagline, + }); + } + } + if (p.pointer_inside and p.hover_row < global_rows) { + const bar = modal.lineSlice(global, p.hover_row); + 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; + while (col < hi and col < s.cols) : (col += 1) { + const cell = s.at(@intCast(col), p.hover_row); + cell.default = false; + cell.style.bg = .{ .rgb = th.sel_bg }; + cell.style.fg = .{ .rgb = th.sel_fg }; + } + } + } + const column_rows = p.columnBarHeight(); + if (column_rows > 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]); + const x = p.col_x[c] + inset; + const w = p.col_w[c] - inset; + const y0 = global_rows; + if (p.col_w[c] == 0 or p.col_x[c] >= s.cols) continue; + const active_col = if (layout.findPane(p, p.active)) |f| f.col == c else false; + const bg = if (active_col and p.settings.focus_tint) chrome.tag_active_bg else chrome.tag_bg; + const fg = if (active_col and p.settings.focus_tint) chrome.tag_active_fg else chrome.tag_fg; + // A grip is muted until it is grabbed; then it lights, as a pane's + // box does for the active pane, so the drag shows what it holds. + const grabbed = p.drag == .column_move and layout.columnBySerial(p, p.drag.column_move.serial) == c; + const grip_bg = if (grabbed) chrome.column_box else chrome.column_box_dim; + const lum = (@as(u16, grip_bg[0]) * 3 + @as(u16, grip_bg[1]) * 6 + @as(u16, grip_bg[2])) / 10; + const ink: [3]u8 = if (lum > 140) .{ 0, 0, 0 } else .{ 255, 255, 255 }; + const grip_style: CellStyle = .{ .bg = .{ .rgb = grip_bg }, .fg = .{ .rgb = ink }, .font_role = .tagline }; + s.fill(p.col_x[c], y0, grip, column_rows, grip_style); + s.fill(p.col_x[c] + grip, y0, inset - grip, column_rows, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); + + s.fill(x, y0, w, column_rows, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); + const bar_scroll = if (p.header_focus and p.header_column == c) p.header_scroll else 0; + const tag = tagline.columnTag(p, c); + for (0..column_rows) |row| { + const line = modal.lineSlice(tag, row); + _ = s.print(x, y0 + @as(u16, @intCast(row)), w, line[panes.File.rawAtDisplay(line, bar_scroll)..], .{ + .fg = .{ .rgb = fg }, + .bg = .{ .rgb = bg }, + .font_role = .tagline, + }); + } + // 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 >= y0 and p.hover_row < y0 + column_rows and p.hover_col >= x and p.hover_col < x + w) { + const bar = modal.lineSlice(tag, p.hover_row - y0); + 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; + while (col < hi and col < w) : (col += 1) { + const cell = s.at(x + @as(u16, @intCast(col)), p.hover_row); + cell.style.bg = .{ .rgb = th.sel_bg }; + cell.style.fg = .{ .rgb = th.sel_fg }; + } + } + } + }; + if (tagline.focusedHeader(p)) |t| { + const text = try edit.flatSurface(p, t); + 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) global_rows else 0; + const rows = if (p.header_column != null) column_rows else global_rows; + for (0..rows) |row| { + const bar = modal.lineSlice(text, row); + const span = tagline.headerSelection(t, text, row) orelse continue; + 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 + @as(u16, @intCast(row))); + cell.style.fg = .{ .rgb = th.sel_fg }; + cell.style.bg = .{ .rgb = th.sel_bg }; + } + } + if (t.cur_row >= 0 and t.cur_row < rows) { + const bar = modal.lineSlice(text, @intCast(t.cur_row)); + 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 + @as(u16, @intCast(t.cur_row)), .bar = t.mode == .insert }; + } + } +} + +fn tagTintRange(pane: *const Pane, tag: []const u8, prefix_len: usize) ?struct { lo: usize, hi: usize } { + if (pane.isTerminal()) { + var words = std.mem.tokenizeAny(u8, tag[prefix_len..], " \t\r\n"); + while (words.next()) |word| { + if (!std.mem.eql(u8, word, "Tty")) continue; + const lo = @intFromPtr(word.ptr) - @intFromPtr(tag.ptr); + return .{ .lo = lo, .hi = lo + word.len }; + } + return null; + } + var start: usize = 0; + const name = if (pane.file) |file| + 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; + break :blk state.path; + } else if (comptime pdf_enabled) blk: { + break :blk if (pane.pdf) |state| state.path else return null; + } else return null; + const basename = if (std.mem.lastIndexOfScalar(u8, name, '/')) |slash| slash + 1 else 0; + if (basename == name.len) return null; + return .{ .lo = start + basename, .hi = start + name.len }; +} + +pub fn renderTagLayers(p: *Pardes, arena: std.mem.Allocator) !void { + const chrome = p.chromeTheme(); + 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 == 0) continue; + const tag = try tagline.tagText(p, arena, pane); + 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 = 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); + // 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. + if (p.settings.workspace_tag) { + for (0..p.topBarHeight()) |line| { + const index = if (line == 0) MAX_PANES + MAX_COLS else HEADER_LINE_LAYER_BASE + MAX_COLS * (MAX_TAG_ROWS - 1) + line - 1; + try renderHeaderLayer(p, arena, index, .workspace, 0, @intCast(line), .{ .x = 0, .y = @intCast(line), .w = p.screen_w, .h = TOPBAR_H }, modal.lineSlice(tagline.topbar(p), line), 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 + // band offset and the border -- none of which a body-grid row can have + // just by wearing a tagline font. The geometry is the one the grid + // pass already chose and recorded, so the two cannot disagree and the + // GUI's "skip the cells a tag layer covers" leaves no stub behind. + // A prompt is one of them too: left on the grid, a pixel shell drew + // its tagline glyphs one to a BODY cell, spaced out like a banner. + 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 <= 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); + if (text.len == 0) continue; + const cx = pane.notices.left[i]; + if (cx == std.math.maxInt(u16) or cx >= r.x + r.w) continue; + const chip = r.x + r.w - cx; + // Right aligned inside the chip, a blank cell short of its + // edge: the same one the grid pass leaves for a prompt caret. + // Wider than the chip, the text loses its head, as on the grid. + const room = p.tagCapacity(chip) -| 1; + const shown = panes.File.displayWidth(text); + var kept = text; + if (shown > room) { + var start = panes.File.rawAtDisplay(text, shown - room); + if (panes.File.rawDisplayCol(text, start) < shown - room) start = panes.File.rawAtDisplay(text, shown - room + 1); + kept = text[start..]; + } + const pad = room -| panes.File.displayWidth(kept); + const line = try arena.alloc(u8, pad + kept.len); + @memset(line[0..pad], ' '); + @memcpy(line[pad..], kept); + // A pixel shell slides the message in as it fades up, and + // fades it on the way out. + const motion: Messages.MessageMotion = if (Messages.noticeLife(pane, i)) |life| Messages.messageMotion(p, life) else .{}; + const fade = motion.alpha; + const page = p.theme().bg orelse chrome.tag_bg; + const layer_index = NOTICE_LAYER_BASE + id * Pane.Notices.max + i; + try renderHeaderLayer(p, arena, layer_index, .notice, @intCast(id), 0, .{ + .x = cx, + .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)); + 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; + 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.input.mode == .insert }; + } + } + 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; + for (0..p.columnBarHeight()) |line| { + const index = if (line == 0) MAX_PANES + column else HEADER_LINE_LAYER_BASE + column * (MAX_TAG_ROWS - 1) + line - 1; + try renderHeaderLayer(p, arena, index, .column, @intCast(column), @intCast(line), .{ .x = p.col_x[column] + @min(TAG_TEXT_INSET, p.col_w[column]), .y = p.topBarHeight() + @as(u16, @intCast(line)), .w = p.col_w[column] -| TAG_TEXT_INSET, .h = COLBAR_H }, modal.lineSlice(tagline.columnTag(p, column), line), if (active) chrome.tag_active_bg else chrome.tag_bg, if (active) chrome.tag_active_fg else chrome.tag_fg); + } + }; +} + +/// One row of a header or a notice band as a tag layer: `text` is line +/// `line` of what it shows. +fn renderHeaderLayer(p: *Pardes, arena: std.mem.Allocator, index: usize, kind: TagKind, id: u16, line: u16, viewport: Rect, text: []const u8, bg: [3]u8, fg: [3]u8) !void { + _ = arena; + const layer = &p.surface.tag_layers[index]; + if (viewport.w == 0) { + layer.cols = 0; + return; + } + const columns: u16 = @intCast(@min(std.math.maxInt(u16), @max(p.tagCapacity(viewport.w), panes.File.displayWidth(text) + 1))); + if (layer.cells.len != columns) layer.cells = try p.gpa.realloc(layer.cells, columns); + layer.kind = kind; + layer.id = id; + layer.line = line; + layer.serial = if (kind == .column) p.col_serial[id] else 0; + layer.viewport = viewport; + layer.cols = columns; + layer.bg = bg; + layer.cursor = null; + layer.slide = 0; + layer.fade = 1; + var surface: Surface = .{ .cols = columns, .rows = 1, .cells = layer.cells }; + // 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: ?*Text = if (p.header_focus and switch (kind) { + .workspace => p.header_column == null, + .column => p.header_column == id, + .pane, .notice => false, + }) tagline.focusedHeader(p) 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) |t| { + if (tagline.headerSelection(t, try edit.flatSurface(p, t), line)) |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, @min(@as(usize, @intCast(@max(0, t.cur_col))), text.len)) -| scroll; + if (t.cur_row == line 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| + (if (pointer.kind == kind and pointer.id == id and pointer.line == line) pointer.col else null) + else if (p.hover_row == viewport.y and p.hover_col >= viewport.x and p.hover_col - viewport.x < viewport.w) + p.hover_col - viewport.x + else + null; + if (col) |hover| if (wordBoundsAtCol(text, panes.File.rawAtDisplay(text, hover + scroll))) |bounds| { + var cell = panes.File.rawDisplayCol(text, bounds.lo) -| scroll; + const end = panes.File.rawDisplayCol(text, bounds.hi) -| scroll; + while (cell < end and cell < columns) : (cell += 1) { + surface.at(@intCast(cell), 0).style.bg = .{ .rgb = p.theme().sel_bg }; + surface.at(@intCast(cell), 0).style.fg = .{ .rgb = p.theme().sel_fg }; + } + }; + } +} + +pub fn paintPaneTag(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool, capacity: u16) !void { + const s = &p.surface; + const th = p.theme(); + const chrome = p.chromeTheme(); + const tx = r.x + @min(TAG_TEXT_INSET, r.w); + const tw = r.w -| TAG_TEXT_INSET; + 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; + const tag_fg = if (active and p.settings.focus_tint) chrome.tag_active_fg else chrome.tag_fg; + 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), 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 tagline.tagText(p, arena, pane); + const tail = tagline.curTail(pane); + const prefix_len = whole.len - tail.len; + // 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) + .{ .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 (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; + 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, 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; + const end = panes.File.rawDisplayCol(tag, hi) -| pane.tag_scroll; + const name_fg = if (active and p.settings.focus_tint) chrome.tag_active_name_fg else chrome.tag_name_fg; + while (col < end and col < tw) : (col += 1) + s.at(tx + @as(u16, @intCast(col)), tag_y).style.fg = .{ .rgb = name_fg }; + } + } + 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)); + 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 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); + 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) 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| { + 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 + @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) >= rows) continue; + paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, selection, th.sel_bg, th.sel_fg); + } +} diff --git a/src/builtins.zig b/src/builtins.zig index 74645376..e9f29102 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1,6 +1,7 @@ //! Command structs and runtime settings form the builtin registry; bindings live in config.zig. const std = @import("std"); const pardes = @import("pardes.zig"); +const tagline = @import("tagline.zig"); const dump = @import("dump.zig"); const exec = @import("exec.zig"); const look = @import("look.zig"); @@ -742,7 +743,7 @@ pub const Grep = struct { pub const Left = struct { pub fn run(c: Ctx) void { if (c.p.header_focus) { - if (c.p.header_column) |column| if (column > 0) c.p.enterHeader(column - 1); + if (c.p.header_column) |column| if (column > 0) tagline.enterHeader(c.p, column - 1); return; } _ = layout.focusDir(c.p, c.id, .left); @@ -754,10 +755,10 @@ pub const Down = struct { 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); + return tagline.enterHeader(c.p, 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(); + tagline.exitHeader(c.p); if (col < c.p.ncol and c.p.col_n[col] > 0) c.p.active = c.p.col_panes[col][0]; return; } @@ -768,20 +769,20 @@ pub const Down = struct { pub const Up = struct { pub fn run(c: Ctx) void { if (c.p.header_focus) { - if (c.p.header_column != null and c.p.topBarHeight() > 0) c.p.enterHeader(null); + if (c.p.header_column != null and c.p.topBarHeight() > 0) tagline.enterHeader(c.p, 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); + if (layout.findPane(c.p, c.id)) |at| tagline.enterHeader(c.p, at.col); + } else if (c.p.topBarHeight() > 0) tagline.enterHeader(c.p, null); } }; pub const Right = struct { pub fn run(c: Ctx) void { if (c.p.header_focus) { - if (c.p.header_column) |column| if (column + 1 < c.p.ncol) c.p.enterHeader(column + 1); + if (c.p.header_column) |column| if (column + 1 < c.p.ncol) tagline.enterHeader(c.p, column + 1); return; } _ = layout.focusDir(c.p, c.id, .right); diff --git a/src/colors.zig b/src/colors.zig index f92f67b1..bb366fc0 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -1,6 +1,7 @@ //! Colour themes: the Theme type, the curated and generated ring, chrome //! colours and their animation, theme files, and switching themes at runtime. const pardes = @import("pardes.zig"); +const tagline = @import("tagline.zig"); const panes = @import("panes.zig"); const std = @import("std"); const layout = @import("layout.zig"); @@ -602,7 +603,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.enterTag(pane); + tagline.enterTag(p, 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 aeb25a90..508e7300 100644 --- a/src/dump.zig +++ b/src/dump.zig @@ -7,6 +7,7 @@ const limits = @import("memory.zig").limits; // diagnostic is the only thing that says WHICH field went bad. const log = std.log.scoped(.dump); const pardes = @import("pardes.zig"); +const tagline = @import("tagline.zig"); const layout = @import("layout.zig"); const filesystem = @import("fs.zig"); const ctlfs = @import("ninep/tree.zig"); @@ -603,7 +604,7 @@ pub fn dumpState(p: *Pardes) !void { for (p.panes, 0..) |slot, id| { const pane = slot orelse continue; slot_to_pane[id] = panes_len; - const tag = try p.tagText(arena, pane); + const tag = try tagline.tagText(p, arena, pane); 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( @@ -784,7 +785,7 @@ fn initDump(gpa: std.mem.Allocator, opts: Options, zon_bytes: []const u8, previo break :restore_image try pardes.panes.Image.restore(p, i, src); }, }; - p.restoreDumpTail(pane, src); + tagline.restoreDumpTail(p, pane, src); pane.vweight = src.vweight; pane.collapsed = src.collapsed; } diff --git a/src/edit.zig b/src/edit.zig index 36544d6b..edc86dd2 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -3,6 +3,7 @@ //! operations, replace, case, join, indent, comments, numbers, textobjects //! and surround, undo, yank and paste, and the pointer selections as text. const pardes = @import("pardes.zig"); +const tagline = @import("tagline.zig"); const mouse = @import("mouse.zig"); const normal = @import("normal.zig"); const std = @import("std"); @@ -15,7 +16,8 @@ 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 tag_layer = @import("tag_layer.zig"); +const TagHit = tag_layer.Hit; const BOX_H = pardes.BOX_H; const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; const Mouse = pardes.Mouse; @@ -72,7 +74,7 @@ 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.focusedHeader()) |t| { + if (tagline.focusedHeader(p)) |t| { p.clip_pending = null; return pasteInto(p, t, bytes); } @@ -132,7 +134,7 @@ pub fn clipYank(p: *Pardes, pane: *Pane, main_only: bool) void { /// (the tag's lines first, as many as it shows) pub fn paneText(p: *Pardes, pane: *Pane) ![]u8 { const arena = p.scratch.allocator(); - const tag = try p.tagText(arena, pane); + const tag = try tagline.tagText(p, 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) }); @@ -353,9 +355,9 @@ pub fn pinPaneCursor(p: *Pardes, t: *Text) void { pub fn flatSurface(p: *Pardes, t: *Text) ![]const u8 { switch (t.what) { .body => {}, - .tag => return Pardes.curTail(t.pane()), + .tag => return tagline.curTail(t.pane()), .input => return t.own orelse "", - .column, .workspace => return t.own orelse p.headerDefault(t.what), + .column, .workspace => return t.own orelse tagline.headerDefault(p, t.what), } const pane = t.pane(); if (pane.file) |f| return f.content; @@ -1617,7 +1619,7 @@ pub fn pointerTextSelection(p: *const Pardes, id: usize, col: u16, row: u16, bod 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, row - tag_y) else null; + const tag_col = if (on_tag) tag_layer.columnAt(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, 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); diff --git a/src/exec.zig b/src/exec.zig index a673e9e7..a0e3d47f 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -3,6 +3,7 @@ //! chord hands over, the terminals commands run in, placing a document, and //! saving a pane. const pardes = @import("pardes.zig"); +const tagline = @import("tagline.zig"); const std = @import("std"); const layout = @import("layout.zig"); const modal = @import("modal.zig"); @@ -352,7 +353,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.own) |own| if (!std.mem.eql(u8, own, Pardes.defaultTail(old))) return; + if (old.tag.own) |own| if (!std.mem.eql(u8, own, tagline.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); @@ -490,7 +491,7 @@ pub fn applySettingBuiltin(p: *Pardes, setting: config.Runtime.Setting, arg: ?[] const tagline_metrics_changed = setting.action == .tagline_size and p.settings.font.tagline_percent != previous_tagline_percent; if (p.settings.column_tags != previous_column_tags) { - if (p.header_column != null) p.exitHeader(); + if (p.header_column != null) tagline.exitHeader(p); } if (transition_changed or tagline_metrics_changed or p.settings.column_tags != previous_column_tags) { p.abandonPanelAnimations(); diff --git a/src/fs-help.txt b/src/fs-help.txt index 4eecad41..efdecf46 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -39,7 +39,7 @@ Pitfalls, one each: addr, dot and limit read the same pair of offsets they take, so cp between them works. dirty, mark and scroll read "0" or "1" and take "0" or "1"; truncating limit lifts it. Writing body appends; open it with truncation to replace; writes are whole UTF-8 sequences. - Truncating tag clears the part you may edit; truncating dot or addr empties it. + tag reads path++text; writes append to the text (newlines too); truncating clears it, and dot or addr. A terminal's body is a history snapshot frozen per open; pty/data is the live stream. A failing command is reported in the editor and in log, not as a write error; a bad line fails the write. pane//ctl: acme's status line; takes get (reload), lock/unlock on a held fd (exec 3>ctl; echo lock >&3). diff --git a/src/fs.zig b/src/fs.zig index 5374c843..7e387958 100644 --- a/src/fs.zig +++ b/src/fs.zig @@ -36,10 +36,12 @@ else const source_files = [_]Source{ .{ .path = "src/pardes.zig", .contents = @embedFile("pardes.zig") }, .{ .path = "src/panes.zig", .contents = @embedFile("panes.zig") }, + .{ .path = "src/Text.zig", .contents = @embedFile("Text.zig") }, .{ .path = "src/surface.zig", .contents = @embedFile("surface.zig") }, .{ .path = "src/colors.zig", .contents = @embedFile("colors.zig") }, .{ .path = "src/Messages.zig", .contents = @embedFile("Messages.zig") }, .{ .path = "src/body_layer.zig", .contents = @embedFile("body_layer.zig") }, + .{ .path = "src/tagline.zig", .contents = @embedFile("tagline.zig") }, .{ .path = "src/edit.zig", .contents = @embedFile("edit.zig") }, .{ .path = "src/normal.zig", .contents = @embedFile("normal.zig") }, .{ .path = "src/mouse.zig", .contents = @embedFile("mouse.zig") }, diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 7bf45676..415b21e8 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -7417,7 +7417,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.enterHeader(null); + pardes.tagline.enterHeader(core, 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 54b89081..8e44f1d9 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -1,5 +1,6 @@ const std = @import("std"); const pardes = @import("pardes.zig"); +const tagline = @import("tagline.zig"); const dump = @import("dump.zig"); const config = @import("config.zig"); const panes = @import("panes.zig"); @@ -934,7 +935,7 @@ pub fn removePane(p: *Pardes, id: usize) void { while (k + 1 < p.col_n[c]) : (k += 1) p.col_panes[c][k] = p.col_panes[c][k + 1]; p.col_n[c] -= 1; if (p.col_n[c] == 0) { - p.exitHeader(); + tagline.exitHeader(p); 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; @@ -955,7 +956,7 @@ pub fn joinCol(p: *Pardes) void { const f = findPane(p, p.active) orelse return; const c = f.col; if (c + 1 >= p.ncol) return; - p.exitHeader(); + tagline.exitHeader(p); const dst = c + 1; 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]; @@ -1010,7 +1011,7 @@ pub fn splitColumn(p: *Pardes, source_id: usize, id: usize, before: bool) bool { const new_weight = old_weight - source_weight; p.col_weight[source_col] = source_weight; const c = source_col + @intFromBool(!before); - p.exitHeader(); + tagline.exitHeader(p); var j = p.ncol; while (j > c) : (j -= 1) { p.col_panes[j] = p.col_panes[j - 1]; @@ -2262,7 +2263,7 @@ test "column reorder moves only crossed state and preserves weights" { 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(i32, 21), p.focusedHeader().?.cur_col); + try std.testing.expectEqual(@as(i32, 21), tagline.focusedHeader(p).?.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]); diff --git a/src/look.zig b/src/look.zig index 8aa2c0a1..cbdf0bea 100644 --- a/src/look.zig +++ b/src/look.zig @@ -19,7 +19,8 @@ const Color = @import("surface.zig").Color; const pdf = panes.Pdf.pdf; const Pane = panes.Pane; const MAX_PANES = pardes.MAX_PANES; -const TagHit = @import("tag_layer.zig").Hit; +const tag_layer = @import("tag_layer.zig"); +const TagHit = tag_layer.Hit; const BOX_H = pardes.BOX_H; const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; const pathUnder = pardes.pathUnder; @@ -878,9 +879,9 @@ fn noteLookHover(p: *Pardes, col: u16, row: u16, body_hit: ?Mouse.BodyHit, tag_h if (comptime pdf_enabled) if (p.pdf_hover_preview) |shown| if (shown.col == col and shown.row == row and shown.pane == id and shown.serial == pane.serial) return; if (p.look_hover_preview) |shown| - if (shown.col == col and shown.row == row and shown.pane == id and shown.serial == pane.serial and mouse.sameBodyCell(shown.body_hit, body_hit) and mouse.sameTagCell(shown.tag_hit, tag_hit)) return; + if (shown.col == col and shown.row == row and shown.pane == id and shown.serial == pane.serial and mouse.sameBodyCell(shown.body_hit, body_hit) and tag_layer.sameCell(shown.tag_hit, tag_hit)) return; if (p.look_hover_wait) |waiting| - if (waiting.col == col and waiting.row == row and waiting.pane == id and waiting.serial == pane.serial and mouse.sameBodyCell(waiting.body_hit, body_hit) and mouse.sameTagCell(waiting.tag_hit, tag_hit)) return; + if (waiting.col == col and waiting.row == row and waiting.pane == id and waiting.serial == pane.serial and mouse.sameBodyCell(waiting.body_hit, body_hit) and tag_layer.sameCell(waiting.tag_hit, tag_hit)) return; cancelLookHover(p); p.look_hover_wait = .{ .col = col, .row = row, .pane = id, .serial = pane.serial, .body_hit = body_hit, .tag_hit = tag_hit }; diff --git a/src/mouse.zig b/src/mouse.zig index 4b624dca..df657ead 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -2,6 +2,7 @@ //! releases (acme's chords, border and seam drags, gestures), and the //! chrome targets a shell asks about. const pardes = @import("pardes.zig"); +const tagline = @import("tagline.zig"); const exec = @import("exec.zig"); const look = @import("look.zig"); const std = @import("std"); @@ -19,8 +20,7 @@ const pdf = panes.Pdf.pdf; const platform = pardes.platform; const Pane = panes.Pane; const MAX_PANES = pardes.MAX_PANES; -const TagHit = @import("tag_layer.zig").Hit; -const TagKind = @import("tag_layer.zig").Kind; +const tag_layer = @import("tag_layer.zig"); const TOPBAR_H = pardes.TOPBAR_H; const BOX_H = pardes.BOX_H; const TAG_GAP = pardes.TAG_GAP; @@ -176,30 +176,6 @@ pub fn bodyHitForPane(p: *const Pardes, id: usize, supplied: Mouse.BodyHit, clam return p.reprojectBodyHit(mapped_hit); } -pub fn sameTagCell(a: ?TagHit, b: ?TagHit) bool { - const first = a orelse return b == null; - const second = b orelse return false; - return first.kind == second.kind and first.id == second.id and first.serial == second.serial and first.col == second.col; -} - -/// 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 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; - const right = @as(f32, @floatFromInt(layer.viewport.x + layer.viewport.w)) * bw; - point.pixel_x = std.math.clamp(point.pixel_x, left, @max(left, right - 0.001)); - point.pixel_y = (@as(f32, @floatFromInt(layer.viewport.y)) + 0.5) * bh; - break; - }; - return if (p.reprojectTagHit(point)) |mapped| mapped.col else null; -} - pub fn sameBodyCell(a: ?Mouse.BodyHit, b: ?Mouse.BodyHit) bool { const first = a orelse return b == null; const second = b orelse return false; @@ -294,7 +270,7 @@ 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 { + const t = tagline.focusedHeader(p) orelse { p.header_drag = false; return; }; @@ -303,7 +279,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { const top = if (p.header_column != null) p.topBarHeight() else 0; const line: u16 = @intCast(@min(mrow -| top, modal.lineCount(text) -| 1, (if (p.header_column != null) p.columnBarHeight() else p.topBarHeight()) -| 1)); const bar = modal.lineSlice(text, line); - 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, line) orelse (mcol -| x)) + p.header_scroll)); + const at = @min(bar.len, panes.File.rawAtDisplay(bar, (tag_layer.columnAt(p, if (p.header_column != null) .column else .workspace, p.header_column orelse 0, p.pointer_tag_hit, p.header_drag, line) orelse (mcol -| x)) + p.header_scroll)); // the anchor stays where the press put it t.cur_row = line; t.cur_col = @intCast(at); @@ -338,23 +314,23 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { if (line > 0 and line >= modal.lineCount(text)) return; const bar = modal.lineSlice(text, line); 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, line) orelse (mcol -| x)) + scroll)); + const at = @min(bar.len, panes.File.rawAtDisplay(bar, (tag_layer.columnAt(p, if (column != null) .column else .workspace, column orelse 0, p.pointer_tag_hit, p.header_drag, line) 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); + if (!focused) tagline.enterHeader(p, column); t.mode = .insert; t.cur_row = line; t.cur_col = @intCast(at); t.vsel = .{ .active = false, .row = line, .col = @intCast(at) }; p.header_drag = true; } else { - const span = if (focused) Pardes.headerSelection(t, text, line) else null; + const span = if (focused) tagline.headerSelection(t, text, line) 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(); + tagline.exitHeader(p); if (word.len > 0) { if (m.button == config.exec_button) { const named = std.meta.stringToEnum(Builtin, word); @@ -366,7 +342,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { return; } if (m.kind == .press) { - p.exitHeader(); + tagline.exitHeader(p); } switch (m.button) { @@ -484,7 +460,7 @@ pub fn handleMouse(p: *Pardes, m: Mouse) void { pane.tag.msel.active = false; pane.tag.nsel = 0; pane.tag.cur_pinned = true; - const at = p.tagOffsetAt(pane, @intCast(@max(0, pointed.sel.r0)), @intCast(@max(0, pointed.sel.c0))) orelse modal.Cursor{ .row = 0, .col = 0 }; + const at = tagline.tagOffsetAt(p, 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); } @@ -626,7 +602,7 @@ pub fn dragUpdate(p: *Pardes, mcol: u16, mrow: u16, body_hit: ?Mouse.BodyHit) vo // 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| { + if (pane.sel[b].r0 < tag_rows) if (tag_layer.columnAt(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 = tag_line; return; @@ -683,7 +659,7 @@ fn reportGesture( fn gestureRange(p: *Pardes, id: usize, text: []const u8, on_tag: bool, operand: exec.PointerOperand) ctlfs.pane.State.Range { const pane = p.panes[id] orelse return .{}; if (on_tag) { - const tag = p.tagText(p.scratch.allocator(), pane) catch return .{}; + const tag = tagline.tagText(p, p.scratch.allocator(), pane) catch return .{}; const sel = operand.expanded orelse operand.preview orelse return .{}; 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)); @@ -847,11 +823,11 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { 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.r1)), @intCast(@max(0, sl.c1))); + const at = tagline.tagOffsetAt(p, 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))); + } else if (!dragged) tagline.draftName(p, pane, @intCast(@max(0, sl.c1))); return; } if (dragged) edit.capturePointerSelection(p, pane, sel_slot) catch {}; @@ -908,13 +884,13 @@ 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 == 0 and s.button == config.exec_button and pane.prompt == .name) { - const prefix_width = panes.File.displayWidth(p.tagPrefix(pane) catch return); + const prefix_width = panes.File.displayWidth(tagline.tagPrefix(p, pane) catch return); const on_name = @as(usize, @intCast(@max(0, clk.c0))) < prefix_width; - if (!p.commitTagName(pane)) return; + if (!tagline.commitTagName(p, pane)) return; // Executing a staged filename commits it; executing its // command tail uses the new identity (especially Save). if (on_name) return; - const new_width = panes.File.displayWidth(p.tagPrefix(pane) catch return); + const new_width = panes.File.displayWidth(tagline.tagPrefix(p, pane) catch return); const shift = @as(i32, @intCast(new_width)) - @as(i32, @intCast(prefix_width)); if (operand.expanded) |*sel| { sel.c0 += shift; @@ -962,8 +938,8 @@ fn chordCutPaste(p: *Pardes, cut: bool) void { 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; + const from = tagline.tagOffsetAt(p, pane, @intCast(@max(0, start[0])), @intCast(@max(0, start[1]))) orelse origin; + const to = tagline.tagOffsetAt(p, 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; diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 282ae473..8e827fba 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -3,6 +3,7 @@ //! mark and scroll, errors, event, look and exec. Terminals add pty/ (pty.zig). const std = @import("std"); const pardes = @import("../pardes.zig"); +const tagline = @import("../tagline.zig"); const exec = @import("../exec.zig"); const look = @import("../look.zig"); const panes = @import("../panes.zig"); @@ -79,7 +80,7 @@ pub fn fileOf(pane: *Pane) ?*panes.File.State { } pub fn tagOf(p: *Pardes, pane: *Pane) []const u8 { - return p.tagText(p.scratch.allocator(), pane) catch ""; + return tagline.tagText(p, p.scratch.allocator(), pane) catch ""; } pub fn dirOf(pane: *Pane) []const u8 { @@ -422,7 +423,7 @@ fn writeTag(req: Req, pane: *Pane) Reply { if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; // 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 had = tagline.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)]); @@ -746,7 +747,7 @@ 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, Pardes.curTail(pane), " Mine")); + try testing.expect(std.mem.endsWith(u8, tagline.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")); @@ -754,7 +755,7 @@ test "tag reads the whole tag and writes append to the editable tail" { // 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, tagline.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); @@ -887,7 +888,7 @@ 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(Pardes.curTail(pane).len > 0); + try testing.expect(tagline.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.expectEqualStrings("", pane.tag.own.?); diff --git a/src/normal.zig b/src/normal.zig index 630f7689..29d6d620 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -2,6 +2,7 @@ //! modal actions, replayed across every selection, and each action is done //! to the pane; PDF panes get their own normal keys. const pardes = @import("pardes.zig"); +const tagline = @import("tagline.zig"); const exec = @import("exec.zig"); const look = @import("look.zig"); const std = @import("std"); @@ -556,8 +557,8 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void // keyboard between them. .command_line => switch (t.what) { .tag => pane.focus = .body, - .column, .workspace => p.exitHeader(), - .body, .input => p.enterTag(pane), + .column, .workspace => tagline.exitHeader(p), + .body, .input => tagline.enterTag(p, pane), }, .pipe_selection => |how| return p.startPrompt(pane, .{ .pipe = how }), .search => return p.startPrompt(pane, .{ .search = config.search_marker }), @@ -600,7 +601,7 @@ pub fn handlePdfNormal(p: *Pardes, pane: *Pane, key: Key) void { p.leader_on = true; p.leader_n = 0; }, - .command_line => p.enterTag(pane), + .command_line => tagline.enterTag(p, 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 6887008c..3cd66eb7 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -299,7 +299,7 @@ pub const Pane = struct { /// 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 had = pane.tag.own orelse pardes.tagline.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; diff --git a/src/pardes.zig b/src/pardes.zig index d07539ba..c802f0ea 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -11,6 +11,7 @@ pub const syntax = @import("syntax.zig"); pub const locations_config = @import("locations_config.zig"); const tracy = @import("tracy.zig"); pub const panes = @import("panes.zig"); +pub const tagline = @import("tagline.zig"); pub const exec = @import("exec.zig"); pub const mouse = @import("mouse.zig"); pub const normal = @import("normal.zig"); @@ -445,6 +446,7 @@ pub const Loc = struct { }; test { + _ = @import("tagline.zig"); _ = @import("exec.zig"); _ = @import("look.zig"); _ = @import("mouse.zig"); @@ -459,48 +461,9 @@ test { _ = @import("tag_layer.zig"); } -const pane_tail = " " ++ config.pane_builtins_str; -const pdf_pane_tail = " " ++ config.pdf_pane_builtins_str; -const file_pane_tail = " " ++ config.file_pane_builtins_str; -const context_pane_tail = file_pane_tail ++ " TreeContext"; -const locations_pane_tail = file_pane_tail ++ " LocationsConfig"; -const terminal_pane_tail = " " ++ config.terminal_pane_builtins_str; -const dirty_marker = " *"; -const legacy_pane_tail = " Del"; -const legacy_file_pane_tail = " Save Del"; -// The defaults from the release before Newtty joined every tagline. Recognized -// so a dump written then upgrades instead of keeping the old word as a tail. -const prev_pane_tail = " New Del"; -const prev_file_pane_tail = " Save New Del"; -const legacy_terminal_pane_tail = " New Del Filter"; -// ...and the terminal default from the release before Save reached it, when a -// scrollback was not yet something you could write to a path. -const prev_terminal_pane_tail = " New Newtty Del Filter"; -const pre_tty_terminal_pane_tail = " Save New Newtty Del Filter"; -const pre_column_pane_tail = " New Newtty Del"; -const pre_column_file_pane_tail = " Save New Newtty Del"; -const pre_column_pdf_pane_tail = " New Newtty Del PdfSections PdfTint"; -const pre_column_terminal_pane_tail = " Save New Newtty Del Tty Filter"; -const pre_collapse_pane_tail = " Tty Del"; -const pre_collapse_file_pane_tail = " Save Tty Del"; -const pre_collapse_pdf_pane_tail = " Tty Del PdfSections PdfTint"; -const pre_collapse_terminal_pane_tail = " Save Tty Del Togglettymode Filter"; -const pre_tty_first_terminal_pane_tail = " Save Tty Del Togglettymode Filter Collapse"; -const pre_mode_terminal_pane_tail = " Tty Save Del Togglettymode Filter Collapse"; -// ...and the defaults from before the closing word moved to the end of every -// tagline, where a click cannot land on it by overshooting the one before. -const pre_close_last_pane_tail = " Tty Del Collapse"; -const pre_close_last_file_pane_tail = " Save Tty Del Collapse"; -const pre_close_last_pdf_pane_tail = " Tty Del PdfSections PdfTint Collapse"; -const pre_close_last_terminal_pane_tail = " Tty Save Del Mode Filter Collapse"; - pub const Builtin = builtins.registry.Builtin(); pub const test_api = if (@import("builtin").is_test) struct { - pub fn tagText(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) ![]u8 { - return p.tagText(arena, pane); - } - pub fn runBuiltin( p: *Pardes, name: []const u8, @@ -669,11 +632,11 @@ test "pane-tag Exec prefers Tty and argument builtins before shell fallback" { p.acknowledgeShell(0, "/bin/sh", false); const pane = p.panes[0].?; - try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(pane)); + try std.testing.expectEqualStrings(tagline.terminal_pane_tail, tagline.curTail(pane)); const tag_x = p.rects[0].x + TAG_TEXT_INSET; const tag_y = p.rects[0].y; - const rendered = try p.tagText(p.scratch.allocator(), pane); + const rendered = try tagline.tagText(p, p.scratch.allocator(), pane); const new_x = tag_x + @as(u16, @intCast(std.mem.indexOf(u8, rendered, "Tty").?)) + 1; var panes_before: usize = 0; for (p.panes) |s| if (s != null) { @@ -738,7 +701,7 @@ test "Collapse builtin keeps content and restores the pane from its default tag" p.sync(); const height = p.rects[0].h; const revision = pane.file.?.revision; - for ([_][]const u8{ pane_tail, file_pane_tail, pdf_pane_tail, terminal_pane_tail }) |tail| + for ([_][]const u8{ tagline.pane_tail, tagline.file_pane_tail, tagline.pdf_pane_tail, tagline.terminal_pane_tail }) |tail| try std.testing.expect(std.mem.endsWith(u8, tail, " Collapse Del")); try std.testing.expect(p.executeBuiltinLine(0, "Collapse")); @@ -749,7 +712,7 @@ 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.enterTag(pane); + tagline.enterTag(p, 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); pane.focus = .body; @@ -761,9 +724,9 @@ test "Collapse builtin keeps content and restores the pane from its default tag" // Unedited defaults from the preceding version gain the new command. if (pane.tag.own) |own| p.gpa.free(own); pane.tag.own = null; - p.restoreTailAt(pane, pre_collapse_file_pane_tail, "", .file); + tagline.restoreTailAt(p, pane, tagline.pre_collapse_file_pane_tail, "", .file); try std.testing.expect(pane.tag.own == null); - try std.testing.expectEqualStrings(file_pane_tail, Pardes.curTail(pane)); + try std.testing.expectEqualStrings(tagline.file_pane_tail, tagline.curTail(pane)); } test "LocationsConfig command reports partial updates and survives restore" { @@ -850,12 +813,12 @@ test "TreeContext command and custom tag survive a workspace round trip" { defer p.deinit(); const pane = try p.setTestFile("pub fn main() void {}\n"); try std.testing.expect(!panes.File.supportsContext(pane)); - try std.testing.expectEqualStrings(file_pane_tail, Pardes.curTail(pane)); + try std.testing.expectEqualStrings(tagline.file_pane_tail, tagline.curTail(pane)); const path = try p.gpa.dupe(u8, "/test.zig"); p.gpa.free(pane.file.?.path); pane.file.?.path = path; if (!panes.File.supportsContext(pane)) return error.SkipZigTest; - try std.testing.expectEqualStrings(context_pane_tail, Pardes.curTail(pane)); + try std.testing.expectEqualStrings(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); @@ -872,14 +835,14 @@ test "TreeContext command and custom tag survive a workspace round trip" { defer restored.deinit(); const saved = restored.panes[0].?; try std.testing.expect(saved.file.?.tree_context); - try std.testing.expectEqualStrings(" Save Keep Del", Pardes.curTail(saved)); + try std.testing.expectEqualStrings(" Save Keep Del", tagline.curTail(saved)); } test "Togglettymode builtin and keyboard chord share mode transitions including edited tags" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 120, .rows = 20, .tty_only = true }); defer p.deinit(); const pane = p.panes[0].?; - try std.testing.expect(std.mem.indexOf(u8, Pardes.curTail(pane), " Mode ") != null); + try std.testing.expect(std.mem.indexOf(u8, tagline.curTail(pane), " Mode ") != null); try pane.appendTag(" Togglettymode"); try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); try std.testing.expect(p.executeBuiltinLine(0, "Togglettymode")); @@ -887,19 +850,19 @@ test "Togglettymode builtin and keyboard chord share mode transitions including p.update(.{ .key = .{ .cp = p.opts.tty_toggle, .ctrl = true } }); try std.testing.expectEqual(Text.Mode.tty, pane.body.mode); // The tag has its own mode: the body keeps tty while the tag is typed into. - p.enterTag(pane); + tagline.enterTag(p, 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.focus == .body); - p.enterTag(pane); + tagline.enterTag(p, 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.focus == .body); p.acknowledgePanelPresentation(&.{}); - const tag = try p.tagText(p.scratch.allocator(), pane); + const tag = try tagline.tagText(p, p.scratch.allocator(), pane); const x = p.rects[0].x + TAG_TEXT_INSET + @as(u16, @intCast(std.mem.indexOf(u8, tag, "Togglettymode").?)); const y = p.rects[0].y; p.update(.{ .mouse = .{ .button = .middle, .kind = .press, .col = x, .row = y } }); @@ -965,30 +928,30 @@ test "compact tag commands stay beside their own prefix across layout changes" { const above = p.panes[0].?; try std.testing.expectEqual(p.rects[0].x, p.rects[below_id].x); - const above_tag = try p.tagText(gpa, above); + const above_tag = try tagline.tagText(p, gpa, above); defer gpa.free(above_tag); - const below_tag = try p.tagText(p.scratch.allocator(), below); + const below_tag = try tagline.tagText(p, p.scratch.allocator(), below); try std.testing.expect(below_tag.len > above_tag.len); - const tail = terminal_pane_tail; + const tail = tagline.terminal_pane_tail; try std.testing.expectEqualStrings(tail, above_tag[above_tag.len - tail.len ..]); try std.testing.expectEqual(above.cwdSlice().len + tail.len, above_tag.len); p.update(.{ .resize = .{ .cols = 88, .rows = 30 } }); while (p.nextEffect()) |_| {} - try std.testing.expectEqualStrings(above_tag, try p.tagText(p.scratch.allocator(), above)); + try std.testing.expectEqualStrings(above_tag, try tagline.tagText(p, p.scratch.allocator(), above)); p.update(.{ .resize = .{ .cols = 87, .rows = 30 } }); while (p.nextEffect()) |_| {} - try std.testing.expectEqualStrings(above_tag, try p.tagText(p.scratch.allocator(), above)); + try std.testing.expectEqualStrings(above_tag, try tagline.tagText(p, p.scratch.allocator(), above)); p.update(.{ .resize = .{ .cols = 100, .rows = 30 } }); while (p.nextEffect()) |_| {} - try std.testing.expectEqualStrings(tail, Pardes.curTail(below)); + try std.testing.expectEqualStrings(tail, tagline.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); + try std.testing.expectEqual(above_tag.len, (try tagline.tagText(p, p.scratch.allocator(), above)).len); p.update(.{ .resize = .{ .cols = 100, .rows = 2 } }); while (p.nextEffect()) |_| {} try std.testing.expectEqual(@as(u16, 0), p.rects[below_id].h); - try std.testing.expectEqualStrings(above_tag, try p.tagText(p.scratch.allocator(), above)); + try std.testing.expectEqualStrings(above_tag, try tagline.tagText(p, p.scratch.allocator(), above)); } test "legacy default tag tails upgrade while custom tails remain owned" { @@ -998,120 +961,120 @@ test "legacy default tag tails upgrade while custom tails remain owned" { const terminal = p.panes[0].?; const terminal_old = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{ - try p.tagPrefix(terminal), - legacy_pane_tail, + try tagline.tagPrefix(p, terminal), + tagline.legacy_pane_tail, }); - p.restoreTail(terminal, terminal_old); + tagline.restoreTail(p, terminal, terminal_old); try std.testing.expect(terminal.tag.own == null); - try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(tagline.terminal_pane_tail, tagline.curTail(terminal)); const terminal_previous = try std.fmt.allocPrint(p.scratch.allocator(), "{s} New Del", .{ - try p.tagPrefix(terminal), + try tagline.tagPrefix(p, terminal), }); - p.restoreTail(terminal, terminal_previous); + tagline.restoreTail(p, terminal, terminal_previous); try std.testing.expect(terminal.tag.own == null); - try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(tagline.terminal_pane_tail, tagline.curTail(terminal)); const terminal_prefilter = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{ - try p.tagPrefix(terminal), - prev_terminal_pane_tail, + try tagline.tagPrefix(p, terminal), + tagline.prev_terminal_pane_tail, }); - p.restoreTail(terminal, terminal_prefilter); + tagline.restoreTail(p, terminal, terminal_prefilter); try std.testing.expect(terminal.tag.own == null); - try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(tagline.terminal_pane_tail, tagline.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); + for ([_][]const u8{ tagline.pre_mode_terminal_pane_tail, tagline.pre_tty_first_terminal_pane_tail, tagline.pre_collapse_terminal_pane_tail }) |old_tail| { + const old = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{ try tagline.tagPrefix(p, terminal), old_tail }); + tagline.restoreTail(p, terminal, old); try std.testing.expect(terminal.tag.own == null); - try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(tagline.terminal_pane_tail, tagline.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); + const custom_mode = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s} Keep", .{ try tagline.tagPrefix(p, terminal), tagline.pre_mode_terminal_pane_tail }); + tagline.restoreTail(p, terminal, custom_mode); try std.testing.expect(terminal.tag.own != null); - try std.testing.expectEqualStrings(pre_mode_terminal_pane_tail ++ " Keep", Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(tagline.pre_mode_terminal_pane_tail ++ " Keep", tagline.curTail(terminal)); 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), + try tagline.tagPrefix(p, terminal), }); - p.restoreTail(terminal, terminal_custom); + tagline.restoreTail(p, terminal, terminal_custom); try std.testing.expect(terminal.tag.own != null); - try std.testing.expectEqualStrings(" Keep Del", Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(" Keep Del", tagline.curTail(terminal)); if (terminal.tag.own) |own| p.gpa.free(own); terminal.tag.own = null; - p.restoreDumpTail(terminal, .{ + tagline.restoreDumpTail(p, terminal, .{ .kind = .terminal, .tag = "TTY /historical/cwd Keep Del", .body = "", .terminal = .{ .cwd = "/historical/cwd" }, }); try std.testing.expect(terminal.tag.own != null); - try std.testing.expectEqualStrings(" Keep Del", Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(" Keep Del", tagline.curTail(terminal)); if (terminal.tag.own) |own| p.gpa.free(own); terminal.tag.own = null; - p.restoreDumpTail(terminal, .{ + tagline.restoreDumpTail(p, terminal, .{ .kind = .terminal, .tag = "TTY /historical/cwd New Del", .body = "", .terminal = .{ .cwd = "/historical/cwd" }, }); try std.testing.expect(terminal.tag.own == null); - try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(tagline.terminal_pane_tail, tagline.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. 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), + try tagline.tagPrefix(p, terminal), }); - p.restoreTail(terminal, terminal_fileish); + tagline.restoreTail(p, terminal, terminal_fileish); try std.testing.expect(terminal.tag.own != null); - try std.testing.expectEqualStrings(" Save Del", Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(" Save Del", tagline.curTail(terminal)); // A savable file has a distinct old default. Save remains first after the // migration so the tag's established `:w` route is unchanged. const file = try p.setTestFile(""); const file_old = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{ - try p.tagPrefix(file), - legacy_file_pane_tail, + try tagline.tagPrefix(p, file), + tagline.legacy_file_pane_tail, }); - p.restoreTail(file, file_old); + tagline.restoreTail(p, file, file_old); try std.testing.expect(file.tag.own == null); - try std.testing.expectEqualStrings(" Save Tty Collapse Del", Pardes.curTail(file)); + try std.testing.expectEqualStrings(" Save Tty Collapse Del", tagline.curTail(file)); const file_custom = try std.fmt.allocPrint(p.scratch.allocator(), "{s} Save Mine Del", .{ - try p.tagPrefix(file), + try tagline.tagPrefix(p, file), }); - p.restoreTail(file, file_custom); + tagline.restoreTail(p, file, file_custom); try std.testing.expect(file.tag.own != null); - try std.testing.expectEqualStrings(" Save Mine Del", Pardes.curTail(file)); + try std.testing.expectEqualStrings(" Save Mine Del", tagline.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. 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), + try tagline.tagPrefix(p, file), }); - p.restoreTail(file, file_generic); + tagline.restoreTail(p, file, file_generic); try std.testing.expect(file.tag.own != null); - try std.testing.expectEqualStrings(" New Del", Pardes.curTail(file)); + try std.testing.expectEqualStrings(" New Del", tagline.curTail(file)); const image_doc = try panes.Image.create(p, 1, "/tmp/legacy image.ppm", &.{}); - try std.testing.expectEqualStrings(" Tty Collapse Del", Pardes.curTail(image_doc)); - p.restoreDumpTail(image_doc, .{ + try std.testing.expectEqualStrings(" Tty Collapse Del", tagline.curTail(image_doc)); + tagline.restoreDumpTail(p, image_doc, .{ .kind = .image, .tag = "img /tmp/legacy image.ppm Keep Del", .body = "", .image = .{ .path = "/tmp/legacy image.ppm" }, }); try std.testing.expect(image_doc.tag.own != null); - try std.testing.expectEqualStrings(" Keep Del", Pardes.curTail(image_doc)); + try std.testing.expectEqualStrings(" Keep Del", tagline.curTail(image_doc)); } test "Joincol folds the active column into its right neighbor, keeping its panes" { @@ -1245,19 +1208,19 @@ test "first document keeps its originating shell and only opens a column when it test "pane defaults keep creation of scratch panes in column tags" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true }); defer p.deinit(); - for ([_][]const u8{ pane_tail, file_pane_tail, pdf_pane_tail, terminal_pane_tail, config.topbar_str }) |tag| { + for ([_][]const u8{ tagline.pane_tail, tagline.file_pane_tail, tagline.pdf_pane_tail, tagline.terminal_pane_tail, config.topbar_str }) |tag| { var words = std.mem.tokenizeScalar(u8, tag, ' '); while (words.next()) |word| try std.testing.expect(!std.mem.eql(u8, word, "New")); } - try std.testing.expectEqualStrings("New Tty Find Grep Joincol Delcol", p.columnTag(0)); + try std.testing.expectEqualStrings("New Tty Find Grep Joincol Delcol", tagline.columnTag(p, 0)); const terminal = p.panes[0].?; - p.restoreTailAt(terminal, pre_column_terminal_pane_tail, "", .terminal); + tagline.restoreTailAt(p, terminal, tagline.pre_column_terminal_pane_tail, "", .terminal); try std.testing.expect(terminal.tag.own == null); - try std.testing.expectEqualStrings(terminal_pane_tail, Pardes.curTail(terminal)); + try std.testing.expectEqualStrings(tagline.terminal_pane_tail, tagline.curTail(terminal)); const file = try p.setTestFile("unchanged\n"); - p.restoreTailAt(file, pre_column_file_pane_tail, "", .file); + tagline.restoreTailAt(p, file, tagline.pre_column_file_pane_tail, "", .file); try std.testing.expect(file.tag.own == null); - try std.testing.expectEqualStrings(file_pane_tail, Pardes.curTail(file)); + try std.testing.expectEqualStrings(tagline.file_pane_tail, tagline.curTail(file)); } test "an unsaved file marker sits between its path and builtins until Save" { @@ -1267,29 +1230,29 @@ test "an unsaved file marker sits between its path and builtins until Save" { while (p.nextEffect()) |_| {} const pane = try p.setTestFile("before\n"); - const clean = try p.tagText(p.scratch.allocator(), pane); + const clean = try tagline.tagText(p, p.scratch.allocator(), pane); try std.testing.expect(std.mem.indexOf(u8, clean, "/test.txt *") == null); panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "after\n")); - const dirty = try p.tagText(p.scratch.allocator(), pane); + const dirty = try tagline.tagText(p, p.scratch.allocator(), pane); const marker_at = std.mem.indexOf(u8, dirty, "/test.txt *") orelse return error.MissingDirtyMarker; const save_at = std.mem.indexOf(u8, dirty, "Save") orelse return error.MissingSaveBuiltin; try std.testing.expect(marker_at < save_at); try std.testing.expect(p.executeBuiltinLine(0, "Save")); while (p.nextEffect()) |effect| p.perform(effect); - const saved = try p.tagText(p.scratch.allocator(), pane); + const saved = try tagline.tagText(p, p.scratch.allocator(), pane); try std.testing.expect(std.mem.indexOf(u8, saved, "/test.txt *") == null); panes.File.changed(p, 0, "external\n"); - const reloaded = try p.tagText(p.scratch.allocator(), pane); + const reloaded = try tagline.tagText(p, p.scratch.allocator(), pane); try std.testing.expect(std.mem.indexOf(u8, reloaded, "/test.txt *") == null); // A generated output is file-shaped and Save can write it to a path, but // there is no file of its own for it to be dirty against. pane.file.?.output = .{ .from = .search }; panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "result\n")); - const output = try p.tagText(p.scratch.allocator(), pane); + const output = try tagline.tagText(p, p.scratch.allocator(), pane); try std.testing.expect(std.mem.indexOf(u8, output, "/test.txt *") == null); } @@ -1422,7 +1385,7 @@ test "image dump restores source bytes renderer choices and exact custom tail" { 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.own != null); - try std.testing.expectEqualStrings(" Keep Del", Pardes.curTail(restored_pane)); + try std.testing.expectEqualStrings(" Keep Del", tagline.curTail(restored_pane)); try std.testing.expectEqualSlices(u8, source, restored_pane.image.?.raw); try dump.dumpState(restored); @@ -1903,7 +1866,7 @@ test "Save on an output buffer writes its rows out and leaves the buffer alone" defer gpa.free(rows); // Save leads its tagline now, and the path is REQUIRED: a bare Save asks - try std.testing.expectEqualStrings(file_pane_tail, Pardes.curTail(out)); + try std.testing.expectEqualStrings(tagline.file_pane_tail, tagline.curTail(out)); try std.testing.expect(p.executeBuiltinLine(id, "Save")); try std.testing.expect(out.prompt == .save); edit.insertKey(p, &out.input, .{ .cp = 'h', .text = "help.txt" }); @@ -2091,17 +2054,17 @@ test "Save reaches every tagline with text behind it and no other" { const out = try p.setTestFile("build.zig:1:1 pub fn main\n"); out.file.?.output = .{ .from = .search }; - try std.testing.expectEqualStrings(locations_pane_tail, Pardes.curTail(out)); + try std.testing.expectEqualStrings(tagline.locations_pane_tail, tagline.curTail(out)); // A dump written before Save reached output buffers carries the generic // tail. That is a DEFAULT and not something typed, so it upgrades. const dumped = try std.fmt.allocPrint(p.scratch.allocator(), "{s}{s}", .{ - try p.tagPrefix(out), - pane_tail, + try tagline.tagPrefix(p, out), + tagline.pane_tail, }); - p.restoreTail(out, dumped); + tagline.restoreTail(p, out, dumped); try std.testing.expect(out.tag.own == null); - try std.testing.expectEqualStrings(locations_pane_tail, Pardes.curTail(out)); + try std.testing.expectEqualStrings(tagline.locations_pane_tail, tagline.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. @@ -2109,18 +2072,18 @@ test "Save reaches every tagline with text behind it and no other" { 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, + try tagline.tagPrefix(p, out), + tagline.prev_file_pane_tail, }); - p.restoreTail(out, scratch_dumped); + tagline.restoreTail(p, out, scratch_dumped); try std.testing.expect(out.tag.own == null); - try std.testing.expectEqualStrings(" Save Tty Collapse Del", Pardes.curTail(out)); + try std.testing.expectEqualStrings(" Save Tty Collapse Del", tagline.curTail(out)); // An image's bytes on disk already are what they are: nothing of the // pane's own is unwritten, so the word is absent and inert. const img_id = p.freeSlot().?; const img = try panes.Image.create(p, img_id, "/tmp/pardes-tag.ppm", &.{}); - try std.testing.expectEqualStrings(" Tty Collapse Del", Pardes.curTail(img)); + try std.testing.expectEqualStrings(" Tty Collapse Del", tagline.curTail(img)); try std.testing.expect(p.executeBuiltinLine(img_id, "Save")); try std.testing.expect(img.prompt != .save); var buf: [256]u8 = undefined; @@ -2545,7 +2508,7 @@ comptime { const WordBounds = struct { lo: usize, hi: usize }; -fn wordBoundsAtCol(str: []const u8, col: usize) ?WordBounds { +pub fn wordBoundsAtCol(str: []const u8, col: usize) ?WordBounds { if (col >= str.len or str[col] == ' ') return null; var lo: usize = col; while (lo > 0 and str[lo - 1] != ' ') lo -= 1; @@ -2636,7 +2599,7 @@ test "Unicode display cells map back to body and tag byte cursors" { // 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.draftName(pane, 1); + tagline.draftName(p, 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); @@ -2644,15 +2607,15 @@ test "Unicode display cells map back to body and tag byte cursors" { try std.testing.expectEqual(@as(i32, 6), pane.input.cur_col); pane.closePrompt(); - const before = try gpa.dupe(u8, Pardes.curTail(pane)); + const before = try gpa.dupe(u8, tagline.curTail(pane)); defer gpa.free(before); - p.enterTag(pane); + tagline.enterTag(p, 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)); + try std.testing.expectEqualStrings(before, tagline.curTail(pane)); } test "tabbed file aligns syntax cursor and mouse at the nearest insertion gap" { @@ -2726,23 +2689,23 @@ test "editable workspace and column tags are typed into and persist" { 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 } }); p.update(.{ .key = .{ .cp = 'é', .text = "é" } }); - try std.testing.expect(std.mem.startsWith(u8, p.columnTag(0), "éNew")); + try std.testing.expect(std.mem.startsWith(u8, tagline.columnTag(p, 0), "éNew")); p.update(.{ .key = .{ .cp = Key.backspace } }); - try std.testing.expect(std.mem.startsWith(u8, p.columnTag(0), "New")); + try std.testing.expect(std.mem.startsWith(u8, tagline.columnTag(p, 0), "New")); p.update(.{ .paste = "Grep " }); - try std.testing.expect(std.mem.startsWith(u8, p.columnTag(0), "Grep New")); + try std.testing.expect(std.mem.startsWith(u8, tagline.columnTag(p, 0), "Grep New")); try std.testing.expectEqualStrings("untouched\n", p.panes[0].?.file.?.content); try dump.dumpState(p); const restored = try dump.restore(p, p.dump_out.?); defer restored.deinit(); 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.expectEqualStrings(tagline.columnTag(p, 0), tagline.columnTag(restored, 0)); 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(); - try std.testing.expectEqualStrings("", empty.columnTag(0)); + try std.testing.expectEqualStrings("", tagline.columnTag(empty, 0)); } test "column tags follow their column through split and close" { @@ -2752,12 +2715,12 @@ test "column tags follow their column through split and close" { 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.expectEqualStrings("Left Find", tagline.columnTag(p, 0)); 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); - try std.testing.expectEqualStrings("Right Grep", p.columnTag(0)); + try std.testing.expectEqualStrings("Right Grep", tagline.columnTag(p, 0)); } test "column tags render edit hover and scroll from the column edge" { @@ -2780,7 +2743,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(i32, 0), p.focusedHeader().?.cur_col); + try std.testing.expectEqual(@as(i32, 0), tagline.focusedHeader(p).?.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 } }); @@ -2790,7 +2753,7 @@ test "column tags render edit hover and scroll from the column edge" { 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 = Key.home } }); p.update(.{ .key = .{ .cp = 'H', .text = "Help " } }); - try std.testing.expect(std.mem.startsWith(u8, p.columnTag(column), "Help New Tty")); + try std.testing.expect(std.mem.startsWith(u8, tagline.columnTag(p, column), "Help New Tty")); const edited = try p.render(frame.allocator()); try std.testing.expectEqual(x + 5, edited.cursor.?.x); // Only the text viewport participates in caret reveal. @@ -2844,7 +2807,7 @@ test "header clicks beyond text append and long UTF-8 tags reveal their caret" { p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = 40, .row = TOPBAR_H } }); p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = 40, .row = TOPBAR_H } }); p.update(.{ .key = .{ .cp = 'x', .text = " extended" } }); - try std.testing.expectEqualStrings("New extended", p.columnTag(0)); + try std.testing.expectEqualStrings("New extended", tagline.columnTag(p, 0)); p.update(.{ .paste = " 界界界界界界界界界界界界界界界界界界界界界界界界界界界界界界" }); const frame = try p.render(p.scratch.allocator()); try std.testing.expect(p.header_scroll > 0); @@ -2866,7 +2829,7 @@ test "a column tag with a newline in it takes a row per line and pushes its pane p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = 40, .row = TOPBAR_H } }); p.update(.{ .key = .{ .cp = Key.enter } }); p.update(.{ .key = .{ .cp = 'S', .text = "Snarf" } }); - try std.testing.expectEqualStrings("New\nSnarf", p.columnTag(0)); + try std.testing.expectEqualStrings("New\nSnarf", tagline.columnTag(p, 0)); try std.testing.expectEqual(@as(u16, 2), p.columnBarHeight()); const frame = try p.render(p.scratch.allocator()); try std.testing.expectEqual(TOPBAR_H + 2, p.rects[0].y); @@ -2884,7 +2847,7 @@ test "a column tag with a newline in it takes a row per line and pushes its pane // Taking the newline back out gives the panes their row again. p.update(.{ .key = .{ .cp = Key.home } }); p.update(.{ .key = .{ .cp = Key.backspace } }); - try std.testing.expectEqualStrings("NewSnarf", p.columnTag(0)); + try std.testing.expectEqualStrings("NewSnarf", tagline.columnTag(p, 0)); _ = try p.render(p.scratch.allocator()); try std.testing.expectEqual(TOPBAR_H + COLBAR_H, p.rects[0].y); } @@ -2916,7 +2879,7 @@ test "ColumnTags reclaims the row and releases hidden header focus without losin try std.testing.expectEqual(shown.h + COLBAR_H, p.rects[0].h); 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)); + try std.testing.expectEqualStrings("New Help", tagline.columnTag(p, 0)); p.update(.{ .command = "ColumnTags" }); try std.testing.expect(p.settings.column_tags); @@ -2932,7 +2895,7 @@ test "ColumnTags reclaims the row and releases hidden header focus without losin 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("New Help", tagline.columnTag(p, 0)); try std.testing.expectEqualStrings("unchanged body\n", pane.file.?.content); } @@ -2940,7 +2903,7 @@ test "a header's execute key runs the word under its cursor and lets go of the k const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 12, .tty_only = true }); defer p.deinit(); _ = try p.setTestFile("body\n"); - p.enterHeader(null); + tagline.enterHeader(p, 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); @@ -4082,23 +4045,6 @@ pub const Pardes = struct { return a; } - /// 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's height: a row per line of it while the setting /// keeps it, zero once a native shell takes its commands over. Layout and /// hit testing read this rather than the constant, the way they read @@ -4119,36 +4065,6 @@ pub const Pardes = struct { return @intCast(@min(lines, MAX_TAG_ROWS, @max(COLBAR_H, p.screen_h / 3))); } - pub fn columnTag(p: *const Pardes, c: usize) []const u8 { - return p.col_tags[c].own orelse column_tag_default; - } - - /// 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 t = p.focusedHeader() orelse { - p.header_scroll = 0; - return; - }; - const text = edit.flatSurface(p, t) catch return; - const line = modal.lineSlice(text, @intCast(@max(0, t.cur_row))); - 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(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(line, p.header_scroll); - p.header_scroll = panes.File.rawDisplayCol(line, raw); - if (width > 0 and col >= p.header_scroll + width) { - raw = modal.nextGrapheme(line, raw); - p.header_scroll = panes.File.rawDisplayCol(line, raw); - } - } - fn detachCwds(p: *Pardes, parents: []const *Pane) !void { var copies: [MAX_PANES]?[]u8 = @splat(null); errdefer for (copies) |copy| if (copy) |bytes| p.gpa.free(bytes); @@ -4834,7 +4750,7 @@ pub const Pardes = struct { for (p.panes, 0..) |slot, id| { const pane = slot orelse continue; if (pane.fs.readers == 0) continue; - const tag = p.tagText(p.scratch.allocator(), pane) catch continue; + const tag = tagline.tagText(p, p.scratch.allocator(), pane) catch continue; const snap = &pane.fs.tag_snap; if (std.mem.eql(u8, snap.items, tag)) continue; if (snap.capacity != 0 or snap.items.len != 0) @@ -4846,39 +4762,6 @@ pub const Pardes = struct { // ---- tag + selection text (chord sources) ---- - pub fn tagPrefix(p: *Pardes, pane: *Pane) ![]u8 { - const arena = p.scratch.allocator(); - if (comptime pdf_enabled) if (pane.pdf) |pv| return std.fmt.allocPrint( - arena, - "{s} [{d}/{d}]", - .{ pv.path, pv.page + 1, pv.page_count }, - ); - if (pane.image) |*state| return panes.Image.tagPrefix(arena, state); - if (pane.file) |f| { - 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); - } - return arena.dupe(u8, pane.cwdSlice()); - } - - /// 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 { - if (comptime pdf_enabled) if (pane.pdf != null) return pdf_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; - if (pane.file != null) return file_pane_tail; - if (pane.isTerminal()) return terminal_pane_tail; - return pane_tail; - } - pub fn paneIdOf(p: *const Pardes, pane: *const Pane) ?usize { for (p.panes, 0..) |slot, id| if (slot) |sp| { if (sp == pane) return id; @@ -4886,168 +4769,13 @@ 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); - const out = try arena.alloc(u8, prefix.len + tail.len); - @memcpy(out[0..prefix.len], prefix); - @memcpy(out[prefix.len..], tail); - return out; - } - - fn tagTintRange(pane: *const Pane, tag: []const u8, prefix_len: usize) ?struct { lo: usize, hi: usize } { - if (pane.isTerminal()) { - var words = std.mem.tokenizeAny(u8, tag[prefix_len..], " \t\r\n"); - while (words.next()) |word| { - if (!std.mem.eql(u8, word, "Tty")) continue; - const lo = @intFromPtr(word.ptr) - @intFromPtr(tag.ptr); - return .{ .lo = lo, .hi = lo + word.len }; - } - return null; - } - var start: usize = 0; - const name = if (pane.file) |file| - 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; - break :blk state.path; - } else if (comptime pdf_enabled) blk: { - break :blk if (pane.pdf) |state| state.path else return null; - } else return null; - const basename = if (std.mem.lastIndexOfScalar(u8, name, '/')) |slash| slash + 1 else 0; - if (basename == name.len) return null; - return .{ .lo = start + basename, .hi = start + name.len }; - } - - /// 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 (!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); - pane.tag_scroll = @intCast(panes.File.displayWidth(line) + 1 -| width); - } - } - // 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 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 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 - /// 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 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 { - if (pane.prompt != .name) return true; - const id = p.paneIdOf(pane) orelse return false; - 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; - } - for (name) |byte| if (byte < ' ') { - p.reportError(id, "name", error.InvalidName); - return false; - }; - const full = std.fs.path.resolvePosix(p.scratch.allocator(), &.{ paneDir(pane), name }) catch |err| { - p.reportError(id, "name", err); - return false; - }; - ctlfs.pane.nameBuffer(p, id, full, true) catch |err| { - p.reportError(id, "name", err); - return false; - }; - pane.closePrompt(); - return true; - } - - pub fn exitHeader(p: *Pardes) void { - p.header_focus = false; - p.header_column = null; - p.header_drag = false; - p.header_scroll = 0; - } - - /// 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 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. 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 = pane.body.mode; p.active = id; - p.exitHeader(); + tagline.exitHeader(p); pane.focus = .body; pane.closePrompt(); switch (previous) { @@ -5068,7 +4796,7 @@ pub const Pardes = struct { const pane = p.panes[id] orelse return; if (!pane.isTerminal()) return; p.active = id; - p.exitHeader(); + tagline.exitHeader(p); pane.focus = .body; pane.closePrompt(); if (pane.body.mode == .tty) { @@ -5089,7 +4817,7 @@ pub const Pardes = struct { return; } const pane = p.panes[p.active] orelse return; - const header = p.focusedHeader(); + const header = tagline.focusedHeader(p); 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; @@ -5136,7 +4864,7 @@ pub const Pardes = struct { // 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(); + tagline.exitHeader(p); const free = p.freeSlot() orelse return; const nt = p.newShell(free, "") catch return; nt.greet = true; @@ -5150,11 +4878,11 @@ pub const Pardes = struct { } for (config.jump_keys) |jk| { if (!hit(key, &.{jk.chord})) continue; - p.exitHeader(); + tagline.exitHeader(p); return exec.runBuiltin(p, jk.cmd, p.active, "", null); } if (hit(key, config.pane_to_new_column)) { - p.exitHeader(); + tagline.exitHeader(p); 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); @@ -5170,7 +4898,7 @@ pub const Pardes = struct { // 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; + if (tagline.commitTagName(p, pane)) pane.focus = .body; return; } if (hit(key, config.escape)) { @@ -5209,7 +4937,7 @@ pub const Pardes = struct { // 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 shown = if (t.what == .tag) tagline.tagText(p, 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); @@ -5221,7 +4949,7 @@ pub const Pardes = struct { }; // 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 (header != null) tagline.exitHeader(p) else pane.focus = .body; if (txt.len > 0) exec.runBuiltin(p, cmd, p.active, "", txt); return; } @@ -5615,90 +5343,6 @@ pub const Pardes = struct { // ---- dump / load (acme-style: `pardes -l state.zon` restores a session) ---- - pub fn restoreDumpTail(p: *Pardes, pane: *Pane, src: dump.Pane) void { - if (src.tag_tail) |tail| { - pane.tag.own = p.gpa.dupe(u8, tail) catch return; - return; - } - const tail_class = tailClass(pane); - if (src.kind == .image and panes.Pdf.isPath(src.image.?.path)) { - if (panes.Pdf.legacySavedPrefix(src.image.?.path, src.tag)) |prefix| - return p.restoreTailAt(pane, src.tag, prefix, .generic); - } - if (src.kind == .terminal and std.mem.startsWith(u8, src.tag, "TTY ")) { - const legacy = std.fmt.allocPrint(p.scratch.allocator(), "TTY {s}", .{src.terminal.?.cwd}) catch return; - if (std.mem.startsWith(u8, src.tag, legacy)) - return p.restoreTailAt(pane, src.tag, legacy, .terminal); - } - const current = p.tagPrefix(pane) catch return; - if (std.mem.startsWith(u8, src.tag, current)) - return p.restoreTailAt(pane, src.tag, savedPrefix(src.tag, current, tail_class), tail_class); - if (src.kind != .image) return; - const saved = src.image.?; - if (pane.image) |*state| if (panes.Image.legacySavedPrefix(state, src.tag)) |legacy| - return p.restoreTailAt(pane, src.tag, legacy, .generic); - if (panes.Pdf.isPath(saved.path)) if (panes.Pdf.legacySavedPrefix(saved.path, src.tag)) |legacy| - p.restoreTailAt(pane, src.tag, legacy, .generic); - } - - fn restoreTail(p: *Pardes, pane: *Pane, saved_tag: []const u8) void { - const pfx = p.tagPrefix(pane) catch return; - const class = tailClass(pane); - p.restoreTailAt(pane, saved_tag, savedPrefix(saved_tag, pfx, class), class); - } - - const TailClass = enum { generic, file, output, terminal }; - - fn tailClass(pane: *const Pane) TailClass { - if (pane.file) |f| return if (f.output == null) .file else .output; - if (pane.isTerminal()) return .terminal; - return .generic; - } - - fn savedPrefix(saved_tag: []const u8, live: []const u8, class: TailClass) []const u8 { - if (class == .generic or class == .terminal) return live; - if (!std.mem.startsWith(u8, saved_tag, live)) return live; - const marked_len = live.len + dirty_marker.len; - if (saved_tag.len >= marked_len and std.mem.eql(u8, saved_tag[live.len..marked_len], dirty_marker)) - return saved_tag[0..marked_len]; - return live; - } - - fn restoreTailAt( - p: *Pardes, - pane: *Pane, - saved_tag: []const u8, - pfx: []const u8, - class: TailClass, - ) void { - if (!std.mem.startsWith(u8, saved_tag, pfx)) return; - const rest = saved_tag[pfx.len..]; - const said = std.mem.trimStart(u8, rest, " "); - const defaults: []const []const u8 = switch (class) { - .generic => &.{ pdf_pane_tail, pane_tail, pre_close_last_pdf_pane_tail, pre_close_last_pane_tail, pre_collapse_pdf_pane_tail, pre_collapse_pane_tail, pre_column_pdf_pane_tail, pre_column_pane_tail, prev_pane_tail, legacy_pane_tail }, - .file => &.{ context_pane_tail, file_pane_tail, pre_close_last_file_pane_tail, pre_collapse_file_pane_tail, pre_column_file_pane_tail, prev_file_pane_tail, legacy_file_pane_tail }, - .output => &.{ - locations_pane_tail, - file_pane_tail, - pre_close_last_file_pane_tail, - pre_close_last_pane_tail, - prev_file_pane_tail, - legacy_file_pane_tail, - pane_tail, - prev_pane_tail, - legacy_pane_tail, - pre_column_file_pane_tail, - pre_column_pane_tail, - pre_collapse_file_pane_tail, - pre_collapse_pane_tail, - }, - .terminal => &.{ terminal_pane_tail, pre_close_last_terminal_pane_tail, pre_close_last_pane_tail, pre_mode_terminal_pane_tail, pre_tty_first_terminal_pane_tail, pre_collapse_terminal_pane_tail, pre_column_terminal_pane_tail, pre_tty_terminal_pane_tail, prev_terminal_pane_tail, legacy_terminal_pane_tail, pane_tail, pre_collapse_pane_tail, pre_column_pane_tail, prev_pane_tail, legacy_pane_tail }, - }; - for (defaults) |default| - if (std.mem.eql(u8, said, std.mem.trimStart(u8, default, " "))) return; - pane.tag.own = p.gpa.dupe(u8, rest) catch return; - } - /// Close a pane; its rows go to `to`, or where layout.absorbVWeight /// sends them when that is null. pub fn removePane(p: *Pardes, id: usize, to: ?usize) !void { @@ -5854,7 +5498,7 @@ pub const Pardes = struct { /// deferred greetings. The mirror of the prototype's loop epilogue. pub fn sync(p: *Pardes) void { if (p.header_column != null and p.columnBarHeight() == 0) { - p.exitHeader(); + tagline.exitHeader(p); } p.reapPanes(); layout.compute(p); @@ -5886,7 +5530,7 @@ pub const Pardes = struct { 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; + const lines = std.mem.count(u8, tagline.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); @@ -5976,7 +5620,7 @@ pub const Pardes = struct { 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 { + pub fn tagCapacity(p: *const Pardes, physical_width: u16) u16 { const layer: TagLayer = .{ .viewport = .{ .x = 0, .y = 0, .w = physical_width, .h = 1 } }; return layer.capacity(p.row_metrics); } @@ -6107,110 +5751,8 @@ pub const Pardes = struct { } } - // global tagbar: full width, top rows — unless a native shell has - // taken its commands over, in which case the rows are not ours to draw - p.revealHeader(); - const global = p.topbar(); - const global_rows = p.topBarHeight(); - 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, global_rows, .{ - .bg = .{ .rgb = chrome.tag_bg }, - .font_role = .tagline, - }); - for (0..global_rows) |row| { - const line = modal.lineSlice(global, row); - _ = s.print(0, @intCast(row), s.cols, line[panes.File.rawAtDisplay(line, global_scroll)..], .{ - .fg = .{ .rgb = chrome.tag_fg }, - .bg = .{ .rgb = chrome.tag_bg }, - .font_role = .tagline, - }); - } - } - if (p.pointer_inside and p.hover_row < global_rows) { - const bar = modal.lineSlice(global, p.hover_row); - 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; - while (col < hi and col < s.cols) : (col += 1) { - const cell = s.at(@intCast(col), p.hover_row); - cell.default = false; - cell.style.bg = .{ .rgb = th.sel_bg }; - cell.style.fg = .{ .rgb = th.sel_fg }; - } - } - } - const column_rows = p.columnBarHeight(); - if (column_rows > 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]); - const x = p.col_x[c] + inset; - const w = p.col_w[c] - inset; - const y0 = global_rows; - if (p.col_w[c] == 0 or p.col_x[c] >= s.cols) continue; - const active_col = if (layout.findPane(p, p.active)) |f| f.col == c else false; - const bg = if (active_col and p.settings.focus_tint) chrome.tag_active_bg else chrome.tag_bg; - const fg = if (active_col and p.settings.focus_tint) chrome.tag_active_fg else chrome.tag_fg; - // A grip is muted until it is grabbed; then it lights, as a pane's - // box does for the active pane, so the drag shows what it holds. - const grabbed = p.drag == .column_move and layout.columnBySerial(p, p.drag.column_move.serial) == c; - const grip_bg = if (grabbed) chrome.column_box else chrome.column_box_dim; - const lum = (@as(u16, grip_bg[0]) * 3 + @as(u16, grip_bg[1]) * 6 + @as(u16, grip_bg[2])) / 10; - const ink: [3]u8 = if (lum > 140) .{ 0, 0, 0 } else .{ 255, 255, 255 }; - const grip_style: CellStyle = .{ .bg = .{ .rgb = grip_bg }, .fg = .{ .rgb = ink }, .font_role = .tagline }; - s.fill(p.col_x[c], y0, grip, column_rows, grip_style); - s.fill(p.col_x[c] + grip, y0, inset - grip, column_rows, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); - - s.fill(x, y0, w, column_rows, .{ .bg = .{ .rgb = bg }, .font_role = .tagline }); - const bar_scroll = if (p.header_focus and p.header_column == c) p.header_scroll else 0; - const tag = p.columnTag(c); - for (0..column_rows) |row| { - const line = modal.lineSlice(tag, row); - _ = s.print(x, y0 + @as(u16, @intCast(row)), w, line[panes.File.rawAtDisplay(line, bar_scroll)..], .{ - .fg = .{ .rgb = fg }, - .bg = .{ .rgb = bg }, - .font_role = .tagline, - }); - } - // 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 >= y0 and p.hover_row < y0 + column_rows and p.hover_col >= x and p.hover_col < x + w) { - const bar = modal.lineSlice(tag, p.hover_row - y0); - 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; - while (col < hi and col < w) : (col += 1) { - const cell = s.at(x + @as(u16, @intCast(col)), p.hover_row); - cell.style.bg = .{ .rgb = th.sel_bg }; - cell.style.fg = .{ .rgb = th.sel_fg }; - } - } - } - }; - if (p.focusedHeader()) |t| { - const text = try edit.flatSurface(p, t); - 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) global_rows else 0; - const rows = if (p.header_column != null) column_rows else global_rows; - for (0..rows) |row| { - const bar = modal.lineSlice(text, row); - const span = headerSelection(t, text, row) orelse continue; - 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 + @as(u16, @intCast(row))); - cell.style.fg = .{ .rgb = th.sel_fg }; - cell.style.bg = .{ .rgb = th.sel_bg }; - } - } - if (t.cur_row >= 0 and t.cur_row < rows) { - const bar = modal.lineSlice(text, @intCast(t.cur_row)); - 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 + @as(u16, @intCast(t.cur_row)), .bar = t.mode == .insert }; - } - } - - try p.renderTagLayers(arena); + try body_layer.paintHeaders(p); + try body_layer.renderTagLayers(p, arena); switch (p.drag) { .border_v => |d| { @@ -6450,204 +5992,6 @@ pub const Pardes = struct { return !cell.default and !(cell.len == 1 and cell.text[0] == ' '); } - fn renderTagLayers(p: *Pardes, arena: std.mem.Allocator) !void { - const chrome = p.chromeTheme(); - 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 == 0) continue; - const tag = try p.tagText(arena, pane); - 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 = rows, .cells = storage }; - std.mem.swap(Surface, &p.surface, &temporary); - 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); - // 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. - if (p.settings.workspace_tag) { - for (0..p.topBarHeight()) |line| { - const index = if (line == 0) MAX_PANES + MAX_COLS else HEADER_LINE_LAYER_BASE + MAX_COLS * (MAX_TAG_ROWS - 1) + line - 1; - try p.renderHeaderLayer(arena, index, .workspace, 0, @intCast(line), .{ .x = 0, .y = @intCast(line), .w = p.screen_w, .h = TOPBAR_H }, modal.lineSlice(p.topbar(), line), 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 - // band offset and the border -- none of which a body-grid row can have - // just by wearing a tagline font. The geometry is the one the grid - // pass already chose and recorded, so the two cannot disagree and the - // GUI's "skip the cells a tag layer covers" leaves no stub behind. - // A prompt is one of them too: left on the grid, a pixel shell drew - // its tagline glyphs one to a BODY cell, spaced out like a banner. - 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 <= 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); - if (text.len == 0) continue; - const cx = pane.notices.left[i]; - if (cx == std.math.maxInt(u16) or cx >= r.x + r.w) continue; - const chip = r.x + r.w - cx; - // Right aligned inside the chip, a blank cell short of its - // edge: the same one the grid pass leaves for a prompt caret. - // Wider than the chip, the text loses its head, as on the grid. - const room = p.tagCapacity(chip) -| 1; - const shown = panes.File.displayWidth(text); - var kept = text; - if (shown > room) { - var start = panes.File.rawAtDisplay(text, shown - room); - if (panes.File.rawDisplayCol(text, start) < shown - room) start = panes.File.rawAtDisplay(text, shown - room + 1); - kept = text[start..]; - } - const pad = room -| panes.File.displayWidth(kept); - const line = try arena.alloc(u8, pad + kept.len); - @memset(line[0..pad], ' '); - @memcpy(line[pad..], kept); - // A pixel shell slides the message in as it fades up, and - // fades it on the way out. - const motion: Messages.MessageMotion = if (Messages.noticeLife(pane, i)) |life| Messages.messageMotion(p, life) else .{}; - const fade = motion.alpha; - const page = p.theme().bg orelse chrome.tag_bg; - const layer_index = NOTICE_LAYER_BASE + id * Pane.Notices.max + i; - try p.renderHeaderLayer(arena, layer_index, .notice, @intCast(id), 0, .{ - .x = cx, - .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)); - 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; - 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.input.mode == .insert }; - } - } - 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; - for (0..p.columnBarHeight()) |line| { - const index = if (line == 0) MAX_PANES + column else HEADER_LINE_LAYER_BASE + column * (MAX_TAG_ROWS - 1) + line - 1; - try p.renderHeaderLayer(arena, index, .column, @intCast(column), @intCast(line), .{ .x = p.col_x[column] + @min(TAG_TEXT_INSET, p.col_w[column]), .y = p.topBarHeight() + @as(u16, @intCast(line)), .w = p.col_w[column] -| TAG_TEXT_INSET, .h = COLBAR_H }, modal.lineSlice(p.columnTag(column), line), 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 line `row` of its text, in - /// that line's bytes: up to the caret while typing, and over the - /// cursor's own cell too in normal mode, where a cursor is a cell. - pub fn headerSelection(t: *const Text, text: []const u8, row: usize) ?struct { lo: usize, hi: usize } { - if (!t.vsel.active) return null; - const anchor = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.vsel.row)), .col = @intCast(@max(0, t.vsel.col)) }); - const cursor = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) }); - const lo = @min(anchor, cursor); - const hi = if (t.mode == .insert) @max(anchor, cursor) else modal.nextGrapheme(text, @max(anchor, cursor)); - const start = modal.lineStartOffset(text, row); - const end = modal.lineEndOffset(text, row); - if (hi <= start or lo >= end) return null; - return .{ .lo = @max(lo, start) - start, .hi = @min(hi, end) - start }; - } - - /// One row of a header or a notice band as a tag layer: `text` is line - /// `line` of what it shows. - fn renderHeaderLayer(p: *Pardes, arena: std.mem.Allocator, index: usize, kind: TagKind, id: u16, line: u16, viewport: Rect, text: []const u8, bg: [3]u8, fg: [3]u8) !void { - _ = arena; - const layer = &p.surface.tag_layers[index]; - if (viewport.w == 0) { - layer.cols = 0; - return; - } - const columns: u16 = @intCast(@min(std.math.maxInt(u16), @max(p.tagCapacity(viewport.w), panes.File.displayWidth(text) + 1))); - if (layer.cells.len != columns) layer.cells = try p.gpa.realloc(layer.cells, columns); - layer.kind = kind; - layer.id = id; - layer.line = line; - layer.serial = if (kind == .column) p.col_serial[id] else 0; - layer.viewport = viewport; - layer.cols = columns; - layer.bg = bg; - layer.cursor = null; - layer.slide = 0; - layer.fade = 1; - var surface: Surface = .{ .cols = columns, .rows = 1, .cells = layer.cells }; - // 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: ?*Text = if (p.header_focus and switch (kind) { - .workspace => p.header_column == null, - .column => p.header_column == id, - .pane, .notice => false, - }) 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) |t| { - if (headerSelection(t, try edit.flatSurface(p, t), line)) |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, @min(@as(usize, @intCast(@max(0, t.cur_col))), text.len)) -| scroll; - if (t.cur_row == line 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| - (if (pointer.kind == kind and pointer.id == id and pointer.line == line) pointer.col else null) - else if (p.hover_row == viewport.y and p.hover_col >= viewport.x and p.hover_col - viewport.x < viewport.w) - p.hover_col - viewport.x - else - null; - if (col) |hover| if (wordBoundsAtCol(text, panes.File.rawAtDisplay(text, hover + scroll))) |bounds| { - var cell = panes.File.rawDisplayCol(text, bounds.lo) -| scroll; - const end = panes.File.rawDisplayCol(text, bounds.hi) -| scroll; - while (cell < end and cell < columns) : (cell += 1) { - surface.at(@intCast(cell), 0).style.bg = .{ .rgb = p.theme().sel_bg }; - surface.at(@intCast(cell), 0).style.fg = .{ .rgb = p.theme().sel_fg }; - } - }; - } - } - fn renderPane(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool) !void { const tz = tracy.zone(@src(), "renderPane"); defer tz.end(); @@ -6687,7 +6031,7 @@ pub const Pardes = struct { .tty => config.tag_tty, }, box_style); - try p.paintPaneTag(arena, pane, r, id, active, p.tagCapacity(r.w -| TAG_TEXT_INSET)); + try body_layer.paintPaneTag(p, 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. @@ -6714,127 +6058,6 @@ pub const Pardes = struct { try body_layer.renderBody(p, arena, pane, r, id, active, true); } - fn paintPaneTag(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, r: Rect, id: usize, active: bool, capacity: u16) !void { - const s = &p.surface; - const th = p.theme(); - const chrome = p.chromeTheme(); - const tx = r.x + @min(TAG_TEXT_INSET, r.w); - const tw = r.w -| TAG_TEXT_INSET; - 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; - const tag_fg = if (active and p.settings.focus_tint) chrome.tag_active_fg else chrome.tag_fg; - 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), 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; - // 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) - .{ .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 (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; - 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, 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; - const end = panes.File.rawDisplayCol(tag, hi) -| pane.tag_scroll; - const name_fg = if (active and p.settings.focus_tint) chrome.tag_active_name_fg else chrome.tag_name_fg; - while (col < end and col < tw) : (col += 1) - s.at(tx + @as(u16, @intCast(col)), tag_y).style.fg = .{ .rgb = name_fg }; - } - } - 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); - }; - } - // 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); - 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) 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| { - 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 + @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) >= rows) continue; - body_layer.paintPointerSelection(p, pane, r, tx, tw, tag_y, body_y, selection, th.sel_bg, th.sel_fg); - } - } - pub fn appendImagePlace(p: *Pardes, place: ImagePlace) bool { const s = &p.surface; if (s.nimages == s.images.len) { @@ -6954,7 +6177,7 @@ 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.enterTag(pane); + tagline.enterTag(p, 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); pane.focus = .body; diff --git a/src/tag_layer.zig b/src/tag_layer.zig index ac7c4ac2..7cfe5bbf 100644 --- a/src/tag_layer.zig +++ b/src/tag_layer.zig @@ -78,3 +78,28 @@ test "tag text capacity uses its own pitch and excludes the physical grip" { try std.testing.expect(layer.hitAt(120, 85, std.math.nan(f32), 20, 6, 12) == null); try std.testing.expect(layer.hitAt(120, 85, 10, 20, 0, 12) == null); } + +/// Whether two pointer hits name the same cell of the same tag line. +pub fn sameCell(a: ?Hit, b: ?Hit) bool { + const first = a orelse return b == null; + const second = b orelse return false; + return first.kind == second.kind and first.id == second.id and first.serial == second.serial and first.line == second.line and first.col == second.col; +} + +/// 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 columnAt(p: *const pardes.Pardes, kind: Kind, id: usize, supplied: ?Hit, 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 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; + const right = @as(f32, @floatFromInt(layer.viewport.x + layer.viewport.w)) * bw; + point.pixel_x = std.math.clamp(point.pixel_x, left, @max(left, right - 0.001)); + point.pixel_y = (@as(f32, @floatFromInt(layer.viewport.y)) + 0.5) * bh; + break; + }; + return if (p.reprojectTagHit(point)) |mapped| mapped.col else null; +} diff --git a/src/tagline.zig b/src/tagline.zig new file mode 100644 index 00000000..1021e9db --- /dev/null +++ b/src/tagline.zig @@ -0,0 +1,360 @@ +//! The tags (acme's tag half of wind.c): a pane's computed prefix and its +//! default and saved tails, going into a tag and out again, the path drafted +//! as a new name, and the column and workspace tags above the panes. +const pardes = @import("pardes.zig"); +const std = @import("std"); +const modal = @import("modal.zig"); +const ctlfs = @import("ninep/tree.zig"); +const panes = @import("panes.zig"); +const edit = @import("edit.zig"); +const config = @import("config.zig"); +const pdf_enabled = panes.Pdf.enabled; +const dump = @import("dump.zig"); +const Pane = panes.Pane; +const Text = panes.Text; +const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; +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"; +pub const terminal_pane_tail = " " ++ config.terminal_pane_builtins_str; +const dirty_marker = " *"; +pub const legacy_pane_tail = " Del"; +pub const legacy_file_pane_tail = " Save Del"; +// The defaults from the release before Newtty joined every tagline. Recognized +// so a dump written then upgrades instead of keeping the old word as a tail. +const prev_pane_tail = " New Del"; +pub const prev_file_pane_tail = " Save New Del"; +const legacy_terminal_pane_tail = " New Del Filter"; +// ...and the terminal default from the release before Save reached it, when a +// scrollback was not yet something you could write to a path. +pub const prev_terminal_pane_tail = " New Newtty Del Filter"; +const pre_tty_terminal_pane_tail = " Save New Newtty Del Filter"; +const pre_column_pane_tail = " New Newtty Del"; +pub const pre_column_file_pane_tail = " Save New Newtty Del"; +const pre_column_pdf_pane_tail = " New Newtty Del PdfSections PdfTint"; +pub const pre_column_terminal_pane_tail = " Save New Newtty Del Tty Filter"; +const pre_collapse_pane_tail = " Tty Del"; +pub const pre_collapse_file_pane_tail = " Save Tty Del"; +const pre_collapse_pdf_pane_tail = " Tty Del PdfSections PdfTint"; +pub const pre_collapse_terminal_pane_tail = " Save Tty Del Togglettymode Filter"; +pub const pre_tty_first_terminal_pane_tail = " Save Tty Del Togglettymode Filter Collapse"; +pub const pre_mode_terminal_pane_tail = " Tty Save Del Togglettymode Filter Collapse"; +// ...and the defaults from before the closing word moved to the end of every +// tagline, where a click cannot land on it by overshooting the one before. +const pre_close_last_pane_tail = " Tty Del Collapse"; +const pre_close_last_file_pane_tail = " Save Tty Del Collapse"; +const pre_close_last_pdf_pane_tail = " Tty Del PdfSections PdfTint Collapse"; +const pre_close_last_terminal_pane_tail = " Tty Save Del Mode Filter Collapse"; + +/// 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 +pub fn topbar(p: *Pardes) []const u8 { + return p.global_tag.own orelse headerDefault(p, .workspace); +} + +pub fn columnTag(p: *const Pardes, c: usize) []const u8 { + return p.col_tags[c].own orelse column_tag_default; +} + +/// 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; +} + +pub fn revealHeader(p: *Pardes) void { + const t = focusedHeader(p) orelse { + p.header_scroll = 0; + return; + }; + const text = edit.flatSurface(p, t) catch return; + const line = modal.lineSlice(text, @intCast(@max(0, t.cur_row))); + 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(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(line, p.header_scroll); + p.header_scroll = panes.File.rawDisplayCol(line, raw); + if (width > 0 and col >= p.header_scroll + width) { + raw = modal.nextGrapheme(line, raw); + p.header_scroll = panes.File.rawDisplayCol(line, raw); + } +} + +pub fn tagPrefix(p: *Pardes, pane: *Pane) ![]u8 { + const arena = p.scratch.allocator(); + if (comptime pdf_enabled) if (pane.pdf) |pv| return std.fmt.allocPrint( + arena, + "{s} [{d}/{d}]", + .{ pv.path, pv.page + 1, pv.page_count }, + ); + if (pane.image) |*state| return panes.Image.tagPrefix(arena, state); + if (pane.file) |f| { + 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); + } + return arena.dupe(u8, pane.cwdSlice()); +} + +/// 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 { + if (comptime pdf_enabled) if (pane.pdf != null) return pdf_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; + if (pane.file != null) return file_pane_tail; + if (pane.isTerminal()) return terminal_pane_tail; + return pane_tail; +} + +/// 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; +} + +/// 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 (!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 = tagText(p, 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); + pane.tag_scroll = @intCast(panes.File.displayWidth(line) + 1 -| width); + } + } + // 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 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(tagPrefix(p, pane) catch return null) else 0; + if (col < width) return null; + 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 +/// 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 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 { + if (pane.prompt != .name) return true; + const id = p.paneIdOf(pane) orelse return false; + 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; + } + for (name) |byte| if (byte < ' ') { + p.reportError(id, "name", error.InvalidName); + return false; + }; + const full = std.fs.path.resolvePosix(p.scratch.allocator(), &.{ Pardes.paneDir(pane), name }) catch |err| { + p.reportError(id, "name", err); + return false; + }; + ctlfs.pane.nameBuffer(p, id, full, true) catch |err| { + p.reportError(id, "name", err); + return false; + }; + pane.closePrompt(); + return true; +} + +pub fn exitHeader(p: *Pardes) void { + p.header_focus = false; + p.header_column = null; + p.header_drag = false; + p.header_scroll = 0; +} + +/// 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 { + exitHeader(p); + if (p.panes[p.active]) |pane| pane.focus = .body; + p.header_focus = true; + p.header_column = column; + const t = focusedHeader(p) orelse return exitHeader(p); + 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(); +} + +pub fn restoreDumpTail(p: *Pardes, pane: *Pane, src: dump.Pane) void { + if (src.tag_tail) |tail| { + pane.tag.own = p.gpa.dupe(u8, tail) catch return; + return; + } + const tail_class = tailClass(pane); + if (src.kind == .image and panes.Pdf.isPath(src.image.?.path)) { + if (panes.Pdf.legacySavedPrefix(src.image.?.path, src.tag)) |prefix| + return restoreTailAt(p, pane, src.tag, prefix, .generic); + } + if (src.kind == .terminal and std.mem.startsWith(u8, src.tag, "TTY ")) { + const legacy = std.fmt.allocPrint(p.scratch.allocator(), "TTY {s}", .{src.terminal.?.cwd}) catch return; + if (std.mem.startsWith(u8, src.tag, legacy)) + return restoreTailAt(p, pane, src.tag, legacy, .terminal); + } + const current = tagPrefix(p, pane) catch return; + if (std.mem.startsWith(u8, src.tag, current)) + return restoreTailAt(p, pane, src.tag, savedPrefix(src.tag, current, tail_class), tail_class); + if (src.kind != .image) return; + const saved = src.image.?; + if (pane.image) |*state| if (panes.Image.legacySavedPrefix(state, src.tag)) |legacy| + return restoreTailAt(p, pane, src.tag, legacy, .generic); + if (panes.Pdf.isPath(saved.path)) if (panes.Pdf.legacySavedPrefix(saved.path, src.tag)) |legacy| + restoreTailAt(p, pane, src.tag, legacy, .generic); +} + +pub fn restoreTail(p: *Pardes, pane: *Pane, saved_tag: []const u8) void { + const pfx = tagPrefix(p, pane) catch return; + const class = tailClass(pane); + restoreTailAt(p, pane, saved_tag, savedPrefix(saved_tag, pfx, class), class); +} + +const TailClass = enum { generic, file, output, terminal }; + +fn tailClass(pane: *const Pane) TailClass { + if (pane.file) |f| return if (f.output == null) .file else .output; + if (pane.isTerminal()) return .terminal; + return .generic; +} + +fn savedPrefix(saved_tag: []const u8, live: []const u8, class: TailClass) []const u8 { + if (class == .generic or class == .terminal) return live; + if (!std.mem.startsWith(u8, saved_tag, live)) return live; + const marked_len = live.len + dirty_marker.len; + if (saved_tag.len >= marked_len and std.mem.eql(u8, saved_tag[live.len..marked_len], dirty_marker)) + return saved_tag[0..marked_len]; + return live; +} + +pub fn restoreTailAt( + p: *Pardes, + pane: *Pane, + saved_tag: []const u8, + pfx: []const u8, + class: TailClass, +) void { + if (!std.mem.startsWith(u8, saved_tag, pfx)) return; + const rest = saved_tag[pfx.len..]; + const said = std.mem.trimStart(u8, rest, " "); + const defaults: []const []const u8 = switch (class) { + .generic => &.{ pdf_pane_tail, pane_tail, pre_close_last_pdf_pane_tail, pre_close_last_pane_tail, pre_collapse_pdf_pane_tail, pre_collapse_pane_tail, pre_column_pdf_pane_tail, pre_column_pane_tail, prev_pane_tail, legacy_pane_tail }, + .file => &.{ context_pane_tail, file_pane_tail, pre_close_last_file_pane_tail, pre_collapse_file_pane_tail, pre_column_file_pane_tail, prev_file_pane_tail, legacy_file_pane_tail }, + .output => &.{ + locations_pane_tail, + file_pane_tail, + pre_close_last_file_pane_tail, + pre_close_last_pane_tail, + prev_file_pane_tail, + legacy_file_pane_tail, + pane_tail, + prev_pane_tail, + legacy_pane_tail, + pre_column_file_pane_tail, + pre_column_pane_tail, + pre_collapse_file_pane_tail, + pre_collapse_pane_tail, + }, + .terminal => &.{ terminal_pane_tail, pre_close_last_terminal_pane_tail, pre_close_last_pane_tail, pre_mode_terminal_pane_tail, pre_tty_first_terminal_pane_tail, pre_collapse_terminal_pane_tail, pre_column_terminal_pane_tail, pre_tty_terminal_pane_tail, prev_terminal_pane_tail, legacy_terminal_pane_tail, pane_tail, pre_collapse_pane_tail, pre_column_pane_tail, prev_pane_tail, legacy_pane_tail }, + }; + for (defaults) |default| + if (std.mem.eql(u8, said, std.mem.trimStart(u8, default, " "))) return; + pane.tag.own = p.gpa.dupe(u8, rest) catch return; +} + +/// The span a header's selection covers on line `row` of its text, in +/// that line's bytes: up to the caret while typing, and over the +/// cursor's own cell too in normal mode, where a cursor is a cell. +pub fn headerSelection(t: *const Text, text: []const u8, row: usize) ?struct { lo: usize, hi: usize } { + if (!t.vsel.active) return null; + const anchor = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.vsel.row)), .col = @intCast(@max(0, t.vsel.col)) }); + const cursor = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) }); + const lo = @min(anchor, cursor); + const hi = if (t.mode == .insert) @max(anchor, cursor) else modal.nextGrapheme(text, @max(anchor, cursor)); + const start = modal.lineStartOffset(text, row); + const end = modal.lineEndOffset(text, row); + if (hi <= start or lo >= end) return null; + return .{ .lo = @max(lo, start) - start, .hi = @min(hi, end) - start }; +} diff --git a/test/column_drag.zig b/test/column_drag.zig index f128aa61..feea1bf7 100644 --- a/test/column_drag.zig +++ b/test/column_drag.zig @@ -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, p.columnTag(column)); + try std.testing.expectEqualStrings(saved.tag, pardes.tagline.columnTag(p, column)); } } @@ -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.columnTag(column) }; + saved.* = .{ .weight = p.col_weight[column], .serial = p.col_serial[column], .count = p.col_n[column], .tag = pardes.tagline.columnTag(p, 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.focusedHeader().?.cur_col; - const anchor = p.focusedHeader().?.vsel; + const caret = pardes.tagline.focusedHeader(p).?.cur_col; + const anchor = pardes.tagline.focusedHeader(p).?.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.focusedHeader().?.cur_col); - try std.testing.expectEqual(anchor, p.focusedHeader().?.vsel); + try std.testing.expectEqual(caret, pardes.tagline.focusedHeader(p).?.cur_col); + try std.testing.expectEqual(anchor, pardes.tagline.focusedHeader(p).?.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.focusedHeader().?.cur_col); + try std.testing.expectEqual(caret, pardes.tagline.focusedHeader(p).?.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.focusedHeader().?.cur_col); + try std.testing.expectEqual(caret, pardes.tagline.focusedHeader(p).?.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(i32, 0), p.focusedHeader().?.cur_col); + try std.testing.expectEqual(@as(i32, 0), pardes.tagline.focusedHeader(p).?.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/fs_bench.zig b/test/fs_bench.zig index a816ebbd..da9da47c 100644 --- a/test/fs_bench.zig +++ b/test/fs_bench.zig @@ -65,7 +65,7 @@ const Session = struct { .file_id = id, .file_serial = pane.serial, .body_bytes = pane.file.?.content.len, - .tag = try core.tagText(backing, pane), + .tag = try pardes.tagline.tagText(core, backing, pane), }; } diff --git a/test/mode.zig b/test/mode.zig index c429ea72..c7d7d548 100644 --- a/test/mode.zig +++ b/test/mode.zig @@ -11,7 +11,7 @@ fn mode(p: *Pardes, id: usize, expected: panes.Text.Mode) !void { fn clickModeTag(p: *Pardes) !void { const pane = p.panes[0].?; - const text = try p.tagText(p.scratch.allocator(), pane); + const text = try pardes.tagline.tagText(p, p.scratch.allocator(), pane); const col = std.mem.indexOf(u8, text, "Mode") orelse return error.MissingModeTag; const rect = p.rects[0]; const row = if (p.settings.tag_bottom) rect.y + rect.h - pardes.BOX_H else rect.y; @@ -33,7 +33,7 @@ test "Mode cycles terminal modes and keeps legacy toggle and custom tags" { while (p.nextEffect()) |_| {} const pane = p.panes[0].?; 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 std.testing.expect(std.mem.indexOf(u8, try pardes.tagline.tagText(p, 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 @@ -67,7 +67,7 @@ test "Mode from actual tag Exec preserves parked file and output insert transact p.presentation.enabled = false; 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); + try std.testing.expect(std.mem.indexOf(u8, try pardes.tagline.tagText(p, p.scratch.allocator(), pane), " Mode") == null); try customTag(pane, " Mode"); try mode(p, 0, .insert); p.update(.{ .key = .{ .cp = '界', .text = "界" } }); diff --git a/test/panes.zig b/test/panes.zig index 4804c497..954e431b 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -15,7 +15,7 @@ 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)); + return (try pardes.tagline.tagPrefix(p, pane)).len + @as(usize, @intCast(pane.tag.cur_col)); } fn setTag(pane: *Pane, text: []const u8) !void { @@ -52,7 +52,7 @@ const TagLayerTests = struct { defer frame.deinit(); _ = try p.render(frame.allocator()); const layer = try findLayer(p, .pane, 0); - const text = try p.tagText(frame.allocator(), pane); + const text = try pardes.tagline.tagText(p, frame.allocator(), pane); const at = std.mem.indexOf(u8, text, "END").?; const col = panes.File.displayWidth(text[0..at]); try std.testing.expect(col > p.rects[0].w); @@ -70,7 +70,7 @@ const TagLayerTests = struct { 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); + const edited = try pardes.tagline.tagText(p, frame.allocator(), pane); try std.testing.expect(std.mem.endsWith(u8, edited, "界 XEND")); try std.testing.expectEqual(@as(u16, 0), pane.tag_scroll); try std.testing.expectEqualStrings("body\n", pane.file.?.content); @@ -140,7 +140,7 @@ const TagLayerTests = struct { 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); + const left_text = try pardes.tagline.tagText(p, frame.allocator(), left); const start_x = @as(f32, @floatFromInt(left_layer.viewport.x)) * 10 + 12.5; const beyond_x = edge + 12.5; p.update(.{ .mouse = mouse(left_layer, start_x, .press) }); @@ -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(i32, 63), p.focusedHeader().?.cur_col); + try std.testing.expectEqual(@as(i32, 63), pardes.tagline.focusedHeader(p).?.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 } }); } @@ -184,7 +184,7 @@ test "a tag with a newline in it is as tall as its lines, and each line is typed 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.expect(std.mem.endsWith(u8, pardes.tagline.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); @@ -252,7 +252,7 @@ const TagNavigationTests = struct { // 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); + const tail = pardes.tagline.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); @@ -278,7 +278,7 @@ const TagNavigationTests = struct { _ = 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; - const prefix: u16 = @intCast(panes.File.displayWidth(try p.tagPrefix(first))); + const prefix: u16 = @intCast(panes.File.displayWidth(try pardes.tagline.tagPrefix(p, 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.expect(first.focus == .tag and first.tag.mode == .insert); @@ -316,7 +316,7 @@ const TagNavigationTests = struct { 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]); + try std.testing.expectEqualStrings("Save", pardes.tagline.curTail(pane)[@intCast(pane.tag.cur_col)..][0..4]); } } @@ -403,14 +403,14 @@ const TagNavigationTests = struct { key(p, ':'); key(p, 'i'); key(p, Key.end); - const before = Pardes.curTail(pane).len; + const before = pardes.tagline.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.focus == .tag and pane.tag.mode == .insert); } - try std.testing.expectEqualStrings("hjklHJKL:", Pardes.curTail(pane)[before..]); + try std.testing.expectEqualStrings("hjklHJKL:", pardes.tagline.curTail(pane)[before..]); try std.testing.expectEqualStrings("body\n", pane.file.?.content); try std.testing.expectEqual(@as(usize, 0), p.active); } @@ -1187,7 +1187,7 @@ const TagNameTintTests = struct { var arena = std.heap.ArenaAllocator.init(p.gpa); defer arena.deinit(); const surface = try p.render(arena.allocator()); - const text = try p.tagText(arena.allocator(), pane); + const text = try pardes.tagline.tagText(p, arena.allocator(), pane); const base = std.mem.lastIndexOfScalar(u8, name, '/') orelse return error.MissingDirectory; const rect = p.rects[id]; const y = if (p.settings.tag_bottom) rect.y + rect.h - pardes.BOX_H else rect.y; @@ -1235,7 +1235,7 @@ const TagNameTintTests = struct { configure(p); defer p.custom_theme = null; const name = "/a/very/long/directory/that/extends/past/the/tag/界e\u{301}name-with-a-long-tail.zig"; - p.draftName(pane, 0); + pardes.tagline.draftName(p, 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); @@ -1304,7 +1304,7 @@ test "pane filename drafts commit and cancel without changing body or command ta const original = try p.gpa.dupe(u8, pane.file.?.path); defer p.gpa.free(original); try pane.appendTag(" SyntaxBold"); - const tail = try p.gpa.dupe(u8, Pardes.curTail(pane)); + const tail = try p.gpa.dupe(u8, pardes.tagline.curTail(pane)); defer p.gpa.free(tail); for ([_]bool{ false, true }) |commit| { clickPathEnd(p, pane); @@ -1312,13 +1312,13 @@ test "pane filename drafts commit and cancel without changing body or command ta p.update(.{ .paste = "/new name.zig" }); try std.testing.expectEqualStrings(original, pane.file.?.path); try std.testing.expectEqualStrings("/new name.zig", pane.input.own.?); - try std.testing.expectEqualStrings(tail, Pardes.curTail(pane)); + try std.testing.expectEqualStrings(tail, pardes.tagline.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.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, Pardes.curTail(pane)); + try std.testing.expectEqualStrings(tail, pardes.tagline.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); @@ -1351,13 +1351,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.exitHeader(); + pardes.tagline.exitHeader(p); p.update(.tick); clickPathEnd(p, pane); p.update(.{ .paste = "/draft" }); try std.testing.expect(pane.prompt == .name); if (header) { - p.enterHeader(null); + pardes.tagline.enterHeader(p, null); p.update(.tick); } else { try std.testing.expect(p.executeBuiltinLine(0, "New")); @@ -1379,7 +1379,7 @@ test "middle clicking Save commits the drafted filename before issuing a save" { var arena = std.heap.ArenaAllocator.init(p.gpa); defer arena.deinit(); _ = try p.render(arena.allocator()); - const text = try p.tagText(arena.allocator(), pane); + const text = try pardes.tagline.tagText(p, arena.allocator(), pane); const save_at = std.mem.indexOf(u8, text, "Save").?; const x: u16 = @intCast(p.rects[0].x + pardes.TAG_TEXT_INSET + save_at - pane.tag_scroll); const y = p.rects[0].y; @@ -1421,15 +1421,15 @@ test "paste into pane commands and prompts never inserts into the body" { p.update(.{ .key = .{ .cp = 'A' } }); // 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); + try std.testing.expect(std.mem.indexOf(u8, pardes.tagline.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.indexOf(u8, Pardes.curTail(pane), " Custom\nCommand") != null); + try std.testing.expect(std.mem.indexOf(u8, pardes.tagline.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.indexOf(u8, Pardes.curTail(pane), " Custom\nCommand") != null); + try std.testing.expect(std.mem.indexOf(u8, pardes.tagline.curTail(pane), " Custom\nCommand") != null); } test "long pane tags reveal commands and map visible clicks to whole tag addresses" { @@ -1446,7 +1446,7 @@ test "long pane tags reveal commands and map visible clicks to whole tag address const surface = try p.render(arena.allocator()); try std.testing.expect(pane.tag_scroll > 0); try std.testing.expect(surface.cursor.?.x < p.rects[0].x + p.rects[0].w); - const text = try p.tagText(p.gpa, pane); + const text = try pardes.tagline.tagText(p, p.gpa, pane); defer p.gpa.free(text); const offset = std.mem.indexOf(u8, text, "SyntaxBold").?; const x: u16 = @intCast(p.rects[0].x + pardes.TAG_TEXT_INSET + panes.File.rawDisplayCol(text, offset) - pane.tag_scroll); @@ -1455,7 +1455,7 @@ test "long pane tags reveal commands and map visible clicks to whole tag address 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.expectEqual(!before, p.settings.syntax_bold); - try std.testing.expectEqualStrings(text, try p.tagText(p.scratch.allocator(), pane)); + try std.testing.expectEqualStrings(text, try pardes.tagline.tagText(p, p.scratch.allocator(), pane)); } test "terminal overlay recoloring never materializes unrelated history" { @@ -4155,7 +4155,7 @@ test "cancelled normal gestures leave no count or subprefix after mouse and focu const tag_y = if (p.settings.tag_bottom) rect.y + rect.h - pardes.BOX_H else rect.y; 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 + rect.x + pardes.TAG_TEXT_INSET + @as(u16, @intCast(panes.File.displayWidth(try pardes.tagline.tagPrefix(p, 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; diff --git a/test/pdf.zig b/test/pdf.zig index 745ecb1a..3a592451 100644 --- a/test/pdf.zig +++ b/test/pdf.zig @@ -612,7 +612,7 @@ test "MuPDF pane renders, navigates, searches, and round-trips its page" { try std.testing.expectEqual(@as(u16, 0), pane.pdf.?.pan_y); try std.testing.expectEqual(@as(u16, 8), p.cell_pixels.w); try std.testing.expectEqual(@as(u16, 16), p.cell_pixels.h); - const initial_tag = try pardes.test_api.tagText(p, p.scratch.allocator(), pane); + const initial_tag = try pardes.tagline.tagText(p, p.scratch.allocator(), pane); const expected_tag = try std.fmt.allocPrint(p.scratch.allocator(), "{s} [1/{d}]{s}", .{ pane.pdf.?.path, pane.pdf.?.page_count, pane_tail }); try std.testing.expectEqualStrings(expected_tag, initial_tag); try std.testing.expect(std.mem.endsWith(u8, initial_tag, pane_tail)); @@ -833,7 +833,7 @@ test "MuPDF pane renders, navigates, searches, and round-trips its page" { revision_before_toggle, panes.Pdf.rasterForPage(&pane.pdf.?, pane.pdf.?.page).?.revision, ); - const height_tag = try pardes.test_api.tagText(p, p.scratch.allocator(), pane); + const height_tag = try pardes.tagline.tagText(p, p.scratch.allocator(), pane); const expected_height_tag = try std.fmt.allocPrint(p.scratch.allocator(), "{s} [{d}/{d}]{s}", .{ pane.pdf.?.path, pane.pdf.?.page + 1, pane.pdf.?.page_count, pane_tail }); try std.testing.expectEqualStrings(expected_height_tag, height_tag); for (p.panes) |slot| { @@ -1250,7 +1250,7 @@ test "PdfTint cycles pane-local state without adding tag clutter" { return error.MissingPdfTintBuiltin; try std.testing.expectEqual(PdfTintMode.filtered, pv.tint); - const initial_tag = try pardes.test_api.tagText(p, p.scratch.allocator(), pane); + const initial_tag = try pardes.tagline.tagText(p, p.scratch.allocator(), pane); try std.testing.expect(std.mem.startsWith(u8, initial_tag, pv.path)); try std.testing.expect(std.mem.endsWith(u8, initial_tag, " PdfSections PdfTint Collapse Del")); try std.testing.expect(std.mem.indexOf(u8, initial_tag, "filtered") == null); @@ -1263,7 +1263,7 @@ test "PdfTint cycles pane-local state without adding tag clutter" { null, )); try std.testing.expectEqual(PdfTintMode.full, pv.tint); - const full_tag = try pardes.test_api.tagText(p, p.scratch.allocator(), pane); + const full_tag = try pardes.tagline.tagText(p, p.scratch.allocator(), pane); try std.testing.expectEqualStrings(initial_tag, full_tag); try std.testing.expect(std.mem.indexOf(u8, full_tag, "full") == null); @@ -1291,7 +1291,7 @@ test "PdfTint cycles pane-local state without adding tag clutter" { null, )); try std.testing.expectEqual(PdfTintMode.disabled, pv.tint); - const disabled_tag = try pardes.test_api.tagText(p, p.scratch.allocator(), pane); + const disabled_tag = try pardes.tagline.tagText(p, p.scratch.allocator(), pane); try std.testing.expectEqualStrings(initial_tag, disabled_tag); try std.testing.expect(std.mem.indexOf(u8, disabled_tag, "disabled") == null); try std.testing.expect(pardes.test_api.runBuiltin( -- cgit v1.3 From 6fc9f416938b59b665b1fddc052402770a21cc3f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 28 Sep 2026 12:44:57 -0300 Subject: A Restore answers its writer before hanging up, and the log records dumps and restores A client that wrote Restore saw its connection cut with no answer, and could not tell a Restore from a crash. The listener now lets the writer's answer out before the cut, and cuts only the old editor's connections, refusing their requests meanwhile; a client that dials during it is the new editor's and stays. Dump logs 'dump ' and the restored editor's log 'restore '. Keeping connections across a Restore was weighed and left: the fids name the old editor's panes and opens, so it would mean carrying serials and open records into the new one, where acme's Load only adds windows. tty's Restore also closed its shells' ptys without reaping them; it retires them now. Co-Authored-By: Claude Opus 5.5 --- .agents/skills/pardes-9p/SKILL.md | 3 +- docs/fs.md | 20 ++++++++++--- src/9p_io.zig | 63 ++++++++++++++++++++++++++++++++------- src/detached/client.zig | 3 +- src/detached/server.zig | 8 ++--- src/dump.zig | 8 +++-- src/gui/gui.zig | 4 +-- src/macos.zig | 2 +- src/ninep/events.zig | 23 ++++++++++++++ src/pardes.zig | 7 +++-- src/tty/tty.zig | 3 +- test/fs.py | 12 ++++---- test/fs_namespace.zig | 3 +- 13 files changed, 123 insertions(+), 36 deletions(-) (limited to 'src/dump.zig') diff --git a/.agents/skills/pardes-9p/SKILL.md b/.agents/skills/pardes-9p/SKILL.md index 393b0b0f..5e3bc39c 100644 --- a/.agents/skills/pardes-9p/SKILL.md +++ b/.agents/skills/pardes-9p/SKILL.md @@ -51,7 +51,8 @@ $m/exec write a line = a middle click: an editor command word, or a shell $m/pane//pty/run write one line, read `exit N` + its output, or `busy` / `error ...`, on the same open: exec 3<>$m/pane/$n/pty/run; echo make >&3; cat <&3 (a fresh terminal: waits for its first prompt; if none comes, interrupt the read) -$m/log recent events, then EOF: new|del|rename|save , msg +$m/log recent events, then EOF: new|del|rename|save , msg , + dump|restore , err : (exec 3<>$m/log; echo follow >&3; cat <&3 waits for new ones; tail -f does not) $m/screen the rendered screen as JSON, frozen per open $m/listeners this session's dial addresses diff --git a/docs/fs.md b/docs/fs.md index a2d8a9b2..f377d32a 100644 --- a/docs/fs.md +++ b/docs/fs.md @@ -84,7 +84,8 @@ Existing Plan9port/v9fs clients need a userspace bridge for QUIC. /status pid, version and pane count /look write a line: a right click on it at the active pane; read: the serials it touched /exec write a line: a middle click; read the same serials -/log recent events, one a line: new|del|rename|save , msg ; +/log recent events, one a line: new|del|rename|save , msg , + dump|restore , err : ; write follow to that open to wait for more /screen rendered screen JSON; frozen per open handle /listeners the session's dial addresses @@ -106,8 +107,17 @@ builtins, one a line, at whichever pane has the keyboard as each runs -- `Newcol`, `Dump`, `Mount name dial`, `Theme ink`, `Verbose off`; `Exit`, which quits the editor as acme's does (it refuses once, naming each pane with unsaved text, `: Modified (Exit again to discard)`, and a second -`Exit` with nothing edited since quits, throwing that text away; a scratch under 100 bytes is not asked about; `Restore`, which -replaces every pane, asks the same first); and `Kill`, which +`Exit` with nothing edited since quits, throwing that text away; a scratch +under 100 bytes is not asked about; `Restore`, which replaces every pane, +asks the same first -- `Dump` writes `pardes--