From 779ff8cc27014b8c2f2f078985ab2ca9cf285740 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 05:45:38 -0300 Subject: Editor: what an edit of a text runs with, out of Pardes (docs/next-editor.md, R1): src/Editor.zig is a context of the allocators and pointers to the registers, the register the running command names, the replay's multi_* and the retired text, and the core (`p`), gathered per call by `p.editor()` from where they are, so no field of Pardes or its view moves and a dump crosses builds as before (an embedded `ed: Editor` would have renamed `registers` in the dump, matched by name, and lost them at an Upgrade); setYank, registerValue, retireEditText and normal.multiOnce take it, their callers hand `p.editor()`; core-test 810 of 949, shell-test 989 of 992, hxdiff 658 / parity 738 / hxgolf 124 with 0 mismatches, replicas pass --- src/normal.zig | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) (limited to 'src/normal.zig') diff --git a/src/normal.zig b/src/normal.zig index dbd35fb5..d35dd60d 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -21,14 +21,15 @@ const hit = pardes.hit; const sel_slot = pardes.sel_slot; const Pardes = pardes.Pardes; const Macro = pardes.Macro; +const Editor = pardes.Editor; fn isPrefix(key: Key, cp: u21) bool { return key.cp == cp and !key.ctrl and !key.alt; } -pub fn multiOnce(p: *Pardes) bool { - p.multi_stop = true; - return p.multi_first; +pub fn multiOnce(e: Editor) bool { + e.multi_stop.* = true; + return e.multi_first.*; } fn regexMarker(mode: modal.Normal.RegexMode) []const u8 { -- cgit v1.3 From 2b04f877c29cf1e95c2fc8154de1da322c7299a3 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 05:49:29 -0300 Subject: edit: the routing of a text's characters takes the editing context (docs/next-editor.md, R2, first slice): flatSurface, editText, editTextEol, setEditText, setEditTextEnd, setEditTextSpan, paneCursorLines, paneByteAtDisplay, pinPaneCursor, paneWrapWidth, treeIndent, pushUndo, undoStep, stepOwn, selText and vselText take `e: Editor` where they took `*Pardes`, the pane they route to reached through `e.p`; 149 calls in 16 files hand `p.editor()`, nothing else changes; core-test 810 of 949, shell-test 989 of 992, hxdiff 658 / parity 738 / hxgolf 124 with 0 mismatches, replicas pass --- src/Core.zig | 2 +- src/Pipe.zig | 10 +- src/body_layer.zig | 2 +- src/builtins.zig | 4 +- src/draw.zig | 2 +- src/edit.zig | 348 ++++++++++++++++++++++++++--------------------------- src/exec.zig | 4 +- src/keys.zig | 6 +- src/look.zig | 16 +-- src/lsp/Ask.zig | 2 +- src/mouse.zig | 20 +-- src/normal.zig | 26 ++-- src/tagline.zig | 6 +- test/hxdiff.zig | 2 +- test/panes.zig | 2 +- test/perf.zig | 2 +- 16 files changed, 227 insertions(+), 227 deletions(-) (limited to 'src/normal.zig') diff --git a/src/Core.zig b/src/Core.zig index c57818ee..9ba448be 100644 --- a/src/Core.zig +++ b/src/Core.zig @@ -2922,7 +2922,7 @@ test "a REPL bound for a language takes the exec made on a body in it; tags, Exe try std.testing.expectEqualStrings("def f():\r return 1\r\r", Sent.said(1)); // Several selections executed at once: each is sent, not the first. { - const text = try edit.flatSurface(p, &file.body); + const text = try edit.flatSurface(p.editor(), &file.body); file.body.setRanges(text, &.{ .{ .anchor = 0, .head = 8 }, .{ .anchor = 9, .head = 11 } }, &.{}, 0, true); try std.testing.expect(exec.chordEachSel(p, file, .Exec)); Sent.drain(p); diff --git a/src/Pipe.zig b/src/Pipe.zig index 10967a3c..9b913f1e 100644 --- a/src/Pipe.zig +++ b/src/Pipe.zig @@ -95,7 +95,7 @@ pub fn submitPipe(p: *Pardes, id: usize) void { const f = pane.file orelse return; if (!panes.Output.fileTraits(f.output).saves) return; } - const content = edit.flatSurface(p, t) catch |err| return p.reportError(id, "pipe", err); + const content = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(id, "pipe", err); const how = switch (pane.prompt) { .pipe => |pipe| pipe, else => return, @@ -259,7 +259,7 @@ pub fn pipeResponse( .workspace => &p.global_tag, .input => return, }; - const content = edit.flatSurface(p, t) catch |err| return p.reportError(wait.pane, "pipe", err); + const content = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(wait.pane, "pipe", err); const changed = if (t.what == .body) changed: { const f = pane.file orelse return; if (!panes.Output.fileTraits(f.output).saves) return; @@ -314,12 +314,12 @@ pub fn pipeResponse( } // One async request is one history transaction, even at 64 cursors. - edit.pushUndo(p, t) catch |err| { + edit.pushUndo(p.editor(), t) catch |err| { p.gpa.free(replacement); return p.reportError(wait.pane, "pipe", err); }; - edit.setEditText(p, t, replacement) catch |err| return p.reportError(wait.pane, "pipe", err); - const now = edit.flatSurface(p, t) catch |err| return p.reportError(wait.pane, "pipe", err); + edit.setEditText(p.editor(), t, replacement) catch |err| return p.reportError(wait.pane, "pipe", err); + const now = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(wait.pane, "pipe", err); t.setRanges(now, new_ranges[0..n], &.{}, wait.primary, wait.explicit); t.select = false; t.show(); diff --git a/src/body_layer.zig b/src/body_layer.zig index 26513b93..6748c161 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -466,7 +466,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane // `gw`'s labels, two letters over the start of each word if (pane.jump.items.len > 0) labels: { - const flat = edit.flatSurface(p, &pane.body) catch break :labels; + const flat = edit.flatSurface(p.editor(), &pane.body) catch break :labels; const letters = config.jump_label_alphabet; const style: CellStyle = .{ .fg = .{ .rgb = th.sel_fg }, .bg = .{ .rgb = th.sel_bg }, .bold = true }; for (pane.jump.items, 0..) |word, i| { diff --git a/src/builtins.zig b/src/builtins.zig index e9c91fd8..0e8610ae 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -1111,7 +1111,7 @@ pub const Undo = struct { pub fn run(c: Ctx) void { if (@import("edit_cmd.zig").busyOn(c.p, c.id)) return c.p.reportFailure(c.id, "Undo: " ++ @import("edit_cmd.zig").e_busy); if (c.pane.file) |f| if (f.history.journal.done == 0) return c.p.setMessage(c.id, "Undo: nothing to undo"); - edit.undoStep(c.p, &c.pane.body, true) catch |err| c.p.reportError(c.id, "Undo", err); + edit.undoStep(c.p.editor(), &c.pane.body, true) catch |err| c.p.reportError(c.id, "Undo", err); } }; @@ -1120,7 +1120,7 @@ pub const Redo = struct { pub fn run(c: Ctx) void { if (@import("edit_cmd.zig").busyOn(c.p, c.id)) return c.p.reportFailure(c.id, "Redo: " ++ @import("edit_cmd.zig").e_busy); if (c.pane.file) |f| if (f.history.journal.done == f.history.journal.steps.items.len) return c.p.setMessage(c.id, "Redo: nothing to redo"); - edit.undoStep(c.p, &c.pane.body, false) catch |err| c.p.reportError(c.id, "Redo", err); + edit.undoStep(c.p.editor(), &c.pane.body, false) catch |err| c.p.reportError(c.id, "Redo", err); } }; diff --git a/src/draw.zig b/src/draw.zig index 92bcc592..10556ac9 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -645,7 +645,7 @@ fn renderHeaderLayer(p: *Pardes, layer: *pardes.Layer, kind: TagKind, id: u16, v }; } if (editing) |t| { - if (tagline.headerSelection(t, try edit.flatSurface(p, t), line + v.header_top)) |span| { + if (tagline.headerSelection(t, try edit.flatSurface(p.editor(), t), line + v.header_top)) |span| { var col = panes.File.rawDisplayCol(shown, span.lo) -| scroll; const end = panes.File.rawDisplayCol(shown, span.hi) -| scroll; while (col < end and col < columns) : (col += 1) { diff --git a/src/edit.zig b/src/edit.zig index 2dd613ac..e8b5aab2 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -56,7 +56,7 @@ pub fn registerValue(e: Editor, t: *Text, name: u21) ?[]const u8 { return switch (name) { '_' => null, '#' => std.fmt.allocPrint(e.scratch, "{d}", .{i + 1}) catch null, - '.' => selText(e.p, t) catch null, + '.' => selText(e, t) catch null, '%' => if (t.what == .body) if (t.pane()) |pane| (if (pane.file) |f| f.path else null) else null else null, else => e.registers.value(name, i), }; @@ -64,11 +64,11 @@ pub fn registerValue(e: Editor, t: *Text, name: u21) ?[]const u8 { /// the text of the range under the cursor: the selection, or the cursor's /// own character -fn selText(p: *Pardes, t: *Text) Error![]const u8 { +fn selText(e: Editor, t: *Text) Error![]const u8 { const save = t.vsel; defer t.vsel = save; if (!t.vsel.active) t.vsel = .{ .active = true, .row = t.cur_row, .col = t.cur_col, .explicit = false }; - return vselText(p, t); + return vselText(e, t); } /// `p` / `P` / `R` from the register the command names: this range's value @@ -351,7 +351,7 @@ pub fn sweepEnds(sl: Pane.Sel) struct { [2]i32, [2]i32 } { pub fn currentSelText(p: *Pardes, pane: *Pane) ?[]const u8 { if (pane.addon) |k| if (k.selection.len > 0) return k.selection; if (!pane.body.vsel.active) return null; - return vselText(p, &pane.body) catch null; + return vselText(p.editor(), &pane.body) catch null; } pub fn exitInsert(p: *Pardes, t: *Text) void { @@ -363,7 +363,7 @@ pub fn exitInsert(p: *Pardes, t: *Text) void { // helix enter_normal_mode: every range, from its start to the char // before its end when it points forward, else to its end const expl = t.vsel.active and t.vsel.explicit; - const text = flatSurface(p, t) catch |err| return p.reportError(p.view().active, "edit", err); + const text = flatSurface(p.editor(), t) catch |err| return p.reportError(p.view().active, "edit", err); var rs: [Text.max_selections]modal.Selection = undefined; const got = t.ranges(text, 0, &rs); for (rs[0..got.n]) |*r| { @@ -375,10 +375,10 @@ pub fn exitInsert(p: *Pardes, t: *Text) void { t.setRanges(text, rs[0..got.n], &.{}, got.pri, expl); } -pub fn paneCursorLines(p: *Pardes, t: *Text) Error![]const []const u8 { - const arena = p.scratch.allocator(); +pub fn paneCursorLines(e: Editor, t: *Text) Error![]const []const u8 { + const arena = e.scratch; if (t.what != .body) { - const text = try flatSurface(p, t); + const text = try flatSurface(e, 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().?; @@ -387,13 +387,13 @@ pub fn paneCursorLines(p: *Pardes, t: *Text) Error![]const []const u8 { const pane = t.pane() orelse return &.{}; if (pane.file) |*f| return panes.File.cursorLines(arena, pane, f); if (pane.addon != null) return &.{}; - return terminalLines(p, pane); + return terminalLines(e.p, pane); } -pub fn paneByteAtDisplay(p: *Pardes, t: *Text, row: i32, from_raw: i32, display_col: i32) i32 { +pub fn paneByteAtDisplay(e: Editor, t: *Text, row: i32, from_raw: i32, display_col: i32) i32 { if (t.what == .body) if (t.pane()) |pane| if (pane.file != null) return panes.File.byteAtRowDisplay(pane, row, from_raw, display_col); - const lines = paneCursorLines(p, t) catch return @max(0, from_raw + display_col); + const lines = paneCursorLines(e, 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); @@ -406,7 +406,7 @@ pub fn paneByteAtDisplay(p: *Pardes, t: *Text, row: i32, from_raw: i32, display_ /// Freeze the live terminal cursor into the modal coordinate space. The /// emulator reports screen cells; editing state stores UTF-8 byte offsets. -pub fn pinPaneCursor(p: *Pardes, t: *Text) void { +pub fn pinPaneCursor(e: Editor, t: *Text) void { if (t.cur_pinned) return; // Only a body has a live cursor of someone else's to freeze. if (t.what != .body) { @@ -416,7 +416,7 @@ pub fn pinPaneCursor(p: *Pardes, t: *Text) void { const pane = t.pane() orelse return; pane.pinCursor(); if (pane.file == null and pane.addon == null) - t.cur_col = paneByteAtDisplay(p, t, t.cur_row, 0, t.cur_col); + t.cur_col = paneByteAtDisplay(e, t, t.cur_row, 0, t.cur_col); } // ---- a terminal's rows, and the copy of them an edit makes ---- @@ -524,26 +524,26 @@ pub fn terminalLines(p: *Pardes, pane: *Pane) ![]const []const u8 { return lines[0..n]; } -pub fn flatSurface(p: *Pardes, t: *Text) Error![]const u8 { +pub fn flatSurface(e: Editor, t: *Text) Error![]const u8 { switch (t.what) { .body => {}, // the tag as it is shown: the keyboard reaches its prefix too - .tag => return if (t.pane()) |pane| try tagline.tagText(p, p.scratch.allocator(), pane) else "", + .tag => return if (t.pane()) |pane| try tagline.tagText(e.p, e.scratch, pane) else "", .input => return t.own orelse "", - .column, .workspace => return t.own orelse tagline.headerDefault(p, t.what), + .column, .workspace => return t.own orelse tagline.headerDefault(e.p, t.what), } const pane = t.pane() orelse return ""; if (pane.file) |f| return f.content; if (pane.addon != null) return ""; - const lines = try terminalLines(p, pane); + const lines = try terminalLines(e.p, pane); // The kept rows' own join when the lines are them (no edit copy), not // made again on every keystroke; a join of them in scratch else. - const cache = &p.shell_rows; + const cache = &e.p.shell_rows; if (!cache.stale and cache.pane == pane and lines.ptr == cache.rows.ptr and lines.len == cache.rows.len) return cache.text; var total: usize = if (lines.len > 0) lines.len - 1 else 0; for (lines) |line| total += line.len; - const text = try p.scratch.allocator().alloc(u8, total); + const text = try e.scratch.alloc(u8, total); var at: usize = 0; for (lines, 0..) |line, i| { if (i > 0) { @@ -556,24 +556,24 @@ pub fn flatSurface(p: *Pardes, t: *Text) Error![]const u8 { return text; } -pub fn paneWrapWidth(p: *const Pardes, t: *Text) usize { +pub fn paneWrapWidth(e: Editor, t: *Text) usize { if (t.what != .body) return 0; const pane = t.pane() orelse return 0; if (pane.file == null) return 0; - return panes.File.wrapWidth(pane, p.settings.wrap); + return panes.File.wrapWidth(pane, e.p.settings.wrap); } /// 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) Error!?panes.EditText { +fn editText(e: Editor, t: *Text, lo: i32, hi: i32, col: i32) Error!?panes.EditText { // A tag or header nobody has changed shows its default; the first edit // makes that default its own text. if (t.what == .tag) { const pane = t.pane() orelse return null; - return .{ .text = try tagline.tagText(p, p.scratch.allocator(), pane), .row0 = 0 }; + return .{ .text = try tagline.tagText(e.p, e.scratch, pane), .row0 = 0 }; } if (t.what != .body and t.what != .input and t.own == null) - t.own = try p.gpa.dupe(u8, try flatSurface(p, t)); + t.own = try e.gpa.dupe(u8, try flatSurface(e, t)); if (t.what != .body) return .{ .text = t.own orelse &.{}, .row0 = 0 }; const pane = t.pane() orelse return null; if (pane.file) |f| return .{ .text = f.content, .row0 = 0 }; @@ -594,12 +594,12 @@ fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) Error!?panes.EditT var text = old.text; var owned = false; if (extending) { - const rows = try shellRows(p, pane); + const rows = try shellRows(e.p, pane); row0 = old.row - @max(0, up); covered = old.rows + @max(0, up) + @max(0, down); const up_len: usize = @intCast(@max(0, up)); const down_len: usize = @intCast(@max(0, down)); - const parts = try p.scratch.allocator().alloc([]const u8, up_len + 1 + down_len); + const parts = try e.scratch.alloc([]const u8, up_len + 1 + down_len); for (parts[0..up_len], 0..) |*part, i| { const src = @as(usize, @intCast(row0)) + i; part.* = if (src < rows.len) rows[src] else ""; @@ -613,100 +613,100 @@ fn editText(p: *Pardes, t: *Text, lo: i32, hi: i32, col: i32) Error!?panes.EditT const src = @as(usize, @intCast(old.row + old.rows)) + i; part.* = if (src < rows.len) rows[src] else ""; } - text = try std.mem.join(p.gpa, "\n", parts); + text = try std.mem.join(e.gpa, "\n", parts); owned = true; } const row: usize = @intCast(@max(0, want_lo - row0)); const line_len: i32 = @intCast(modal.lineSlice(text, row).len); if (col > line_len) { - const spaces = p.scratch.allocator().alloc(u8, @intCast(col - line_len)) catch { - if (owned) p.gpa.free(text); + const spaces = e.scratch.alloc(u8, @intCast(col - line_len)) catch { + if (owned) e.gpa.free(text); return null; }; @memset(spaces, ' '); - const padded = modal.insertAt(p.gpa, text, .{ .row = row, .col = @intCast(line_len) }, spaces) catch { - if (owned) p.gpa.free(text); + const padded = modal.insertAt(e.gpa, text, .{ .row = row, .col = @intCast(line_len) }, spaces) catch { + if (owned) e.gpa.free(text); return null; }; - if (owned) p.gpa.free(text); + if (owned) e.gpa.free(text); text = padded; owned = true; } if (owned) { - if (pane.ovl) |overlay| p.gpa.free(overlay.text); + if (pane.ovl) |overlay| e.gpa.free(overlay.text); pane.ovl = .{ .row = row0, .rows = covered, .text = text }; } // A terminal's text is its program's: edited here it is a copy, to run // with Tab or B2, gone when the program draws again. Said at its first // edit, so it never looks like an edit that was lost. - if (fresh) for (p.panes, 0..) |slot, id| if (slot == pane) - p.setMessage(id, "a copy of the terminal's text: Tab or B2 runs it; what the program draws next replaces it (Ctrl-b types to the program)"); + if (fresh) for (e.p.panes, 0..) |slot, id| if (slot == pane) + e.p.setMessage(id, "a copy of the terminal's text: Tab or B2 runs it; what the program draws next replaces it (Ctrl-b types to the program)"); return .{ .text = pane.ovl.?.text, .row0 = pane.ovl.?.row }; } -fn editTextEol(p: *Pardes, t: *Text, b: Bounds) Error!?panes.EditText { - const eb = (try editText(p, t, b.lo_row, b.hi_row, -1)) orelse return null; +fn editTextEol(e: Editor, t: *Text, b: Bounds) Error!?panes.EditText { + const eb = (try editText(e, t, b.lo_row, b.hi_row, -1)) orelse return null; const r: usize = @intCast(@max(0, b.hi_row - eb.row0)); // A file's own line count and line, from its index. if (r + 1 < panes.File.textLineCount(t, eb.text)) return eb; if (b.hi_col < @as(i32, @intCast(panes.File.textLine(t, eb.text, r).len))) return eb; - return editText(p, t, b.lo_row, b.hi_row + 1, -1); + return editText(e, t, b.lo_row, b.hi_row + 1, -1); } /// install a rewritten editable text (frees the old one) -pub fn setEditText(p: *Pardes, t: *Text, new: []u8) Error!void { - return setEditTextEnd(p, t, new, null); +pub fn setEditText(e: Editor, t: *Text, new: []u8) Error!void { + return setEditTextEnd(e, t, new, null); } /// `setEditText` with where the edit ended in `new` (in the edit text's /// rows) when the caller knows it, as typing does: then nothing scans the /// whole text to find it. Null, it is found by comparing the texts. -pub fn setEditTextEnd(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor) Error!void { - return setEditTextSpan(p, t, new, known_end, null); +pub fn setEditTextEnd(e: Editor, t: *Text, new: []u8, known_end: ?modal.Cursor) Error!void { + return setEditTextSpan(e, t, new, known_end, null); } /// `setEditTextEnd` with what a file's splice left alone at either end, when /// the caller knows it (typing): the line index is then not found again by /// comparing the whole old and new texts, which a keystroke in a 7 MB file did. -fn setEditTextSpan(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor, span: ?panes.File.Span) Error!void { +fn setEditTextSpan(e: Editor, t: *Text, new: []u8, known_end: ?modal.Cursor, span: ?panes.File.Span) Error!void { if (t.what == .tag) { // A tag is edited as it is shown, but only what follows its // prefix is its own: an edit that changed the prefix is refused. // The shown text stays alive until the next such edit, since every // caller reads the new text back, as a body's is kept. - defer retireEditText(p.editor(), new); + defer retireEditText(e, new); const pane = t.pane() orelse return; - const prefix = try tagline.pathPrefix(p, p.scratch.allocator(), pane); + const prefix = try tagline.pathPrefix(e.p, e.scratch, pane); if (!std.mem.startsWith(u8, new, prefix)) { t.refused = true; return; } - const tail = try p.gpa.dupe(u8, new[prefix.len..]); - if (t.own) |old| p.gpa.free(old); + const tail = try e.gpa.dupe(u8, new[prefix.len..]); + if (t.own) |old| e.gpa.free(old); t.own = tail; return; } if (t.what != .body) { - if (t.own) |old| p.gpa.free(old); + if (t.own) |old| e.gpa.free(old); t.own = new; return; } - const pane = t.pane() orelse return retireEditText(p.editor(), new); + const pane = t.pane() orelse return retireEditText(e, new); // A live query pane's rows are its line 1's (Query.zig): an edit there // is refused, as a tag's prefix refuses one, and one from line 1 into // them is cut at its end. The rows' metadata stays theirs across an // edit of the line, which moves no row. if (pane.file) |*f| if (pane.query) |q| if (!q.frozen) { - const kept = panes.Query.clampEdit(p, t, f.content, new) orelse return retireEditText(p.editor(), new); - if (kept.ptr != new.ptr) retireEditText(p.editor(), new); + const kept = panes.Query.clampEdit(e.p, t, f.content, new) orelse return retireEditText(e, new); + if (kept.ptr != new.ptr) retireEditText(e, new); const end = modal.positionAt(kept, kept.len - panes.File.spanOf(f.content, kept).tail); t.last_edit = .{ .row = @intCast(end.row), .col = @intCast(end.col) }; const rows = f.location_rows; const spans = f.pager_spans; f.location_rows = &.{}; f.pager_spans = &.{}; - panes.File.setContentSpan(p, f, kept, null); + panes.File.setContentSpan(e.p, f, kept, null); f.location_rows = rows; f.pager_spans = spans; return; @@ -719,14 +719,14 @@ fn setEditTextSpan(p: *Pardes, t: *Text, new: []u8, known_end: ?modal.Cursor, sp const found = span orelse if (known_end == null or pane.file != null) panes.File.spanOf(old, new) else null; const end = known_end orelse modal.positionAt(new, new.len - found.?.tail); t.last_edit = .{ .row = @as(i32, @intCast(end.row)) + row0, .col = @intCast(end.col) }; - if (pane.file) |*f| return panes.File.setContentSpan(p, f, new, found); + if (pane.file) |*f| return panes.File.setContentSpan(e.p, f, new, found); // A terminal's edit copy rewritten: the text it replaces freed. - const overlay = if (pane.ovl) |*value| value else return retireEditText(p.editor(), new); + const overlay = if (pane.ovl) |*value| value else return retireEditText(e, new); for (0..pane.sel.len) |button| { pane.clearPointerSelection(button); pane.sel[button].state = .none; } - p.gpa.free(overlay.text); + e.gpa.free(overlay.text); overlay.text = new; } @@ -750,11 +750,11 @@ pub fn retireEditText(e: Editor, new: []u8) void { /// helix's indent for a line opened after byte `at` of `row` (indent.zig), /// from the file's tree, where its grammar has an indent query. -fn treeIndent(p: *Pardes, t: *Text, text: []const u8, row: usize, at: usize) Error!?[]const u8 { +fn treeIndent(e: Editor, t: *Text, text: []const u8, row: usize, at: usize) Error!?[]const u8 { const f = bodyFile(t) orelse return null; const l = indents.lang(f.path) orelse return null; - const tree = normal.fileTree(p, f) orelse return null; - return indents.forNewline(p.scratch.allocator(), l, tree, text, row, at); + const tree = normal.fileTree(e.p, f) orelse return null; + return indents.forNewline(e.scratch, l, tree, text, row, at); } /// helix's default auto-pairs (auto_pairs.rs DEFAULT_PAIRS): `o` opens one @@ -785,15 +785,15 @@ pub fn clampFileCursor(t: *Text) bool { pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) Error!void { if (t.what == .body) if (t.pane()) |pane| if (pane.addon != null) return; - pinPaneCursor(p, t); + pinPaneCursor(p.editor(), t); _ = clampFileCursor(t); // snapshot once per insert session (WITH the pre-insert selection) so // `u` undoes the whole session and restores what was selected - try pushUndo(p, t); + try pushUndo(p.editor(), t); t.select = false; t.restore_cursor = false; t.sticky_col = -1; - const text = flatSurface(p, t) catch { + const text = flatSurface(p.editor(), t) catch { t.mode = .insert; t.vsel.active = false; t.normal.clear(); @@ -826,7 +826,7 @@ pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) Error!void var now = text; if (hi < text.len and gap >= text.len and !terminal) { const grown = try std.mem.concat(p.gpa, u8, &.{ text, "\n" }); - try setEditText(p, t, grown); + try setEditText(p.editor(), t, grown); now = grown; // what setEditText keeps; `text` may be gone } const gc = modal.positionAt(now, gap); @@ -850,13 +850,13 @@ pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) Error!void 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 t.cur_row; - const eb = (try editText(p, t, abs, abs, -1)) orelse return; + const eb = (try editText(p.editor(), t, abs, abs, -1)) orelse return; const row: usize = @intCast(@max(0, abs - eb.row0)); // helix open_below/open_above: the tree's indent for a line // after the one above the new one, else acme's copy of this one const above = if (below) row else row -| 1; const after = if (!below and row == 0) 0 else panes.File.textLineStart(t, eb.text, above) + panes.File.textLine(t, eb.text, above).len; - const ind = (try treeIndent(p, t, eb.text, above, after)) orelse modal.indentText(modal.lineSlice(eb.text, row)); + const ind = (try treeIndent(p.editor(), t, eb.text, above, after)) orelse modal.indentText(modal.lineSlice(eb.text, row)); const arena = p.scratch.allocator(); const block_len = std.math.mul(usize, cnt, ind.len + 1) catch return error.OutOfMemory; const block = try arena.alloc(u8, block_len); @@ -878,12 +878,12 @@ pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) Error!void else .{ .row = row, .col = 0 }; const new = try modal.insertAt(p.gpa, eb.text, at, block); - try setEditText(p, t, new); + try setEditText(p.editor(), 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_count == 1) opened: { - const t2 = flatSurface(p, t) catch break :opened; + const t2 = flatSurface(p.editor(), t) catch break :opened; var rs: [Text.max_selections]modal.Selection = undefined; const m = @min(cnt, Text.max_selections); for (0..m) |k| { @@ -923,12 +923,12 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) Error!void { return; } // helix commit_undo_checkpoint: `u` after the session goes back to here - if (hit(key, config.insert_checkpoint)) return pushUndo(p, t); + if (hit(key, config.insert_checkpoint)) return pushUndo(p.editor(), t); // helix maps every range through each insert-mode edit (Range::map): // the edits below work on the bare cursor, and the range the cursor // heads is carried through what they did to the text afterwards if (!t.vsel.active) return insertEdit(p, t, key); - const old = flatSurface(p, t) catch return insertEdit(p, t, key); + const old = flatSurface(p.editor(), t) catch return insertEdit(p, t, key); const r = t.primaryRange(old, 0); const c = modal.selectionCursor(old, r); const old_len = old.len; @@ -936,7 +936,7 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) Error!void { t.vsel.active = false; try insertEdit(p, t, key); if (t.mode != .insert) return; - const new = try flatSurface(p, t); + const new = try flatSurface(p.editor(), t); const c2 = modal.offsetAt(new, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) }); // every insert-mode edit happens at the cursor: an insertion there, or // a deletion that ends there (backward) or starts there (forward) @@ -991,11 +991,11 @@ fn mapThroughEdit(pos: usize, at: usize, del: usize, ins: usize, before: bool) u fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { t.vsel.active = false; - if (!t.cur_pinned) pinPaneCursor(p, t); + if (!t.cur_pinned) pinPaneCursor(p.editor(), t); _ = clampFileCursor(t); switch (key.cp) { Key.left, Key.right, Key.up, Key.down => { - const lines = try paneCursorLines(p, t); + const lines = try paneCursorLines(p.editor(), t); const cur0 = t.toModalCursor(); // In a pane's tag, Up on its first line collapses it and Down // on its last expands it, where they would move nothing; acme's @@ -1024,7 +1024,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { Key.page_up, Key.page_down => { // helix binds insert pageup/pagedown to the same view // scroll + cursor snap as normal mode - const flat = try flatSurface(p, t); + const flat = try flatSurface(p.editor(), t); const range = t.primaryRange(flat, 0); if (t.what != .body) return; const step: i32 = @intCast(@max(1, (t.pane() orelse return).rows)); @@ -1039,7 +1039,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { }, Key.end => { // helix insert End: past the last char (goto_line_end_newline) - const text = try flatSurface(p, t); + const text = try flatSurface(p.editor(), t); const cur0 = t.toModalCursor(); t.cur_col = @intCast(panes.File.textLine(t, text, cur0.row).len); t.cur_pinned = true; @@ -1048,7 +1048,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { }, else => {}, } - const eb = (try editText(p, t, t.cur_row, t.cur_row, t.cur_col)) orelse return; + const eb = (try editText(p.editor(), t, t.cur_row, t.cur_row, t.cur_col)) orelse return; const text = eb.text; const c = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - eb.row0)), .col = @intCast(@max(0, t.cur_col)) }; if (key.text.len > 0 and !key.ctrl and !key.alt) { @@ -1065,7 +1065,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { t.last_edit = .{ .row = @intCast(end.row), .col = @intCast(end.col) }; } else { const new = try modal.spliceAlloc(p.gpa, text, at, at, key.text); - try setEditTextSpan(p, t, new, end, .{ .head = at, .tail = text.len - at }); + try setEditTextSpan(p.editor(), t, new, end, .{ .head = at, .tail = text.len - at }); } t.cur_row = @as(i32, @intCast(end.row)) + eb.row0; t.cur_col = @intCast(end.col); @@ -1076,7 +1076,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { // 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) - ((try editText(p, t, t.cur_row - 1, t.cur_row, 0)) orelse return) + ((try editText(p.editor(), t, t.cur_row - 1, t.cur_row, 0)) orelse return) else eb; const c2 = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - e2.row0)), .col = c.col }; @@ -1086,7 +1086,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { const from = @min(wr.anchor, wr.head); const fc = modal.positionAt(e2.text, from); const new = try modal.deleteSpan(p.gpa, e2.text, fc, c2); - try setEditTextEnd(p, t, new, fc); + try setEditTextEnd(p.editor(), t, new, fc); t.cur_row = @as(i32, @intCast(fc.row)) + e2.row0; t.cur_col = @intCast(fc.col); t.cur_pinned = true; @@ -1095,7 +1095,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { } 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)) - ((try editText(p, t, t.cur_row, t.cur_row + 1, t.cur_col)) orelse return) + ((try editText(p.editor(), t, t.cur_row, t.cur_row + 1, t.cur_col)) orelse return) else eb; const c2 = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - e2.row0)), .col = c.col }; @@ -1104,13 +1104,13 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { const to = @max(wr.anchor, wr.head); if (to <= g) return; const new = try modal.deleteSpan(p.gpa, e2.text, c2, modal.positionAt(e2.text, to)); - try setEditTextEnd(p, t, new, c2); + try setEditTextEnd(p.editor(), t, new, c2); t.cur_pinned = true; return; } if (hit(key, config.kill_to_line_start)) { const new = try modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = 0 }, c); - try setEditTextEnd(p, t, new, .{ .row = c.row, .col = 0 }); + try setEditTextEnd(p.editor(), t, new, .{ .row = c.row, .col = 0 }); t.cur_col = 0; t.cur_pinned = true; t.show(); @@ -1119,7 +1119,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { if (hit(key, config.kill_to_line_end)) { const llen = modal.lineSlice(text, c.row).len; const new = try modal.deleteSpan(p.gpa, text, c, .{ .row = c.row, .col = llen }); - try setEditTextEnd(p, t, new, c); + try setEditTextEnd(p.editor(), t, new, c); t.cur_pinned = true; return; } @@ -1132,7 +1132,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { // cursor go and the new line takes the indent if (std.mem.indexOfNone(u8, before, " \t") == null) { const new = try modal.insertAt(p.gpa, text, .{ .row = c.row, .col = 0 }, "\n"); - try setEditTextEnd(p, t, new, .{ .row = c.row + 1, .col = 0 }); + try setEditTextEnd(p.editor(), t, new, .{ .row = c.row + 1, .col = 0 }); t.cur_row += 1; t.cur_pinned = true; t.show(); @@ -1146,7 +1146,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { // indent, the cursor to one a level in. const arena = p.scratch.allocator(); const lead = modal.indentText(line); - const tree = try treeIndent(p, t, text, c.row, panes.File.textLineStart(t, text, c.row) + before.len); + const tree = try treeIndent(p.editor(), t, text, c.row, panes.File.textLineStart(t, text, c.row) + before.len); const pair = bodyFile(t) != null and c.col < line.len and opensPair(before[before.len - 1], line[c.col]); const more = modal.newlineIndentWidth(line, c.col) > lead.len; const base = tree orelse if (pair or !more) lead else try std.mem.concat(arena, u8, &.{ lead, indents.unit(null, lead) }); @@ -1158,7 +1158,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { const cut = try modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = kept }, c); defer p.gpa.free(cut); const new = try modal.insertAt(p.gpa, cut, .{ .row = c.row, .col = kept }, block); - try setEditTextEnd(p, t, new, if (pair) .{ .row = c.row + 2, .col = base.len } else .{ .row = c.row + 1, .col = mid.len }); + try setEditTextEnd(p.editor(), t, new, if (pair) .{ .row = c.row + 2, .col = base.len } else .{ .row = c.row + 1, .col = mid.len }); t.cur_row += 1; t.cur_col = @intCast(mid.len); t.cur_pinned = true; @@ -1191,7 +1191,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { } else { const new = if (e > s) try modal.spliceAlloc(p.gpa, text, s, e, "") else try p.gpa.dupe(u8, text); const span: panes.File.Span = if (e > s) .{ .head = s, .tail = text.len - e } else .{ .head = text.len, .tail = 0 }; - try setEditTextSpan(p, t, new, .{ .row = c.row, .col = prev }, span); + try setEditTextSpan(p.editor(), t, new, .{ .row = c.row, .col = prev }, span); } t.cur_col = @intCast(prev); t.cur_pinned = true; @@ -1201,12 +1201,12 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { // at col 0: eat the newline above (join up) — a terminal grows // its buffer over the row it is joining with if (t.cur_row <= 0) return; - const e2 = (try editText(p, t, t.cur_row - 1, t.cur_row, 0)) orelse return; + const e2 = (try editText(p.editor(), 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 = try modal.deleteSpan(p.gpa, e2.text, .{ .row = row - 1, .col = prevlen }, .{ .row = row, .col = 0 }); - try setEditTextEnd(p, t, new, .{ .row = row - 1, .col = prevlen }); + try setEditTextEnd(p.editor(), t, new, .{ .row = row - 1, .col = prevlen }); t.cur_row -= 1; t.cur_col = @intCast(prevlen); t.cur_pinned = true; @@ -1219,13 +1219,13 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { if (c.col < line.len) { const at = modal.offsetAt(text, c); const new = try modal.spliceAlloc(p.gpa, text, at, modal.nextGrapheme(text, at), ""); - try setEditTextEnd(p, t, new, c); + try setEditTextEnd(p.editor(), t, new, c); } else { - const e2 = (try editText(p, t, t.cur_row, t.cur_row + 1, t.cur_col)) orelse return; + const e2 = (try editText(p.editor(), 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 = try modal.deleteSpan(p.gpa, e2.text, .{ .row = row, .col = c.col }, .{ .row = row + 1, .col = 0 }); - try setEditTextEnd(p, t, new, .{ .row = row, .col = c.col }); + try setEditTextEnd(p.editor(), t, new, .{ .row = row, .col = c.col }); } t.cur_pinned = true; }, @@ -1257,14 +1257,14 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { } pub fn insertTab(p: *Pardes, t: *Text) Error!void { - const eb = (try editText(p, t, t.cur_row, t.cur_row, t.cur_col)) orelse return; + const eb = (try editText(p.editor(), t, t.cur_row, t.cur_row, 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 pad = modal.INDENT_W - (c.col % modal.INDENT_W); const new = try modal.insertAt(p.gpa, eb.text, c, " "[0..pad]); - try setEditTextEnd(p, t, new, .{ .row = c.row, .col = c.col + pad }); + try setEditTextEnd(p.editor(), t, new, .{ .row = c.row, .col = c.col + pad }); t.cur_col += @intCast(pad); t.cur_pinned = true; t.show(); @@ -1284,10 +1284,10 @@ 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, t: *Text) Error![]const u8 { - const text = try flatSurface(p, t); +fn vselText(e: Editor, t: *Text) Error![]const u8 { + const text = try flatSurface(e, t); const r = t.primaryRange(text, 0); - return p.scratch.allocator().dupe(u8, text[@min(r.anchor, r.head)..@max(r.anchor, r.head)]); + return e.scratch.dupe(u8, text[@min(r.anchor, r.head)..@max(r.anchor, r.head)]); } pub fn normalDelete(p: *Pardes, t: *Text, yank: bool) Error!void { @@ -1297,14 +1297,14 @@ pub fn normalDelete(p: *Pardes, t: *Text, yank: bool) Error!void { // cell too, where the delete joins the lines. if (!t.vsel.active) t.vsel = .{ .active = true, .row = t.cur_row, .col = t.cur_col, .explicit = false }; const b = vselBounds(t); - if (yank) try setYank(p.editor(), try vselText(p, t)); // read the range before the move - try pushUndo(p, t); - const eb = (try editTextEol(p, t, b)) orelse { + if (yank) try setYank(p.editor(), try vselText(p.editor(), t)); // read the range before the move + try pushUndo(p.editor(), t); + const eb = (try editTextEol(p.editor(), t, b)) orelse { t.vsel.active = false; return; }; const new = try deleteSelection(p, t, eb); - try setEditText(p, t, new); + try setEditText(p.editor(), t, new); t.cur_row = b.lo_row; t.cur_col = b.lo_col; t.clampCursor(new, eb.row0); @@ -1316,12 +1316,12 @@ pub fn normalYank(p: *Pardes, t: *Text) Error!void { try setYank(p.editor(), text); return; }; - try setYank(p.editor(), try if (t.vsel.active) vselText(p, t) else selText(p, t)); + try setYank(p.editor(), try if (t.vsel.active) vselText(p.editor(), t) else selText(p.editor(), t)); } pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usize) Error!void { if (y0.len == 0) return; - try pushUndo(p, t); + try pushUndo(p.editor(), t); t.select = false; t.sticky_col = -1; const arena = p.scratch.allocator(); @@ -1336,7 +1336,7 @@ pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usiz vselBounds(t) else .{ .lo_row = t.cur_row, .lo_col = t.cur_col, .hi_row = t.cur_row, .hi_col = t.cur_col }; - const eb = (try editText(p, t, b.lo_row, b.hi_row, -1)) orelse return; + const eb = (try editText(p.editor(), 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]; @@ -1352,7 +1352,7 @@ pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usiz out = try modal.pasteLineBelow(p.gpa, eb.text, row, block_text); t.cur_row = @as(i32, @intCast(row + n)) + row0; } - try setEditText(p, t, out); + try setEditText(p.editor(), 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, t.cur_row - row0))).len; @@ -1369,7 +1369,7 @@ pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usiz break :blk .{ .row = hrow, .col = gcol }; }; const out = try modal.insertAt(p.gpa, eb.text, at, y); - try setEditText(p, t, out); + try setEditText(p.editor(), 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) { @@ -1389,20 +1389,20 @@ pub fn normalChange(p: *Pardes, t: *Text) Error!void { t.sticky_col = -1; if (t.vsel.active) { const b = vselBounds(t); - const eb = (try editTextEol(p, t, b)) orelse return; + const eb = (try editTextEol(p.editor(), 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) { - try setYank(p.editor(), try vselText(p, t)); - try pushUndo(p, t); + try setYank(p.editor(), try vselText(p.editor(), t)); + try pushUndo(p.editor(), t); const d = try modal.deleteLines(p.gpa, eb.text, @intCast(@max(0, b.lo_row - eb.row0)), @intCast(@max(0, b.hi_row - eb.row0))); - try setEditText(p, t, d); + try setEditText(p.editor(), t, d); const n = modal.lineCount(d); const row: usize = @min(@as(usize, @intCast(@max(0, b.lo_row - eb.row0))), if (n == 0) 0 else n - 1); const ind = modal.indentText(modal.lineSlice(d, row)); const arena = p.scratch.allocator(); const block = try std.fmt.allocPrint(arena, "{s}\n", .{ind}); const new = try modal.insertAt(p.gpa, d, .{ .row = row, .col = 0 }, block); - try setEditText(p, t, new); + try setEditText(p.editor(), t, new); t.cur_row = @as(i32, @intCast(row)) + eb.row0; t.cur_col = @intCast(ind.len); t.vsel.active = false; @@ -1412,10 +1412,10 @@ pub fn normalChange(p: *Pardes, t: *Text) Error!void { t.show(); return; } - try setYank(p.editor(), try vselText(p, t)); - try pushUndo(p, t); + try setYank(p.editor(), try vselText(p.editor(), t)); + try pushUndo(p.editor(), t); const new = try deleteSelection(p, t, eb); - try setEditText(p, t, new); + try setEditText(p.editor(), t, new); t.cur_row = b.lo_row; t.cur_col = b.lo_col; t.clampCursor(new, eb.row0); @@ -1423,12 +1423,12 @@ pub fn normalChange(p: *Pardes, t: *Text) Error!void { t.normal.clear(); return; } - try pushUndo(p, t); - const eb = (try editTextEol(p, t, selRows(t))) orelse return; + try pushUndo(p.editor(), t); + const eb = (try editTextEol(p.editor(), t, selRows(t))) orelse return; const r = t.primaryRange(eb.text, eb.row0); try setYank(p.editor(), eb.text[r.anchor..r.head]); const new = try modal.spliceAlloc(p.gpa, eb.text, r.anchor, r.head, ""); - try setEditText(p, t, new); + try setEditText(p.editor(), t, new); const llen = modal.lineSlice(new, @intCast(@max(0, t.cur_row - eb.row0))).len; t.cur_col = @min(t.cur_col, @as(i32, @intCast(llen))); t.mode = .insert; @@ -1467,8 +1467,8 @@ fn setEditCells(p: *Pardes, t: *Text, new: []u8, row0: i32, cells: []const Text. const ac = modal.positionAt(new, c.anc); s.* = .{ .row = @as(i32, @intCast(cc.row)) + row0, .col = @intCast(cc.col), .arow = @as(i32, @intCast(ac.row)) + row0, .acol = @intCast(ac.col) }; } - try setEditText(p, t, new); - const text = try flatSurface(p, t); + try setEditText(p.editor(), t, new); + const text = try flatSurface(p.editor(), t); var rs: [Text.max_selections]modal.Selection = undefined; for (sels[0..cells.len], rs[0..cells.len]) |s, *r| r.* = Text.cellRange(text, s.arow, s.acol, s.row, s.col); t.setRanges(text, rs[0..cells.len], &.{}, pri, expl); @@ -1478,7 +1478,7 @@ fn setEditCells(p: *Pardes, t: *Text, new: []u8, row0: i32, cells: []const Text. /// newlines included (helix), so `xrz` joins the selected lines pub fn normalReplaceChar(p: *Pardes, t: *Text, ch: u21) Error!void { t.select = false; - const eb = (try editTextEol(p, t, selRows(t))) orelse return; + const eb = (try editTextEol(p.editor(), 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); @@ -1489,9 +1489,9 @@ pub fn normalReplaceChar(p: *Pardes, t: *Text, ch: u21) Error!void { const encoded_len = std.unicode.utf8Encode(ch, &encoded) catch return; // a surrogate half types nothing const rep = try p.scratch.allocator().alloc(u8, graphemes * encoded_len); for (0..graphemes) |i| @memcpy(rep[i * encoded_len ..][0..encoded_len], encoded[0..encoded_len]); - try pushUndo(p, t); + try pushUndo(p.editor(), t); const new = try modal.spliceAlloc(p.gpa, eb.text, lo, hi, rep); - try setEditText(p, t, new); + try setEditText(p.editor(), t, new); const end = lo + rep.len; const mapped: modal.Selection = if (before.head < before.anchor) .{ .anchor = end, .head = lo } @@ -1513,12 +1513,12 @@ pub fn chordReplace(p: *Pardes, t: *Text) Error!void { fn replaceWithText(p: *Pardes, t: *Text, y: []const u8) Error!void { if (y.len == 0) return; t.select = false; - const eb = (try editTextEol(p, t, selRows(t))) orelse return; + const eb = (try editTextEol(p.editor(), t, selRows(t))) orelse return; const r = t.primaryRange(eb.text, eb.row0); const lo = @min(r.anchor, r.head); - try pushUndo(p, t); + try pushUndo(p.editor(), t); const new = try modal.spliceAlloc(p.gpa, eb.text, lo, @max(r.anchor, r.head), y); - try setEditText(p, t, new); + try setEditText(p.editor(), t, new); const end = lo + y.len; t.setRange(new, eb.row0, if (r.head < r.anchor) .{ .anchor = end, .head = lo } else .{ .anchor = lo, .head = end }, false); } @@ -1527,11 +1527,11 @@ fn replaceWithText(p: *Pardes, t: *Text, y: []const u8) Error!void { /// keeping the selection (helix) pub fn normalCase(p: *Pardes, t: *Text, op: modal.CaseOp) Error!void { t.select = false; - const eb = (try editTextEol(p, t, selRows(t))) orelse return; + const eb = (try editTextEol(p.editor(), t, selRows(t))) orelse return; const r = t.primaryRange(eb.text, eb.row0); - try pushUndo(p, t); + try pushUndo(p.editor(), t); const new = try modal.changeCase(p.gpa, eb.text, @min(r.anchor, r.head), @max(r.anchor, r.head), op); - try setEditText(p, t, new); + try setEditText(p.editor(), t, new); } /// Where `pos` lands after `chs`, which are ascending and disjoint. @@ -1559,7 +1559,7 @@ pub fn normalJoin(p: *Pardes, t: *Text, select_space: bool) Error!void { // a join always eats the newline of its last line, so the buffer has // to reach one row PAST every range const b = allSelRows(t); - const eb = (try editText(p, t, b.lo_row, b.hi_row + 1, -1)) orelse return; + const eb = (try editText(p.editor(), t, b.lo_row, b.hi_row + 1, -1)) orelse return; const text = eb.text; var rs: [Text.max_selections]modal.Selection = undefined; const got = t.ranges(text, eb.row0, &rs); @@ -1590,7 +1590,7 @@ pub fn normalJoin(p: *Pardes, t: *Text, select_space: bool) Error!void { const chs = changes.items; const chs_len = chs.len; if (chs_len == 0) return; - try pushUndo(p, t); + try pushUndo(p.editor(), t); const new = try sam.apply(p.gpa, text, chs[0..chs_len]); // every range's cells ride through the edit; Alt-J replaces them with // the spaces, when it put any in @@ -1625,7 +1625,7 @@ pub fn normalJoin(p: *Pardes, t: *Text, select_space: bool) Error!void { /// and the primary moves with the text it had. pub fn normalRotateContents(p: *Pardes, t: *Text, forward: bool, cnt: usize) Error!void { const expl = t.vsel.active and t.vsel.explicit; - const eb = (try editTextEol(p, t, allSelRows(t))) orelse return; + const eb = (try editTextEol(p.editor(), t, allSelRows(t))) orelse return; const text = eb.text; var rs: [Text.max_selections]modal.Selection = undefined; const got = t.ranges(text, eb.row0, &rs); @@ -1641,7 +1641,7 @@ pub fn normalRotateContents(p: *Pardes, t: *Text, forward: bool, cnt: usize) Err .text = text[@min(src.anchor, src.head)..@max(src.anchor, src.head)], }; } - try pushUndo(p, t); + try pushUndo(p.editor(), t); const new = try sam.apply(p.gpa, text, chs[0..n]); var cells: [Text.max_selections]Text.Cells = undefined; var delta: i64 = 0; @@ -1660,7 +1660,7 @@ pub fn normalRotateContents(p: *Pardes, t: *Text, forward: bool, cnt: usize) Err /// in display cells. A range over several lines aligns nothing. pub fn normalAlign(p: *Pardes, t: *Text) Error!void { const expl = t.vsel.active and t.vsel.explicit; - const eb = (try editTextEol(p, t, allSelRows(t))) orelse return; + const eb = (try editTextEol(p.editor(), t, allSelRows(t))) orelse return; const text = eb.text; var rs: [Text.max_selections]modal.Selection = undefined; const got = t.ranges(text, eb.row0, &rs); @@ -1709,7 +1709,7 @@ pub fn normalAlign(p: *Pardes, t: *Text) Error!void { m += 1; } if (m == 0) return; - try pushUndo(p, t); + try pushUndo(p.editor(), t); const new = try sam.apply(p.gpa, text, chs[0..m]); var cells: [Text.max_selections]Text.Cells = undefined; for (rs[0..n], cells[0..n]) |r, *cell| { @@ -1722,7 +1722,7 @@ pub fn normalAlign(p: *Pardes, t: *Text) Error!void { pub fn normalIndent(p: *Pardes, t: *Text, cnt: usize, add: bool) Error!void { t.select = false; const sr = selRows(t); - const eb = (try editText(p, t, sr.lo_row, sr.hi_row, -1)) orelse return; + const eb = (try editText(p.editor(), t, sr.lo_row, sr.hi_row, -1)) orelse return; const text = eb.text; const range = t.primaryRange(text, eb.row0); const span = Text.rangeLineSpan(text, range); @@ -1763,7 +1763,7 @@ pub fn normalIndent(p: *Pardes, t: *Text, cnt: usize, add: bool) Error!void { } } if (chs_len == 0) return; - try pushUndo(p, t); + try pushUndo(p.editor(), 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)) }) @@ -1772,7 +1772,7 @@ pub fn normalIndent(p: *Pardes, t: *Text, cnt: usize, add: bool) Error!void { const new = try sam.apply(p.gpa, text, chs[0..chs_len]); const nc = mapThroughChanges(chs[0..chs_len], cur_off); const na = mapThroughChanges(chs[0..chs_len], anc_off); - try setEditText(p, t, new); + try setEditText(p.editor(), t, new); const cc = modal.positionAt(new, nc); const ac = modal.positionAt(new, na); t.cur_row = @as(i32, @intCast(cc.row)) + eb.row0; @@ -1791,9 +1791,9 @@ pub fn normalToggleComment(p: *Pardes, t: *Text) Error!void { t.select = false; // helix exit_select_mode // the buffer must cover every cursor's rows, not just the primary's const b = allSelRows(t); - const surface = try flatSurface(p, t); + const surface = try flatSurface(p.editor(), t); const last_row = @as(i32, @intCast(panes.File.textLineCount(t, surface))) - 1; - const eb = (try editText(p, t, b.lo_row, @min(b.hi_row + 1, last_row), -1)) orelse return; + const eb = (try editText(p.editor(), t, b.lo_row, @min(b.hi_row + 1, last_row), -1)) orelse return; const text = eb.text; var rs: [Text.max_selections]modal.Selection = undefined; const got = t.ranges(text, eb.row0, &rs); @@ -1854,7 +1854,7 @@ pub fn normalToggleComment(p: *Pardes, t: *Text) Error!void { .{ .q0 = @intCast(at), .q1 = @intCast(at), .text = ins }; chs_len += 1; } - try pushUndo(p, t); + try pushUndo(p.editor(), t); // one edit, and the WHOLE selection rides through it (helix maps the // selection with the transaction) var cells: [Text.max_selections]Text.Cells = undefined; @@ -1867,15 +1867,15 @@ pub fn normalToggleComment(p: *Pardes, t: *Text) Error!void { } pub fn normalAdjustNumber(p: *Pardes, t: *Text, delta: i64) Error!void { - const eb = (try editTextEol(p, t, selRows(t))) orelse return; + const eb = (try editTextEol(p.editor(), t, selRows(t))) orelse return; const r = t.primaryRange(eb.text, eb.row0); const lo = @min(r.anchor, r.head); const hi = @max(r.anchor, r.head); const rep = (modal.incrementDecimal(p.scratch.allocator(), eb.text[lo..hi], delta) catch null) orelse return; - try pushUndo(p, t); + try pushUndo(p.editor(), t); t.select = false; const new = try modal.spliceAlloc(p.gpa, eb.text, lo, hi, rep); - try setEditText(p, t, new); + try setEditText(p.editor(), t, new); t.setRange(new, eb.row0, .{ .anchor = lo, .head = lo + rep.len }, false); } @@ -1885,15 +1885,15 @@ pub fn addNewline(p: *Pardes, t: *Text, below: bool, cnt: usize) Error!void { // above the selection's first line, below its last (helix line_range) const sr = selRows(t); const at = if (below) sr.hi_row else sr.lo_row; - const eb = (try editText(p, t, at, at, -1)) orelse return; - try pushUndo(p, t); + const eb = (try editText(p.editor(), t, at, at, -1)) orelse return; + try pushUndo(p.editor(), t); const row: usize = @intCast(@max(0, at - eb.row0)); const arena = p.scratch.allocator(); const nl = try arena.alloc(u8, cnt); @memset(nl, '\n'); const llen = modal.lineSlice(eb.text, row).len; const new = try modal.insertAt(p.gpa, eb.text, .{ .row = row, .col = if (below) llen else 0 }, nl); - try setEditText(p, t, new); + try setEditText(p.editor(), t, new); if (!below) { // the whole selection moved down; stay on it const n: i32 = @intCast(cnt); @@ -1948,7 +1948,7 @@ pub fn textobjectSelect(p: *Pardes, t: *Text, text: []const u8, obj: u21, around }, else => {}, } - const lines = try paneCursorLines(p, t); + const lines = try paneCursorLines(p.editor(), t); const cur = modal.positionAt(text, modal.selectionCursor(text, range)); const pair: ?modal.Range = switch (obj) { '\'', '"', '`' => modal.enclosingQuote(lines, cur, @intCast(obj)), @@ -1975,15 +1975,15 @@ pub fn textobjectSelect(p: *Pardes, t: *Text, text: []const u8, obj: u21, around pub fn surroundAdd(p: *Pardes, t: *Text, ch: u21) Error!void { const pr = pairFor(ch) orelse return; t.select = false; - const eb = (try editTextEol(p, t, selRows(t))) orelse return; + const eb = (try editTextEol(p.editor(), t, selRows(t))) orelse return; const r = t.primaryRange(eb.text, eb.row0); const lo = @min(r.anchor, r.head); const hi = @max(r.anchor, r.head); - try pushUndo(p, t); + try pushUndo(p.editor(), t); const open = [1]u8{pr.o}; const close = [1]u8{pr.c}; const new = try sam.apply(p.gpa, eb.text, &.{ .{ .q0 = @intCast(lo), .q1 = @intCast(lo), .text = &open }, .{ .q0 = @intCast(hi), .q1 = @intCast(hi), .text = &close } }); - try setEditText(p, t, new); + try setEditText(p.editor(), t, new); // the wrapped range keeps the direction it had (helix with_direction) t.setRange(new, eb.row0, if (r.head < r.anchor) .{ .anchor = hi + 2, .head = lo } else .{ .anchor = lo, .head = hi + 2 }, false); } @@ -1991,7 +1991,7 @@ pub fn surroundAdd(p: *Pardes, t: *Text, ch: u21) Error!void { /// `md`: delete the enclosing pair's chars; the cursor maps through pub fn surroundDelete(p: *Pardes, t: *Text, ch: u21) Error!void { const pr = pairFor(ch) orelse return; - const lines = try paneCursorLines(p, t); + const lines = try paneCursorLines(p.editor(), t); const cur = t.toModalCursor(); const r = (if (pr.o == pr.c) modal.enclosingQuote(lines, cur, pr.o) @@ -1999,12 +1999,12 @@ pub fn surroundDelete(p: *Pardes, t: *Text, ch: u21) Error!void { 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 = (try editText(p, t, lo, hi, -1)) orelse return; + const eb = (try editText(p.editor(), 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 }; - try pushUndo(p, t); + try pushUndo(p.editor(), 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 }); @@ -2012,7 +2012,7 @@ pub fn surroundDelete(p: *Pardes, t: *Text, ch: u21) Error!void { .{ .q0 = @intCast(a_off), .q1 = @intCast(modal.nextGrapheme(text, a_off)), .text = "" }, .{ .q0 = @intCast(b_off), .q1 = @intCast(modal.nextGrapheme(text, b_off)), .text = "" }, }); - try setEditText(p, t, new); + try setEditText(p.editor(), t, new); var nc = cur_off; if (nc > b_off) nc -= 1; if (nc > a_off) nc -= 1; @@ -2028,57 +2028,57 @@ pub fn surroundDelete(p: *Pardes, t: *Text, ch: u21) Error!void { pub fn surroundReplace(p: *Pardes, t: *Text, from: u21, to: u21) Error!void { const fp = pairFor(from) orelse return; const tp = pairFor(to) orelse return; - const lines = try paneCursorLines(p, t); + const lines = try paneCursorLines(p.editor(), t); 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 = (try editText(p, t, @as(i32, @intCast(r.a.row)), @as(i32, @intCast(r.b.row)), -1)) orelse return; + const eb = (try editText(p.editor(), 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); - try pushUndo(p, t); + try pushUndo(p.editor(), t); const out = try p.gpa.dupe(u8, eb.text); out[modal.lineStartOffset(out, ar) + r.a.col] = tp.o; out[modal.lineStartOffset(out, br) + r.b.col] = tp.c; - try setEditText(p, t, out); + try setEditText(p.editor(), t, out); } -pub fn pushUndo(p: *Pardes, t: *Text) error{OutOfMemory}!void { +pub fn pushUndo(e: Editor, t: *Text) error{OutOfMemory}!void { // one keystroke, one undo step — even when it edited at ten cursors. - if (!p.multi_first) return; + if (!e.multi_first.*) return; switch (t.what) { // A B1 chord took its one undo point when it began (mouse.zig). - .body => if (p.view().chord_hold) return, - .tag, .column, .workspace => return t.remember(p.gpa, if (t.own) |own| .{ .text = own } else null), + .body => if (e.p.view().chord_hold) return, + .tag, .column, .workspace => return t.remember(e.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() orelse return; - if (pane.file != null) return panes.File.pushUndo(p, pane); - return pane.body.remember(p.gpa, pane.ovl); + if (pane.file != null) return panes.File.pushUndo(e.p, pane); + return pane.body.remember(e.gpa, pane.ovl); } /// Undo (back) or redo one step of the text's history: its file's, its /// terminal overlay's, or a tag's or header's own. -pub fn undoStep(p: *Pardes, t: *Text, back: bool) error{OutOfMemory}!void { - if (t.what == .tag or t.what == .column or t.what == .workspace) return stepOwn(p, t, back); +pub fn undoStep(e: Editor, t: *Text, back: bool) error{OutOfMemory}!void { + if (t.what == .tag or t.what == .column or t.what == .workspace) return stepOwn(e, t, back); if (t.what != .body) return; const pane = t.pane() orelse return; - if (pane.file != null) return panes.File.undoStep(p, pane, back); + if (pane.file != null) return panes.File.undoStep(e.p, pane, back); // A terminal's edit copy, as it was. - const to = (try pane.body.step(p.gpa, pane.ovl, back)) orelse return; - if (pane.ovl) |o| p.gpa.free(o.text); + const to = (try pane.body.step(e.gpa, pane.ovl, back)) orelse return; + if (pane.ovl) |o| e.gpa.free(o.text); pane.ovl = to.ovl; pane.ensureCursorVisible(); } /// 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) error{OutOfMemory}!void { - const to = (try t.step(p.gpa, if (t.own) |own| .{ .text = own } else null, back)) orelse return; - if (t.own) |own| p.gpa.free(own); +fn stepOwn(e: Editor, t: *Text, back: bool) error{OutOfMemory}!void { + const to = (try t.step(e.gpa, if (t.own) |own| .{ .text = own } else null, back)) orelse return; + if (t.own) |own| e.gpa.free(own); t.own = if (to.ovl) |buffer| buffer.text else null; } @@ -2330,10 +2330,10 @@ test "flat text replacement preserves a terminal fragment origin and direction" 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); + const lines = try paneCursorLines(p.editor(), &pane.body); try std.testing.expectEqualStrings("first", lines[0]); try std.testing.expectEqualStrings("λλ", lines[3]); - const flat = try flatSurface(p, &pane.body); + const flat = try flatSurface(p.editor(), &pane.body); try std.testing.expect(std.mem.startsWith(u8, flat, "first\nsecond\nthird\nλλ\n")); } @@ -2430,10 +2430,10 @@ test "a typed edit's known end is where the texts' comparison would find it" { const base = try p.gpa.dupe(u8, pane.file.?.content); defer p.gpa.free(base); const scanned = try modal.insertAt(p.gpa, base, c.at, c.s); - try setEditTextEnd(p, t, scanned, null); + try setEditTextEnd(p.editor(), t, scanned, null); const by_scan = t.last_edit.?; const known = try modal.insertAt(p.gpa, base, c.at, c.s); - try setEditTextEnd(p, t, known, modal.advanceBy(c.at, c.s)); + try setEditTextEnd(p.editor(), t, known, modal.advanceBy(c.at, c.s)); try std.testing.expectEqual(by_scan.row, t.last_edit.?.row); try std.testing.expectEqual(by_scan.col, t.last_edit.?.col); } diff --git a/src/exec.zig b/src/exec.zig index 4ab5a37f..f2fb30d4 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -32,7 +32,7 @@ const Pardes = pardes.Pardes; pub fn chordEachSel(p: *Pardes, pane: *Pane, cmd: Builtin) bool { const v = p.view(); if (pane.body.nsel == 0) return false; - const text = edit.flatSurface(p, &pane.body) catch return false; + const text = edit.flatSurface(p.editor(), &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; @@ -118,7 +118,7 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l @as(i32, @intCast(panes.File.rawAtDisplay(raw_line, @intCast(@max(0, clicked.c0))))) else if (clicked.r0 >= pane.tag_rows) edit.paneByteAtDisplay( - p, + p.editor(), &pane.body, wrapped.line, wrapped.at, diff --git a/src/keys.zig b/src/keys.zig index 413818ed..8a9006dc 100644 --- a/src/keys.zig +++ b/src/keys.zig @@ -381,7 +381,7 @@ pub fn handleKey(p: *Pardes, key: Key) void { if (t.what != .body) { // An explicit selection, else the word under the cursor in the // text as it is shown: a tag's prefix is part of what a word is. - const shown = p.scratch.allocator().dupe(u8, edit.flatSurface(p, t) catch |err| return p.reportError(p.view().active, "exec", err)) catch |err| return p.reportError(p.view().active, "exec", err); + const shown = p.scratch.allocator().dupe(u8, edit.flatSurface(p.editor(), t) catch |err| return p.reportError(p.view().active, "exec", err)) catch |err| return p.reportError(p.view().active, "exec", err); const range = t.primaryRange(shown, 0); const lo = @min(range.anchor, range.head); const hi = @max(range.anchor, range.head); @@ -408,7 +408,7 @@ pub fn handleKey(p: *Pardes, key: Key) void { exec.runBuiltin(p, cmd, p.view().active, "", txt); return; } - edit.pinPaneCursor(p, &pane.body); + edit.pinPaneCursor(p.editor(), &pane.body); const explicit = (if (pane.addon) |k| k.selection.len > 0 else false) or (pane.body.vsel.active and pane.body.vsel.explicit); if (explicit) { @@ -826,7 +826,7 @@ test "s in a header selects in the header's own text" { p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expect(p.view().header != null and pane.prompt == .none); var ranges: [Text.max_selections]modal.Selection = undefined; - const text = try edit.flatSurface(p, &p.global_tag); + const text = try edit.flatSurface(p.editor(), &p.global_tag); const got = p.global_tag.ranges(text, 0, &ranges); try std.testing.expectEqual(@as(usize, 2), got.n); // Newcol, Joincol try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); diff --git a/src/look.zig b/src/look.zig index 136a7a9c..62f6a7da 100644 --- a/src/look.zig +++ b/src/look.zig @@ -296,7 +296,7 @@ pub fn cursorWordSel(p: *Pardes, pane: *Pane) Pane.Sel { const vcol = if (pane.file != null) w.pad + panes.File.displayOffset(pane, pane.body.cur_row, w.at, pane.body.cur_col) + @as(i32, panes.File.gutterWidth(pane)) else blk: { - const lines = edit.paneCursorLines(p, &pane.body) catch break :blk pane.body.cur_col; + const lines = edit.paneCursorLines(p.editor(), &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))); @@ -372,7 +372,7 @@ pub fn runSearch(p: *Pardes, id: usize, pat_raw: []const u8, start: SearchStart, @memcpy(out[0..out_len], rows[0..out_len]); nrows = std.mem.count(u8, rows, "\n"); } else { - const lines = try edit.paneCursorLines(p, &pane.body); + const lines = try edit.paneCursorLines(p.editor(), &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; @@ -547,7 +547,7 @@ pub fn wordSpan(p: ?*pardes.Pardes, word: []const u8, cwd: []const u8, realbuf: } fn lookSpanIn(p: *Pardes, pane: *Pane, from: LookFrom, delta: i32, budget: *usize) ?Pane.LookSpot { - const lines = edit.paneCursorLines(p, &pane.body) catch return null; + const lines = edit.paneCursorLines(p.editor(), &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; @@ -636,7 +636,7 @@ pub fn lookWalk(p: *Pardes, delta: i32) void { } fn landLookSpot(p: *Pardes, id: usize, pane: *Pane, spot: Pane.LookSpot) void { - edit.pinPaneCursor(p, &pane.body); // fresh out of tty mode the cursor still tracks the shell + edit.pinPaneCursor(p.editor(), &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.nsel = 0; pane.body.cur_row = spot.row; @@ -751,7 +751,7 @@ pub fn focusPaneLine(p: *Pardes, id: usize, at: Spot, landing: enum { center, ke } fn selectSpan(p: *Pardes, pane: *Pane, at: Spot) void { - const text = edit.flatSurface(p, &pane.body) catch |err| return p.reportError(p.view().active, "look", err); + const text = edit.flatSurface(p.editor(), &pane.body) catch |err| return p.reportError(p.view().active, "look", err); // 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); @@ -1185,7 +1185,7 @@ fn closeAndMiss(p: *Pardes, id: usize, opened: usize, name: []const u8, why: []c fn lookTerminalAddress(p: *Pardes, id: usize, target: usize, expr: []const u8) void { const Addr = @import("ninep/addr.zig").Addr; const pane = p.panes[target].?; - const lines = edit.paneCursorLines(p, &pane.body) catch return missed(p, id, "{s}", .{"out of memory"}); + const lines = edit.paneCursorLines(p.editor(), &pane.body) catch return missed(p, id, "{s}", .{"out of memory"}); var text: std.ArrayList(u8) = .empty; const arena = p.scratch.allocator(); const row: usize = @intCast(@max(0, pane.body.cur_row)); @@ -1490,7 +1490,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { if (found == .pane and found.pane.id < MAX_PANES) if (p.panes[found.pane.id]) |shown| { // A terminal's lines are its logical lines, as a +Search lists them. const n = if (shown.file) |*f| panes.File.nlines(p.gpa, f) else if (shown.isTerminal()) - if (edit.paneCursorLines(p, &shown.body)) |ls| ls.len else |_| std.math.maxInt(usize) + if (edit.paneCursorLines(p.editor(), &shown.body)) |ls| ls.len else |_| std.math.maxInt(usize) else std.math.maxInt(usize); if (pl.at.line > n) return missedLine(p, id, trimmed, pl.at.line); @@ -2515,7 +2515,7 @@ test "LookNext in a command pane walks its own file:line places, whoever walked exec.runBuiltin(p, .LookNext, p.view().active, "", null); try std.testing.expectEqual(dst, p.view().active); const first = cmd.look_at orelse return error.NoSpot; - const lines = try edit.paneCursorLines(p, &cmd.body); + const lines = try edit.paneCursorLines(p.editor(), &cmd.body); try std.testing.expect(std.mem.startsWith(u8, lines[@intCast(first.row)][@intCast(first.col0)..], "x.c:3:1")); exec.runBuiltin(p, .LookNext, p.view().active, "", null); try std.testing.expectEqual(dst, p.view().active); diff --git a/src/lsp/Ask.zig b/src/lsp/Ask.zig index 879c1f5d..da03c021 100644 --- a/src/lsp/Ask.zig +++ b/src/lsp/Ask.zig @@ -224,7 +224,7 @@ fn applyLspEdits(p: *Pardes, pane: *Pane, revision: u32, edits: []const LspEdit) } @memcpy(replacement[write_at..], f.content[read_at..]); - edit.pushUndo(p, &pane.body) catch { + edit.pushUndo(p.editor(), &pane.body) catch { p.gpa.free(replacement); return false; }; diff --git a/src/mouse.zig b/src/mouse.zig index 9ca45ad3..590f6806 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -91,7 +91,7 @@ fn headerSweepRun(p: *Pardes, sweep: HeaderSweep) void { const v = p.view(); const column = sweep.column(p) catch return; // error.Gone: its column closed under the sweep const t = if (column) |c| &v.col_tags[c] else &p.global_tag; - const text = edit.flatSurface(p, t) catch |err| return p.reportError(v.active, "edit", err); + const text = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(v.active, "edit", err); const swept = sweep.span(text.len); const selected = if (swept.lo < swept.hi) text[swept.lo..swept.hi] else click: { const line = std.mem.count(u8, text[0..swept.lo], "\n"); @@ -364,7 +364,7 @@ fn headerPoint(p: *Pardes, column: ?usize, mcol: u16, mrow: u16, clamp: bool) ?s const t = if (column) |c| &v.col_tags[c] else &p.global_tag; const x = if (column) |c| v.col_x[c] + TAG_TEXT_INSET else TAG_TEXT_INSET; const focused = v.header != null and p.headerColumn() == column; - const text = edit.flatSurface(p, t) catch return null; + const text = edit.flatSurface(p.editor(), t) catch return null; const base = if (column != null) p.topBarHeight() else 0; const rows = if (column != null) layout.columnBarHeight(p) else p.topBarHeight(); const row: u16 = if (clamp) @min(mrow -| base, rows -| 1) else mrow -| base; @@ -444,7 +444,7 @@ fn chordCutPaste(p: *Pardes, cut: bool) edit.Error!void { // Everything done while B1 stays down is one undo step, as acme // marks the file once per B1 hold (text.c:881 textselect, `state` // and its one filemark): B1-B2 then B1-B3 is a copy. - try edit.pushUndo(p, &pane.body); + try edit.pushUndo(p.editor(), &pane.body); p.view().chord_hold = true; const sl = pane.sel[sel_slot]; pane.sel[sel_slot].state = .none; @@ -455,8 +455,8 @@ fn chordCutPaste(p: *Pardes, cut: bool) edit.Error!void { const w1 = pane.wrapAt(@max(0, sl.r1 - @as(i32, pane.tag_rows))); const row0 = w0.line; const row1 = w1.line; - const col0 = edit.paneByteAtDisplay(p, &pane.body, w0.line, w0.at, sl.c0 - pfx - w0.pad); - const col1 = edit.paneByteAtDisplay(p, &pane.body, w1.line, w1.at, sl.c1 - pfx - w1.pad); + const col0 = edit.paneByteAtDisplay(p.editor(), &pane.body, w0.line, w0.at, sl.c0 - pfx - w0.pad); + const col1 = edit.paneByteAtDisplay(p.editor(), &pane.body, w1.line, w1.at, sl.c1 - pfx - w1.pad); pane.body.cur_row = row1; pane.body.cur_col = col1; pane.body.cur_pinned = true; @@ -475,7 +475,7 @@ fn chordCutPaste(p: *Pardes, cut: bool) edit.Error!void { const y = p.registers.text(p.gpa, pardes.Registers.default) orelse return; if (y.len == 0) return; const at = modal.Cursor{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)) }; - try edit.pushUndo(p, &pane.body); + try edit.pushUndo(p.editor(), &pane.body); const new = try modal.insertAt(p.gpa, f.content, at, y); panes.File.setContent(p, f, new); pane.body.vsel = .{ .active = modal.nextGrapheme(y, 0) < y.len, .row = @intCast(at.row), .col = @intCast(at.col), .explicit = false }; @@ -1042,7 +1042,7 @@ fn gestureRange(p: *Pardes, id: usize, text: []const u8, on_tag: bool, operand: const top = lead[0] - @as(i32, pane.tag_rows); if (top < 0) break :lead null; const w = pane.wrapAt(top); - const col = edit.paneByteAtDisplay(p, &pane.body, w.line, w.at, lead[1] - panes.File.gutterWidth(pane) - w.pad); + const col = edit.paneByteAtDisplay(p.editor(), &pane.body, w.line, w.at, lead[1] - panes.File.gutterWidth(pane) - w.pad); break :lead .{ .row = @intCast(@max(0, w.line)), .col = @intCast(@max(0, col)), @@ -1124,7 +1124,7 @@ fn doubleClick(p: *Pardes, id: usize, t: *panes.Text, on_tag: bool, row: i32, co const c = prev orelse return; if (c.id != id or c.on_tag != on_tag or c.row != row or c.col != col or now - c.ms > 500) return; v.last_click = null; - const text = edit.flatSurface(p, t) catch |err| return p.reportError(v.active, "edit", err); + const text = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(v.active, "edit", err); const q = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) }); const r = edit.doubleClickRange(text, q); if (r[1] <= r[0]) return; @@ -1160,7 +1160,7 @@ fn sweepPoint(p: *Pardes, pane: *panes.Pane, r: i32, c: i32) ?modal.Cursor { if (visible < 0) return null; const w = pane.wrapAt(visible); if (w.line < 0) return null; - const col = edit.paneByteAtDisplay(p, &pane.body, w.line, w.at, c - w.pad - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0)); + const col = edit.paneByteAtDisplay(p.editor(), &pane.body, w.line, w.at, c - w.pad - (if (pane.file != null) @as(i32, panes.File.gutterWidth(pane)) else 0)); return .{ .row = @intCast(w.line), .col = @intCast(@max(0, col)) }; } @@ -1220,7 +1220,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { const w = pane.wrapAt(body_vis); pane.body.cur_row = w.line; pane.body.cur_col = edit.paneByteAtDisplay( - p, + p.editor(), &pane.body, w.line, w.at, diff --git a/src/normal.zig b/src/normal.zig index d35dd60d..a344269c 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -55,7 +55,7 @@ pub fn selRegexArmed(pane: *Pane) ?struct { pat: []const u8, mode: modal.Normal. /// had when s/S/K/Alt-K was pressed; the prompt's snapshot of them lives on /// `pane`. pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, mode: modal.Normal.RegexMode) void { - const text = edit.flatSurface(p, t) catch |err| return p.reportError(p.view().active, "edit", err); + const text = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(p.view().active, "edit", err); const snap = pane.sel_snap[0..pane.nsel_snap]; var out: [Text.max_selections]modal.Selection = undefined; var m: usize = 0; @@ -317,7 +317,7 @@ pub fn nodeSelect(p: *Pardes, pane: *Pane, t: *Text, walk: modal.Normal.NodeWalk /// with two letters each; the next two keys choose one (`jumpKey`). fn startJump(p: *Pardes, pane: *Pane, t: *Text) edit.Error!void { if (t.what != .body) return; - const text = try edit.flatSurface(p, t); + const text = try edit.flatSurface(p.editor(), t); const cursor = modal.selectionCursor(text, t.primaryRange(text, 0)); const top: usize = @intCast(@max(0, pane.scroll())); const start = @min(modal.lineStartOffset(text, top), text.len); @@ -343,7 +343,7 @@ pub fn jumpKey(p: *Pardes, pane: *Pane, t: *Text, key: Key) void { defer pane.jump.clearRetainingCapacity(); if (chosen >= pane.jump.items.len) return; const r = pane.jump.items[chosen]; - const text = edit.flatSurface(p, t) catch |err| return p.reportError(p.view().active, "edit", err); + const text = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(p.view().active, "edit", err); if (!t.select) return t.setRange(text, 0, .{ .anchor = @min(r.anchor, r.head), .head = @max(r.anchor, r.head) }, true); // select mode stretches the primary to the word (helix Movement::Extend) const pr = t.primaryRange(text, 0); @@ -467,7 +467,7 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { after = KeyState.of(t); after_expl = t.vsel.explicit; } - const text = edit.flatSurface(p, t) catch { + const text = edit.flatSurface(p.editor(), t) catch { p.multi_stop = true; break; }; @@ -490,7 +490,7 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { t.nsel = 0; return; } - const text = edit.flatSurface(p, t) catch |err| return p.reportError(p.view().active, "edit", err); + const text = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(p.view().active, "edit", err); var rs: [Text.max_selections]modal.Selection = undefined; var st: [Text.max_selections]i32 = undefined; for (res[0..n], 0..) |r, k| { @@ -539,7 +539,7 @@ pub fn handleNormal(p: *Pardes, t: *Text, key: Key) void { } fn startSelRegex(p: *Pardes, pane: *Pane, t: *Text, mode: modal.Normal.RegexMode) edit.Error!void { - const text = try edit.flatSurface(p, t); + const text = try edit.flatSurface(p.editor(), t); const got = t.ranges(text, 0, &pane.sel_snap); pane.nsel_snap = @intCast(got.n); pane.sel_snap_pri = @intCast(got.pri); @@ -957,8 +957,8 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! pane.sel[sel_slot].state = .none; }; if (raw_selection and a.role == .yank) return edit.normalYank(p, t); - edit.pinPaneCursor(p, t); - const text = try edit.flatSurface(p, t); + edit.pinPaneCursor(p.editor(), t); + const text = try edit.flatSurface(p.editor(), t); const range = t.primaryRange(text, 0); const cur = modal.selectionCursor(text, range); @@ -991,8 +991,8 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! if (nw == slice.len) return; return pointMove(t, text, range, ls + nw); }, - .goto_line_down => return verticalMove(t, text, range, true, a.count, edit.paneWrapWidth(p, t)), - .goto_line_up => return verticalMove(t, text, range, false, a.count, edit.paneWrapWidth(p, t)), + .goto_line_down => return verticalMove(t, text, range, true, a.count, edit.paneWrapWidth(p.editor(), t)), + .goto_line_up => return verticalMove(t, text, range, false, a.count, edit.paneWrapWidth(p.editor(), t)), .goto_column => { const line = modal.lineAtOffset(text, cur); const ls = modal.lineStartOffset(text, line); @@ -1041,7 +1041,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! .replace_prefix => return edit.normalReplaceChar(p, t, a.char), // `mm` .match_prefix => { - const lines = try edit.paneCursorLines(p, t); + const lines = try edit.paneCursorLines(p.editor(), t); const mc = modal.matchBracket(lines, modal.positionAt(text, cur)) orelse return; return pointMove(t, text, range, modal.offsetAt(text, mc)); }, @@ -1155,8 +1155,8 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! .indent => return edit.normalIndent(p, t, a.count, true), .unindent => return edit.normalIndent(p, t, a.count, false), .comment_toggle => return edit.normalToggleComment(p, t), - .undo => return edit.undoStep(p, t, true), - .redo => return edit.undoStep(p, t, false), + .undo => return edit.undoStep(p.editor(), t, true), + .redo => return edit.undoStep(p.editor(), t, false), // Language shortcuts run the same builtins as tags and leader commands. .goto_definition => return exec.runBuiltin(p, .Def, v.active, "", null), .goto_references => return exec.runBuiltin(p, .Refs, v.active, "", null), diff --git a/src/tagline.zig b/src/tagline.zig index 1bb4dc85..84cb3173 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -90,7 +90,7 @@ pub fn revealHeader(p: *Pardes) void { v.header_top = 0; return; }; - const text = edit.flatSurface(p, t) catch |err| return p.reportError(v.active, "tag", err); + const text = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(v.active, "tag", err); const cur: usize = @intCast(@max(0, t.cur_row)); const rows: usize = if (p.headerColumn() != null) layout.columnBarHeight(p) else p.topBarHeight(); if (cur < v.header_top) v.header_top = cur; @@ -424,7 +424,7 @@ pub fn enterHeader(p: *Pardes, column: ?usize) void { p.view().header = if (column) |c| .{ .column = c } else .workspace; if (column) |c| p.setActiveColumn(c); const t = focusedHeader(p) orelse return exitHeader(p); - takeKeyboard(t, edit.flatSurface(p, t) catch |err| return p.reportError(p.view().active, "tag", err)); + takeKeyboard(t, edit.flatSurface(p.editor(), t) catch |err| return p.reportError(p.view().active, "tag", err)); } /// The span a header's selection covers on line `row` of its text, in @@ -452,7 +452,7 @@ pub fn workspaceBlank(p: *Pardes, col: u16, row: u16, tag_hit: ?pardes.TagHit) b const v = p.view(); if (row >= p.topBarHeight() or col >= v.screen_w) return false; if (col < TAG_TEXT_INSET) return true; - const text = edit.flatSurface(p, &p.global_tag) catch return false; + const text = edit.flatSurface(p.editor(), &p.global_tag) catch return false; const scroll: usize = if (v.header != null and p.headerColumn() == null) v.header_scroll else 0; const at = @as(usize, Layer.columnAt(p, .workspace, 0, tag_hit, false, 0) orelse (col - TAG_TEXT_INSET)) + scroll; return at >= panes.File.displayWidth(modal.lineSlice(text, 0)) + 2; diff --git a/test/hxdiff.zig b/test/hxdiff.zig index 010cc674..ae73863e 100644 --- a/test/hxdiff.zig +++ b/test/hxdiff.zig @@ -433,7 +433,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.body); + const lines = try pardes.edit.paneCursorLines(core.editor(), &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); diff --git a/test/panes.zig b/test/panes.zig index 04769ccf..fb973ea2 100644 --- a/test/panes.zig +++ b/test/panes.zig @@ -1153,7 +1153,7 @@ test "terminal edits and undo survive partial history clearing and whole-screen try std.testing.expectEqualStrings("edit one\nedit two", snapshot.ovl.?.text); } try std.testing.expectEqual(@as(usize, 2), pardes.Term.emulatorOf(pane.terminal.?).vt.screens.active.pages.countTrackedPins()); - try pardes.edit.undoStep(p, &pane.body, true); + try pardes.edit.undoStep(p.editor(), &pane.body, true); try std.testing.expectEqualStrings("edit one\nedit two", pane.ovl.?.text); try std.testing.expectEqual(expected, pane.ovl.?.row); } diff --git a/test/perf.zig b/test/perf.zig index 0f5466ad..85cc2ca3 100644 --- a/test/perf.zig +++ b/test/perf.zig @@ -695,7 +695,7 @@ fn measureTerm(op: TermOp, fx: TermFixture, reps: usize) !Cell { pump(core); } _ = try frame(core); - const motion_rows = if (op == .key_down) (try pardes.edit.paneCursorLines(core, &pane.body)).len else 0; + const motion_rows = if (op == .key_down) (try pardes.edit.paneCursorLines(core.editor(), &pane.body)).len else 0; if (op == .key_down and motion_rows < 3) return error.EmptyTerminalFixture; var cols = screen_cols; -- cgit v1.3 From 3dd2072fc525cdadf4f55a69f745c73c0b8c2b21 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 05:53:16 -0300 Subject: edit: the edits of a text take the editing context (docs/next-editor.md, R2, second slice): enterInsert, exitInsert, handleInsert, insertKey, insertEdit, insertTab, pasteRegister, pasteText, normalDelete, normalYank, normalChange, deleteSelection, setEditCells, normalReplaceChar, chordReplace, replaceWithText, normalCase, normalJoin, normalRotateContents, normalAlign, normalIndent, normalToggleComment, normalAdjustNumber, addNewline, textobjectSelect and the three surrounds take `e: Editor`; insertEdit's splice end is `stop` and a comment extension `x` where they were `e`; 71 calls in 8 files hand `p.editor()`; core-test 810 of 949, shell-test 989 of 992, hxdiff 658 / parity 738 / hxgolf 124 with 0 mismatches, replicas pass --- src/Effect.zig | 6 +- src/Query.zig | 10 +- src/edit.zig | 454 ++++++++++++++++++++++++++++---------------------------- src/keys.zig | 14 +- src/lsp/Ask.zig | 2 +- src/mouse.zig | 12 +- src/normal.zig | 58 ++++---- src/tagline.zig | 2 +- 8 files changed, 279 insertions(+), 279 deletions(-) (limited to 'src/normal.zig') diff --git a/src/Effect.zig b/src/Effect.zig index 08694e93..344034e2 100644 --- a/src/Effect.zig +++ b/src/Effect.zig @@ -364,7 +364,7 @@ test "Save on a scratch asks for a path in its inherited dir and makes it a file try std.testing.expectEqualStrings(" Save /tmp/pardes-save-dir/", np.promptText().?); // typing the filename and submitting converts it into an ordinary file - try edit.insertKey(p, &np.input, .{ .cp = 'n', .text = "note.txt" }); + try edit.insertKey(p.editor(), &np.input, .{ .cp = 'n', .text = "note.txt" }); exec.submitSave(p, id); // The write asked for, the pane is the file once it is done. var saved = false; @@ -390,7 +390,7 @@ test "Save on a terminal writes its plaintext scrollback and stays a terminal" { try std.testing.expect(p.executeBuiltinLine(0, "Save")); try std.testing.expect(pane.prompt == .save); - try edit.insertKey(p, &pane.input, .{ .cp = 'l', .text = "log.txt" }); + try edit.insertKey(p.editor(), &pane.input, .{ .cp = 'l', .text = "log.txt" }); exec.submitSave(p, 0); // the pane is untouched: still a terminal, no file behind it @@ -440,7 +440,7 @@ test "Save on an output buffer writes its rows out and leaves the buffer alone" 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); - try edit.insertKey(p, &out.input, .{ .cp = 'h', .text = "help.txt" }); + try edit.insertKey(p.editor(), &out.input, .{ .cp = 'h', .text = "help.txt" }); exec.submitSave(p, id); // the buffer itself is untouched: same origin, same name, still refillable diff --git a/src/Query.zig b/src/Query.zig index 4cede3c5..0263052d 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -336,14 +336,14 @@ pub fn toLineOne(p: *Pardes, id: usize) void { if (layout.findPane(p, id)) |at| p.setActiveColumn(at.col); rp.focus = .body; const t = &rp.body; - if (t.mode == .insert) edit.exitInsert(p, t); + if (t.mode == .insert) edit.exitInsert(p.editor(), t); t.cur_row = 0; t.cur_col = @intCast(lineOne(rp.file.?.content).len); t.vsel.active = false; t.nsel = 0; t.cur_pinned = true; rp.query.?.seen_row = 0; - edit.enterInsert(p, t, .line_end, 1) catch |err| return p.reportError(id, "query", err); + edit.enterInsert(p.editor(), t, .line_end, 1) catch |err| return p.reportError(id, "query", err); showCurrent(rp); } @@ -1318,7 +1318,7 @@ pub fn fillList(p: *Pardes, owner_id: usize, source: Source, rows: []const u8) v if (layout.findPane(p, qid)) |at| p.setActiveColumn(at.col); rp.focus = .body; const t = &rp.body; - if (t.mode == .insert) edit.exitInsert(p, t); + if (t.mode == .insert) edit.exitInsert(p.editor(), t); t.vsel.active = false; t.nsel = 0; caretTo(rp, q.current orelse 0); @@ -1770,7 +1770,7 @@ pub fn land(p: *Pardes, id: usize, row: ?usize) void { const q = rp.query orelse return; if (row) |r| if (r < q.items.items.len and q.items.items[r].kind == .hit) setCurrent(p, id, r, true); const t = &rp.body; - if (t.mode == .insert) edit.exitInsert(p, t); + if (t.mode == .insert) edit.exitInsert(p.editor(), t); freeze(p, id); const owner_id = p.paneBySerial(q.owner); if (q.source == .text) { @@ -1872,7 +1872,7 @@ pub fn cancel(p: *Pardes, id: usize) void { const rp = p.panes[id] orelse return; const q = rp.query orelse return; const t = &rp.body; - if (t.mode == .insert) edit.exitInsert(p, t); + if (t.mode == .insert) edit.exitInsert(p.editor(), t); const owner_id = p.paneBySerial(q.owner); for (p.panes) |slot| if (slot) |tp| { if (tp.places.from != rp.serial and tp.serial != q.owner) continue; diff --git a/src/edit.zig b/src/edit.zig index e8b5aab2..9ae00079 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -77,18 +77,18 @@ fn selText(e: Editor, t: *Text) Error![]const u8 { /// Where a paste goes: after the selection, before it, or over it. pub const Paste = enum { after, before, replace }; -pub fn pasteRegister(p: *Pardes, t: *Text, how: Paste, count: usize) Error!void { - const name: u21 = if (p.view().register != 0) p.view().register else Registers.default; +pub fn pasteRegister(e: Editor, t: *Text, how: Paste, count: usize) Error!void { + const name: u21 = if (e.register.* != 0) e.register.* else Registers.default; if (name == '+' or name == '*') { - if (!normal.multiOnce(p.editor())) return; + if (!normal.multiOnce(e)) return; const pane = t.pane() orelse return; - return clipRequest(p, panes.paneIdOf(p, pane) orelse return, how); + return clipRequest(e.p, panes.paneIdOf(e.p, pane) orelse return, how); } - const y = registerValue(p.editor(), t, name) orelse return; + const y = registerValue(e, t, name) orelse return; switch (how) { - .after => try pasteText(p, t, y, false, count), - .before => try pasteText(p, t, y, true, count), - .replace => try replaceWithText(p, t, y), + .after => try pasteText(e, t, y, false, count), + .before => try pasteText(e, t, y, true, count), + .replace => try replaceWithText(e, t, y), } } @@ -144,16 +144,16 @@ pub fn applyPaste(p: *Pardes, whole: []const u8) Error!void { line[n] = byte; n += 1; }; - if (n > 0) try insertKey(p, &pane.input, .{ .cp = line[0], .text = line[0..n] }); + if (n > 0) try insertKey(p.editor(), &pane.input, .{ .cp = line[0], .text = line[0..n] }); if (normal.selRegexArmed(pane)) |a| if (panes.promptTarget(p, pane)) |t| normal.applySelRegex(p, pane, t, a.pat, a.mode); return; } 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 => try pasteText(p, &pane.body, bytes, false, 1), - .before => try pasteText(p, &pane.body, bytes, true, 1), - .replace => try replaceWithText(p, &pane.body, bytes), + .after => try pasteText(p.editor(), &pane.body, bytes, false, 1), + .before => try pasteText(p.editor(), &pane.body, bytes, true, 1), + .replace => try replaceWithText(p.editor(), &pane.body, bytes), } } @@ -168,7 +168,7 @@ fn pasteInto(p: *Pardes, t: *Text, bytes: []const u8) Error!void { const kept_n = t.nsel; @memcpy(kept_sels[0..kept_n], t.sels[0..kept_n]); t.refused = false; - if (t.mode == .insert) try insertKey(p, t, typed) else try pasteText(p, t, bytes, false, 1); + if (t.mode == .insert) try insertKey(p.editor(), t, typed) else try pasteText(p.editor(), t, bytes, false, 1); if (t.refused) { t.cur_row, t.cur_col, t.vsel = kept; t.restoreSels(kept_sels[0..kept_n]); @@ -191,7 +191,7 @@ pub fn clipYank(p: *Pardes, pane: *Pane, main_only: bool) void { } else { const others = pane.body.nsel; pane.body.nsel = 0; - normalYank(p, &pane.body) catch |err| p.reportError(p.view().active, "edit", err); + normalYank(p.editor(), &pane.body) catch |err| p.reportError(p.view().active, "edit", err); pane.body.nsel = others; } } @@ -354,7 +354,7 @@ pub fn currentSelText(p: *Pardes, pane: *Pane) ?[]const u8 { return vselText(p.editor(), &pane.body) catch null; } -pub fn exitInsert(p: *Pardes, t: *Text) void { +pub fn exitInsert(e: Editor, t: *Text) void { t.mode = .normal; t.reg_wait = false; t.normal.clear(); @@ -363,7 +363,7 @@ pub fn exitInsert(p: *Pardes, t: *Text) void { // helix enter_normal_mode: every range, from its start to the char // before its end when it points forward, else to its end const expl = t.vsel.active and t.vsel.explicit; - const text = flatSurface(p.editor(), t) catch |err| return p.reportError(p.view().active, "edit", err); + const text = flatSurface(e, t) catch |err| return e.reportError(err); var rs: [Text.max_selections]modal.Selection = undefined; const got = t.ranges(text, 0, &rs); for (rs[0..got.n]) |*r| { @@ -783,17 +783,17 @@ pub fn clampFileCursor(t: *Text) bool { return old_row != t.cur_row or old_col != t.cur_col; } -pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) Error!void { +pub fn enterInsert(e: Editor, t: *Text, where: InsertAt, cnt: usize) Error!void { if (t.what == .body) if (t.pane()) |pane| if (pane.addon != null) return; - pinPaneCursor(p.editor(), t); + pinPaneCursor(e, t); _ = clampFileCursor(t); // snapshot once per insert session (WITH the pre-insert selection) so // `u` undoes the whole session and restores what was selected - try pushUndo(p.editor(), t); + try pushUndo(e, t); t.select = false; t.restore_cursor = false; t.sticky_col = -1; - const text = flatSurface(p.editor(), t) catch { + const text = flatSurface(e, t) catch { t.mode = .insert; t.vsel.active = false; t.normal.clear(); @@ -825,8 +825,8 @@ pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) Error!void const terminal = t.what == .body and if (t.pane()) |pane| pane.isTerminal() else false; var now = text; if (hi < text.len and gap >= text.len and !terminal) { - const grown = try std.mem.concat(p.gpa, u8, &.{ text, "\n" }); - try setEditText(p.editor(), t, grown); + const grown = try std.mem.concat(e.gpa, u8, &.{ text, "\n" }); + try setEditText(e, t, grown); now = grown; // what setEditText keeps; `text` may be gone } const gc = modal.positionAt(now, gap); @@ -850,14 +850,14 @@ pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) Error!void 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 t.cur_row; - const eb = (try editText(p.editor(), t, abs, abs, -1)) orelse return; + const eb = (try editText(e, t, abs, abs, -1)) orelse return; const row: usize = @intCast(@max(0, abs - eb.row0)); // helix open_below/open_above: the tree's indent for a line // after the one above the new one, else acme's copy of this one const above = if (below) row else row -| 1; const after = if (!below and row == 0) 0 else panes.File.textLineStart(t, eb.text, above) + panes.File.textLine(t, eb.text, above).len; - const ind = (try treeIndent(p.editor(), t, eb.text, above, after)) orelse modal.indentText(modal.lineSlice(eb.text, row)); - const arena = p.scratch.allocator(); + const ind = (try treeIndent(e, t, eb.text, above, after)) orelse modal.indentText(modal.lineSlice(eb.text, row)); + const arena = e.scratch; const block_len = std.math.mul(usize, cnt, ind.len + 1) catch return error.OutOfMemory; const block = try arena.alloc(u8, block_len); var block_at: usize = 0; @@ -877,13 +877,13 @@ pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) Error!void .{ .row = row, .col = modal.lineSlice(eb.text, row).len } else .{ .row = row, .col = 0 }; - const new = try modal.insertAt(p.gpa, eb.text, at, block); - try setEditText(p.editor(), t, new); + const new = try modal.insertAt(e.gpa, eb.text, at, block); + try setEditText(e, 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_count == 1) opened: { - const t2 = flatSurface(p.editor(), t) catch break :opened; + if (cnt > 1 and e.multi_count.* == 1) opened: { + const t2 = flatSurface(e, t) catch break :opened; var rs: [Text.max_selections]modal.Selection = undefined; const m = @min(cnt, Text.max_selections); for (0..m) |k| { @@ -899,23 +899,23 @@ pub fn enterInsert(p: *Pardes, t: *Text, where: InsertAt, cnt: usize) Error!void t.show(); } -pub fn handleInsert(p: *Pardes, t: *Text, key: Key) void { - if (t.nsel == 0) return insertKey(p, t, key) catch |err| p.reportError(p.view().active, "edit", err); - normal.replaySels(p, t, .{ .insert = key }); +pub fn handleInsert(e: Editor, t: *Text, key: Key) void { + if (t.nsel == 0) return insertKey(e, t, key) catch |err| e.reportError(err); + normal.replaySels(e.p, t, .{ .insert = key }); } -pub fn insertKey(p: *Pardes, t: *Text, key: Key) Error!void { +pub fn insertKey(e: Editor, t: *Text, key: Key) Error!void { // helix aliases: normalize to the base key and re-dispatch - if (hit(key, config.insert_backspace_alias)) return insertKey(p, t, .{ .cp = Key.backspace }); - if (hit(key, config.insert_enter_alias)) return insertKey(p, t, .{ .cp = Key.enter }); - if (hit(key, config.insert_delete_alias)) return insertKey(p, t, .{ .cp = Key.delete }); + if (hit(key, config.insert_backspace_alias)) return insertKey(e, t, .{ .cp = Key.backspace }); + if (hit(key, config.insert_enter_alias)) return insertKey(e, t, .{ .cp = Key.enter }); + if (hit(key, config.insert_delete_alias)) return insertKey(e, t, .{ .cp = Key.delete }); // Ctrl-r : type this range's value of the register (helix // insert_register) if (t.reg_wait) { t.reg_wait = false; if (key.ctrl or key.alt or key.cp >= 0xF0000) return; - const y = registerValue(p.editor(), t, key.cp) orelse return; - if (y.len > 0) try insertKey(p, t, .{ .cp = key.cp, .text = y }); + const y = registerValue(e, t, key.cp) orelse return; + if (y.len > 0) try insertKey(e, t, .{ .cp = key.cp, .text = y }); return; } if (hit(key, config.insert_register)) { @@ -923,20 +923,20 @@ pub fn insertKey(p: *Pardes, t: *Text, key: Key) Error!void { return; } // helix commit_undo_checkpoint: `u` after the session goes back to here - if (hit(key, config.insert_checkpoint)) return pushUndo(p.editor(), t); + if (hit(key, config.insert_checkpoint)) return pushUndo(e, t); // helix maps every range through each insert-mode edit (Range::map): // the edits below work on the bare cursor, and the range the cursor // heads is carried through what they did to the text afterwards - if (!t.vsel.active) return insertEdit(p, t, key); - const old = flatSurface(p.editor(), t) catch return insertEdit(p, t, key); + if (!t.vsel.active) return insertEdit(e, t, key); + const old = flatSurface(e, t) catch return insertEdit(e, t, key); const r = t.primaryRange(old, 0); const c = modal.selectionCursor(old, r); const old_len = old.len; const explicit = t.vsel.explicit; t.vsel.active = false; - try insertEdit(p, t, key); + try insertEdit(e, t, key); if (t.mode != .insert) return; - const new = try flatSurface(p.editor(), t); + const new = try flatSurface(e, t); const c2 = modal.offsetAt(new, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) }); // every insert-mode edit happens at the cursor: an insertion there, or // a deletion that ends there (backward) or starts there (forward) @@ -989,13 +989,13 @@ fn mapThroughEdit(pos: usize, at: usize, del: usize, ins: usize, before: bool) u return pos + ins; } -fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { +fn insertEdit(e: Editor, t: *Text, key: Key) Error!void { t.vsel.active = false; - if (!t.cur_pinned) pinPaneCursor(p.editor(), t); + if (!t.cur_pinned) pinPaneCursor(e, t); _ = clampFileCursor(t); switch (key.cp) { Key.left, Key.right, Key.up, Key.down => { - const lines = try paneCursorLines(p.editor(), t); + const lines = try paneCursorLines(e, t); const cur0 = t.toModalCursor(); // In a pane's tag, Up on its first line collapses it and Down // on its last expands it, where they would move nothing; acme's @@ -1024,7 +1024,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { Key.page_up, Key.page_down => { // helix binds insert pageup/pagedown to the same view // scroll + cursor snap as normal mode - const flat = try flatSurface(p.editor(), t); + const flat = try flatSurface(e, t); const range = t.primaryRange(flat, 0); if (t.what != .body) return; const step: i32 = @intCast(@max(1, (t.pane() orelse return).rows)); @@ -1039,7 +1039,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { }, Key.end => { // helix insert End: past the last char (goto_line_end_newline) - const text = try flatSurface(p.editor(), t); + const text = try flatSurface(e, t); const cur0 = t.toModalCursor(); t.cur_col = @intCast(panes.File.textLine(t, text, cur0.row).len); t.cur_pinned = true; @@ -1048,7 +1048,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { }, else => {}, } - const eb = (try editText(p.editor(), t, t.cur_row, t.cur_row, t.cur_col)) orelse return; + const eb = (try editText(e, t, t.cur_row, t.cur_row, t.cur_col)) orelse return; const text = eb.text; const c = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - eb.row0)), .col = @intCast(@max(0, t.cur_col)) }; if (key.text.len > 0 and !key.ctrl and !key.alt) { @@ -1061,11 +1061,11 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { modal.insertOffset(text, c); const end = modal.advanceBy(c, key.text); if (bodyFile(t)) |f| { - if (!panes.File.replace(p, f, at, 0, key.text)) return; + if (!panes.File.replace(e.p, f, at, 0, key.text)) return; t.last_edit = .{ .row = @intCast(end.row), .col = @intCast(end.col) }; } else { - const new = try modal.spliceAlloc(p.gpa, text, at, at, key.text); - try setEditTextSpan(p.editor(), t, new, end, .{ .head = at, .tail = text.len - at }); + const new = try modal.spliceAlloc(e.gpa, text, at, at, key.text); + try setEditTextSpan(e, t, new, end, .{ .head = at, .tail = text.len - at }); } t.cur_row = @as(i32, @intCast(end.row)) + eb.row0; t.cur_col = @intCast(end.col); @@ -1076,7 +1076,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { // 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) - ((try editText(p.editor(), t, t.cur_row - 1, t.cur_row, 0)) orelse return) + ((try editText(e, t, t.cur_row - 1, t.cur_row, 0)) orelse return) else eb; const c2 = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - e2.row0)), .col = c.col }; @@ -1085,8 +1085,8 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { 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 = try modal.deleteSpan(p.gpa, e2.text, fc, c2); - try setEditTextEnd(p.editor(), t, new, fc); + const new = try modal.deleteSpan(e.gpa, e2.text, fc, c2); + try setEditTextEnd(e, t, new, fc); t.cur_row = @as(i32, @intCast(fc.row)) + e2.row0; t.cur_col = @intCast(fc.col); t.cur_pinned = true; @@ -1095,7 +1095,7 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { } 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)) - ((try editText(p.editor(), t, t.cur_row, t.cur_row + 1, t.cur_col)) orelse return) + ((try editText(e, t, t.cur_row, t.cur_row + 1, t.cur_col)) orelse return) else eb; const c2 = modal.Cursor{ .row = @intCast(@max(0, t.cur_row - e2.row0)), .col = c.col }; @@ -1103,14 +1103,14 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { 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 = try modal.deleteSpan(p.gpa, e2.text, c2, modal.positionAt(e2.text, to)); - try setEditTextEnd(p.editor(), t, new, c2); + const new = try modal.deleteSpan(e.gpa, e2.text, c2, modal.positionAt(e2.text, to)); + try setEditTextEnd(e, t, new, c2); t.cur_pinned = true; return; } if (hit(key, config.kill_to_line_start)) { - const new = try modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = 0 }, c); - try setEditTextEnd(p.editor(), t, new, .{ .row = c.row, .col = 0 }); + const new = try modal.deleteSpan(e.gpa, text, .{ .row = c.row, .col = 0 }, c); + try setEditTextEnd(e, t, new, .{ .row = c.row, .col = 0 }); t.cur_col = 0; t.cur_pinned = true; t.show(); @@ -1118,8 +1118,8 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { } if (hit(key, config.kill_to_line_end)) { const llen = modal.lineSlice(text, c.row).len; - const new = try modal.deleteSpan(p.gpa, text, c, .{ .row = c.row, .col = llen }); - try setEditTextEnd(p.editor(), t, new, c); + const new = try modal.deleteSpan(e.gpa, text, c, .{ .row = c.row, .col = llen }); + try setEditTextEnd(e, t, new, c); t.cur_pinned = true; return; } @@ -1131,8 +1131,8 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { // itself moves down, blanks and all; else the blanks before the // cursor go and the new line takes the indent if (std.mem.indexOfNone(u8, before, " \t") == null) { - const new = try modal.insertAt(p.gpa, text, .{ .row = c.row, .col = 0 }, "\n"); - try setEditTextEnd(p.editor(), t, new, .{ .row = c.row + 1, .col = 0 }); + const new = try modal.insertAt(e.gpa, text, .{ .row = c.row, .col = 0 }, "\n"); + try setEditTextEnd(e, t, new, .{ .row = c.row + 1, .col = 0 }); t.cur_row += 1; t.cur_pinned = true; t.show(); @@ -1144,9 +1144,9 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { // delimiter. Between a pair (helix insert_newline's // on_auto_pair) the closer goes to a line of its own at that // indent, the cursor to one a level in. - const arena = p.scratch.allocator(); + const arena = e.scratch; const lead = modal.indentText(line); - const tree = try treeIndent(p.editor(), t, text, c.row, panes.File.textLineStart(t, text, c.row) + before.len); + const tree = try treeIndent(e, t, text, c.row, panes.File.textLineStart(t, text, c.row) + before.len); const pair = bodyFile(t) != null and c.col < line.len and opensPair(before[before.len - 1], line[c.col]); const more = modal.newlineIndentWidth(line, c.col) > lead.len; const base = tree orelse if (pair or !more) lead else try std.mem.concat(arena, u8, &.{ lead, indents.unit(null, lead) }); @@ -1155,10 +1155,10 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { // a tag keeps its blanks: they part its words, and the last // may be its read-only prefix's const kept = if (t.what == .body) std.mem.trimEnd(u8, before, " \t").len else c.col; - const cut = try modal.deleteSpan(p.gpa, text, .{ .row = c.row, .col = kept }, c); - defer p.gpa.free(cut); - const new = try modal.insertAt(p.gpa, cut, .{ .row = c.row, .col = kept }, block); - try setEditTextEnd(p.editor(), t, new, if (pair) .{ .row = c.row + 2, .col = base.len } else .{ .row = c.row + 1, .col = mid.len }); + const cut = try modal.deleteSpan(e.gpa, text, .{ .row = c.row, .col = kept }, c); + defer e.gpa.free(cut); + const new = try modal.insertAt(e.gpa, cut, .{ .row = c.row, .col = kept }, block); + try setEditTextEnd(e, t, new, if (pair) .{ .row = c.row + 2, .col = base.len } else .{ .row = c.row + 1, .col = mid.len }); t.cur_row += 1; t.cur_col = @intCast(mid.len); t.cur_pinned = true; @@ -1182,16 +1182,16 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { } // deleteSpan's splice, the line found once. const s = start + @min(prev, line.len); - const e = start + @min(c.col, line.len); + const stop = start + @min(c.col, line.len); if (bodyFile(t)) |f| { // As the whole text put back would be: a no-op edit // when there is nothing before the cursor to take. - if (!(if (e > s) panes.File.replace(p, f, s, e - s, "") else panes.File.replace(p, f, text.len, 0, ""))) return; + if (!(if (stop > s) panes.File.replace(e.p, f, s, stop - s, "") else panes.File.replace(e.p, f, text.len, 0, ""))) return; t.last_edit = .{ .row = @intCast(c.row), .col = @intCast(prev) }; } else { - const new = if (e > s) try modal.spliceAlloc(p.gpa, text, s, e, "") else try p.gpa.dupe(u8, text); - const span: panes.File.Span = if (e > s) .{ .head = s, .tail = text.len - e } else .{ .head = text.len, .tail = 0 }; - try setEditTextSpan(p.editor(), t, new, .{ .row = c.row, .col = prev }, span); + const new = if (stop > s) try modal.spliceAlloc(e.gpa, text, s, stop, "") else try e.gpa.dupe(u8, text); + const span: panes.File.Span = if (stop > s) .{ .head = s, .tail = text.len - stop } else .{ .head = text.len, .tail = 0 }; + try setEditTextSpan(e, t, new, .{ .row = c.row, .col = prev }, span); } t.cur_col = @intCast(prev); t.cur_pinned = true; @@ -1201,12 +1201,12 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { // at col 0: eat the newline above (join up) — a terminal grows // its buffer over the row it is joining with if (t.cur_row <= 0) return; - const e2 = (try editText(p.editor(), t, t.cur_row - 1, t.cur_row, 0)) orelse return; + const e2 = (try editText(e, 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 = try modal.deleteSpan(p.gpa, e2.text, .{ .row = row - 1, .col = prevlen }, .{ .row = row, .col = 0 }); - try setEditTextEnd(p.editor(), t, new, .{ .row = row - 1, .col = prevlen }); + const new = try modal.deleteSpan(e.gpa, e2.text, .{ .row = row - 1, .col = prevlen }, .{ .row = row, .col = 0 }); + try setEditTextEnd(e, t, new, .{ .row = row - 1, .col = prevlen }); t.cur_row -= 1; t.cur_col = @intCast(prevlen); t.cur_pinned = true; @@ -1218,26 +1218,26 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { const line = modal.lineSlice(text, c.row); if (c.col < line.len) { const at = modal.offsetAt(text, c); - const new = try modal.spliceAlloc(p.gpa, text, at, modal.nextGrapheme(text, at), ""); - try setEditTextEnd(p.editor(), t, new, c); + const new = try modal.spliceAlloc(e.gpa, text, at, modal.nextGrapheme(text, at), ""); + try setEditTextEnd(e, t, new, c); } else { - const e2 = (try editText(p.editor(), t, t.cur_row, t.cur_row + 1, t.cur_col)) orelse return; + const e2 = (try editText(e, 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 = try modal.deleteSpan(p.gpa, e2.text, .{ .row = row, .col = c.col }, .{ .row = row + 1, .col = 0 }); - try setEditTextEnd(p.editor(), t, new, .{ .row = row, .col = c.col }); + const new = try modal.deleteSpan(e.gpa, e2.text, .{ .row = row, .col = c.col }, .{ .row = row + 1, .col = 0 }); + try setEditTextEnd(e, t, new, .{ .row = row, .col = c.col }); } t.cur_pinned = true; }, Key.tab => { const ln = modal.lineSlice(text, c.row); - if (p.multi_count == 1 and c.col > 0 and c.col <= ln.len and ln[c.col - 1] == '.') dot: { + if (e.multi_count.* == 1 and c.col > 0 and c.col <= ln.len and ln[c.col - 1] == '.') dot: { if (t.what != .body) break :dot; const f = (t.pane() orelse break :dot).file orelse break :dot; if (f.output != null or !lsp.speaks(f.path)) break :dot; - const seq = p.lsp_ask.seq; - p.lspRequest(p.view().active, .completion, ""); - if (p.lsp_ask.seq != seq) return; + const seq = e.p.lsp_ask.seq; + e.p.lspRequest(e.p.view().active, .completion, ""); + if (e.p.lsp_ask.seq != seq) return; } // helix smart_tab: after text, Tab leaves the syntax node the // cursor is in; only where the file has a grammar, since the @@ -1248,23 +1248,23 @@ fn insertEdit(p: *Pardes, t: *Text, key: Key) Error!void { const pane = t.pane() orelse break :smart; const f = pane.file orelse break :smart; if (!syntax.supportsPath(f.path)) break :smart; - return normal.nodeSelect(p, pane, t, .parent_node_end); + return normal.nodeSelect(e.p, pane, t, .parent_node_end); } - try insertTab(p, t); + try insertTab(e, t); }, else => {}, } } -pub fn insertTab(p: *Pardes, t: *Text) Error!void { - const eb = (try editText(p.editor(), t, t.cur_row, t.cur_row, t.cur_col)) orelse return; +pub fn insertTab(e: Editor, t: *Text) Error!void { + const eb = (try editText(e, t, t.cur_row, t.cur_row, 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 pad = modal.INDENT_W - (c.col % modal.INDENT_W); - const new = try modal.insertAt(p.gpa, eb.text, c, " "[0..pad]); - try setEditTextEnd(p.editor(), t, new, .{ .row = c.row, .col = c.col + pad }); + const new = try modal.insertAt(e.gpa, eb.text, c, " "[0..pad]); + try setEditTextEnd(e, t, new, .{ .row = c.row, .col = c.col + pad }); t.cur_col += @intCast(pad); t.cur_pinned = true; t.show(); @@ -1290,41 +1290,41 @@ fn vselText(e: Editor, t: *Text) Error![]const u8 { return e.scratch.dupe(u8, text[@min(r.anchor, r.head)..@max(r.anchor, r.head)]); } -pub fn normalDelete(p: *Pardes, t: *Text, yank: bool) Error!void { +pub fn normalDelete(e: Editor, t: *Text, yank: bool) Error!void { t.select = false; // helix delete exits select mode t.sticky_col = -1; // A bare cursor is the 1-wide selection on its cell (helix), a '\n' // cell too, where the delete joins the lines. if (!t.vsel.active) t.vsel = .{ .active = true, .row = t.cur_row, .col = t.cur_col, .explicit = false }; const b = vselBounds(t); - if (yank) try setYank(p.editor(), try vselText(p.editor(), t)); // read the range before the move - try pushUndo(p.editor(), t); - const eb = (try editTextEol(p.editor(), t, b)) orelse { + if (yank) try setYank(e, try vselText(e, t)); // read the range before the move + try pushUndo(e, t); + const eb = (try editTextEol(e, t, b)) orelse { t.vsel.active = false; return; }; - const new = try deleteSelection(p, t, eb); - try setEditText(p.editor(), t, new); + const new = try deleteSelection(e, t, eb); + try setEditText(e, t, new); t.cur_row = b.lo_row; t.cur_col = b.lo_col; t.clampCursor(new, eb.row0); } -pub fn normalYank(p: *Pardes, t: *Text) Error!void { +pub fn normalYank(e: Editor, t: *Text) Error!void { t.select = false; if (t.what == .body) if (t.pane()) |pane| if (pane.rawPointerText(pane.sel[sel_slot])) |text| { - try setYank(p.editor(), text); + try setYank(e, text); return; }; - try setYank(p.editor(), try if (t.vsel.active) vselText(p.editor(), t) else selText(p.editor(), t)); + try setYank(e, try if (t.vsel.active) vselText(e, t) else selText(e, t)); } -pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usize) Error!void { +pub fn pasteText(e: Editor, t: *Text, y0: []const u8, before: bool, count: usize) Error!void { if (y0.len == 0) return; - try pushUndo(p.editor(), t); + try pushUndo(e, t); t.select = false; t.sticky_col = -1; - const arena = p.scratch.allocator(); + const arena = e.scratch; var y: []const u8 = y0; if (count > 1) { const total = std.math.mul(usize, count, y0.len) catch return error.OutOfMemory; @@ -1336,7 +1336,7 @@ pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usiz vselBounds(t) else .{ .lo_row = t.cur_row, .lo_col = t.cur_col, .hi_row = t.cur_row, .hi_col = t.cur_col }; - const eb = (try editText(p.editor(), t, b.lo_row, b.hi_row, -1)) orelse return; + const eb = (try editText(e, 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]; @@ -1345,14 +1345,14 @@ pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usiz if (before) { const row: usize = @intCast(@max(0, b.lo_row - row0)); const block = try std.fmt.allocPrint(arena, "{s}\n", .{block_text}); - out = try modal.insertAt(p.gpa, eb.text, .{ .row = row, .col = 0 }, block); + out = try modal.insertAt(e.gpa, eb.text, .{ .row = row, .col = 0 }, block); t.cur_row = @as(i32, @intCast(row + n - 1)) + row0; } else { const row: usize = @intCast(@max(0, b.hi_row - row0)); - out = try modal.pasteLineBelow(p.gpa, eb.text, row, block_text); + out = try modal.pasteLineBelow(e.gpa, eb.text, row, block_text); t.cur_row = @as(i32, @intCast(row + n)) + row0; } - try setEditText(p.editor(), t, out); + try setEditText(e, 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, t.cur_row - row0))).len; @@ -1368,8 +1368,8 @@ pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usiz const gcol = modal.nextGrapheme(high_line, hi_col); break :blk .{ .row = hrow, .col = gcol }; }; - const out = try modal.insertAt(p.gpa, eb.text, at, y); - try setEditText(p.editor(), t, out); + const out = try modal.insertAt(e.gpa, eb.text, at, y); + try setEditText(e, 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) { @@ -1384,25 +1384,25 @@ pub fn pasteText(p: *Pardes, t: *Text, y0: []const u8, before: bool, count: usiz t.show(); } -pub fn normalChange(p: *Pardes, t: *Text) Error!void { +pub fn normalChange(e: Editor, t: *Text) Error!void { t.select = false; t.sticky_col = -1; if (t.vsel.active) { const b = vselBounds(t); - const eb = (try editTextEol(p.editor(), t, b)) orelse return; + const eb = (try editTextEol(e, 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) { - try setYank(p.editor(), try vselText(p.editor(), t)); - try pushUndo(p.editor(), t); - const d = try modal.deleteLines(p.gpa, eb.text, @intCast(@max(0, b.lo_row - eb.row0)), @intCast(@max(0, b.hi_row - eb.row0))); - try setEditText(p.editor(), t, d); + try setYank(e, try vselText(e, t)); + try pushUndo(e, t); + const d = try modal.deleteLines(e.gpa, eb.text, @intCast(@max(0, b.lo_row - eb.row0)), @intCast(@max(0, b.hi_row - eb.row0))); + try setEditText(e, t, d); const n = modal.lineCount(d); const row: usize = @min(@as(usize, @intCast(@max(0, b.lo_row - eb.row0))), if (n == 0) 0 else n - 1); const ind = modal.indentText(modal.lineSlice(d, row)); - const arena = p.scratch.allocator(); + const arena = e.scratch; const block = try std.fmt.allocPrint(arena, "{s}\n", .{ind}); - const new = try modal.insertAt(p.gpa, d, .{ .row = row, .col = 0 }, block); - try setEditText(p.editor(), t, new); + const new = try modal.insertAt(e.gpa, d, .{ .row = row, .col = 0 }, block); + try setEditText(e, t, new); t.cur_row = @as(i32, @intCast(row)) + eb.row0; t.cur_col = @intCast(ind.len); t.vsel.active = false; @@ -1412,10 +1412,10 @@ pub fn normalChange(p: *Pardes, t: *Text) Error!void { t.show(); return; } - try setYank(p.editor(), try vselText(p.editor(), t)); - try pushUndo(p.editor(), t); - const new = try deleteSelection(p, t, eb); - try setEditText(p.editor(), t, new); + try setYank(e, try vselText(e, t)); + try pushUndo(e, t); + const new = try deleteSelection(e, t, eb); + try setEditText(e, t, new); t.cur_row = b.lo_row; t.cur_col = b.lo_col; t.clampCursor(new, eb.row0); @@ -1423,12 +1423,12 @@ pub fn normalChange(p: *Pardes, t: *Text) Error!void { t.normal.clear(); return; } - try pushUndo(p.editor(), t); - const eb = (try editTextEol(p.editor(), t, selRows(t))) orelse return; + try pushUndo(e, t); + const eb = (try editTextEol(e, t, selRows(t))) orelse return; const r = t.primaryRange(eb.text, eb.row0); - try setYank(p.editor(), eb.text[r.anchor..r.head]); - const new = try modal.spliceAlloc(p.gpa, eb.text, r.anchor, r.head, ""); - try setEditText(p.editor(), t, new); + try setYank(e, eb.text[r.anchor..r.head]); + const new = try modal.spliceAlloc(e.gpa, eb.text, r.anchor, r.head, ""); + try setEditText(e, t, new); const llen = modal.lineSlice(new, @intCast(@max(0, t.cur_row - eb.row0))).len; t.cur_col = @min(t.cur_col, @as(i32, @intCast(llen))); t.mode = .insert; @@ -1436,9 +1436,9 @@ pub fn normalChange(p: *Pardes, t: *Text) Error!void { } /// `eb` without the primary range. -fn deleteSelection(p: *Pardes, t: *Text, eb: panes.EditText) Error![]u8 { +fn deleteSelection(e: Editor, t: *Text, eb: panes.EditText) Error![]u8 { const r = t.primaryRange(eb.text, eb.row0); - return modal.spliceAlloc(p.gpa, eb.text, @min(r.anchor, r.head), @max(r.anchor, r.head), ""); + return modal.spliceAlloc(e.gpa, eb.text, @min(r.anchor, r.head), @max(r.anchor, r.head), ""); } /// the rows an op's selection spans, absolute (what editText must cover) @@ -1460,15 +1460,15 @@ fn allSelRows(t: *Text) Bounds { /// Put in `new`, an edit of the buffer whose first line is surface row /// `row0`, and select `cells`, each range's cursor and anchor cells in it. -fn setEditCells(p: *Pardes, t: *Text, new: []u8, row0: i32, cells: []const Text.Cells, pri: usize, expl: bool) Error!void { +fn setEditCells(e: Editor, t: *Text, new: []u8, row0: i32, cells: []const Text.Cells, pri: usize, expl: bool) Error!void { var sels: [Text.max_selections]Text.SelRange = undefined; for (cells, sels[0..cells.len]) |c, *s| { const cc = modal.positionAt(new, c.cur); const ac = modal.positionAt(new, c.anc); s.* = .{ .row = @as(i32, @intCast(cc.row)) + row0, .col = @intCast(cc.col), .arow = @as(i32, @intCast(ac.row)) + row0, .acol = @intCast(ac.col) }; } - try setEditText(p.editor(), t, new); - const text = try flatSurface(p.editor(), t); + try setEditText(e, t, new); + const text = try flatSurface(e, t); var rs: [Text.max_selections]modal.Selection = undefined; for (sels[0..cells.len], rs[0..cells.len]) |s, *r| r.* = Text.cellRange(text, s.arow, s.acol, s.row, s.col); t.setRanges(text, rs[0..cells.len], &.{}, pri, expl); @@ -1476,9 +1476,9 @@ fn setEditCells(p: *Pardes, t: *Text, new: []u8, row0: i32, cells: []const Text. /// `r`: overwrite the selection (or the cursor char) with ch — /// newlines included (helix), so `xrz` joins the selected lines -pub fn normalReplaceChar(p: *Pardes, t: *Text, ch: u21) Error!void { +pub fn normalReplaceChar(e: Editor, t: *Text, ch: u21) Error!void { t.select = false; - const eb = (try editTextEol(p.editor(), t, selRows(t))) orelse return; + const eb = (try editTextEol(e, 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); @@ -1487,11 +1487,11 @@ pub fn normalReplaceChar(p: *Pardes, t: *Text, ch: u21) Error!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; // a surrogate half types nothing - const rep = try p.scratch.allocator().alloc(u8, graphemes * encoded_len); + const rep = try e.scratch.alloc(u8, graphemes * encoded_len); for (0..graphemes) |i| @memcpy(rep[i * encoded_len ..][0..encoded_len], encoded[0..encoded_len]); - try pushUndo(p.editor(), t); - const new = try modal.spliceAlloc(p.gpa, eb.text, lo, hi, rep); - try setEditText(p.editor(), t, new); + try pushUndo(e, t); + const new = try modal.spliceAlloc(e.gpa, eb.text, lo, hi, rep); + try setEditText(e, t, new); const end = lo + rep.len; const mapped: modal.Selection = if (before.head < before.anchor) .{ .anchor = end, .head = lo } @@ -1503,35 +1503,35 @@ pub fn normalReplaceChar(p: *Pardes, t: *Text, ch: u21) Error!void { /// `R`: replace the selection (or the cursor char) with the DEFAULT /// register. `SPC R` is the same verb over the system clipboard. /// The acme chords' replace: the default register as one text. -pub fn chordReplace(p: *Pardes, t: *Text) Error!void { - return replaceWithText(p, t, p.registers.text(p.gpa, Registers.default) orelse return); +pub fn chordReplace(e: Editor, t: *Text) Error!void { + return replaceWithText(e, t, e.registers.text(e.gpa, Registers.default) orelse return); } /// The pasted text becomes the selection, in the direction the replaced one /// had: a forward head lands on its last char (which for a trailing-newline /// `y` is the '\n' cell of the last full line), a backward one on its first. -fn replaceWithText(p: *Pardes, t: *Text, y: []const u8) Error!void { +fn replaceWithText(e: Editor, t: *Text, y: []const u8) Error!void { if (y.len == 0) return; t.select = false; - const eb = (try editTextEol(p.editor(), t, selRows(t))) orelse return; + const eb = (try editTextEol(e, t, selRows(t))) orelse return; const r = t.primaryRange(eb.text, eb.row0); const lo = @min(r.anchor, r.head); - try pushUndo(p.editor(), t); - const new = try modal.spliceAlloc(p.gpa, eb.text, lo, @max(r.anchor, r.head), y); - try setEditText(p.editor(), t, new); + try pushUndo(e, t); + const new = try modal.spliceAlloc(e.gpa, eb.text, lo, @max(r.anchor, r.head), y); + try setEditText(e, t, new); const end = lo + y.len; t.setRange(new, eb.row0, if (r.head < r.anchor) .{ .anchor = end, .head = lo } else .{ .anchor = lo, .head = end }, false); } /// `~` / `` ` `` / ``Alt-` ``: case-map the selection (or the cursor char), /// keeping the selection (helix) -pub fn normalCase(p: *Pardes, t: *Text, op: modal.CaseOp) Error!void { +pub fn normalCase(e: Editor, t: *Text, op: modal.CaseOp) Error!void { t.select = false; - const eb = (try editTextEol(p.editor(), t, selRows(t))) orelse return; + const eb = (try editTextEol(e, t, selRows(t))) orelse return; const r = t.primaryRange(eb.text, eb.row0); - try pushUndo(p.editor(), t); - const new = try modal.changeCase(p.gpa, eb.text, @min(r.anchor, r.head), @max(r.anchor, r.head), op); - try setEditText(p.editor(), t, new); + try pushUndo(e, t); + const new = try modal.changeCase(e.gpa, eb.text, @min(r.anchor, r.head), @max(r.anchor, r.head), op); + try setEditText(e, t, new); } /// Where `pos` lands after `chs`, which are ascending and disjoint. @@ -1554,19 +1554,19 @@ fn mapThroughChanges(chs: []const sam.Op, pos: usize) usize { /// (helix join_selections): the newline and the next line's leading blanks /// become one space, or nothing when that line is blank, and a line two /// ranges share is joined once. `Alt-J` then selects the spaces it put in. -pub fn normalJoin(p: *Pardes, t: *Text, select_space: bool) Error!void { +pub fn normalJoin(e: Editor, t: *Text, select_space: bool) Error!void { const expl = t.vsel.active and t.vsel.explicit; // a join always eats the newline of its last line, so the buffer has // to reach one row PAST every range const b = allSelRows(t); - const eb = (try editText(p.editor(), t, b.lo_row, b.hi_row + 1, -1)) orelse return; + const eb = (try editText(e, t, b.lo_row, b.hi_row + 1, -1)) orelse return; const text = eb.text; var rs: [Text.max_selections]modal.Selection = undefined; const got = t.ranges(text, eb.row0, &rs); // Lines, their count and rows from the file's index when it has one: // counted from the top, a J in a 7 MB file was 8 ms. const nlines = panes.File.textLineCount(t, text); - const arena = p.scratch.allocator(); + const arena = e.scratch; var changes: std.ArrayList(sam.Op) = .empty; var next: usize = 0; // lines below this one are joined already for (rs[0..got.n]) |r| { @@ -1590,8 +1590,8 @@ pub fn normalJoin(p: *Pardes, t: *Text, select_space: bool) Error!void { const chs = changes.items; const chs_len = chs.len; if (chs_len == 0) return; - try pushUndo(p.editor(), t); - const new = try sam.apply(p.gpa, text, chs[0..chs_len]); + try pushUndo(e, t); + const new = try sam.apply(e.gpa, text, chs[0..chs_len]); // every range's cells ride through the edit; Alt-J replaces them with // the spaces, when it put any in var cells: [Text.max_selections]Text.Cells = undefined; @@ -1616,16 +1616,16 @@ pub fn normalJoin(p: *Pardes, t: *Text, select_space: bool) Error!void { n = got.n; pri = got.pri; } - try setEditCells(p, t, new, eb.row0, cells[0..n], pri, expl); + try setEditCells(e, t, new, eb.row0, cells[0..n], pri, expl); } /// `Alt-)` / `Alt-(`: rotate the TEXT of the selections forward / back by /// one range (count ranges), in one edit (helix reorder_selection_contents). /// Each range comes back over the text it now holds, in its own direction, /// and the primary moves with the text it had. -pub fn normalRotateContents(p: *Pardes, t: *Text, forward: bool, cnt: usize) Error!void { +pub fn normalRotateContents(e: Editor, t: *Text, forward: bool, cnt: usize) Error!void { const expl = t.vsel.active and t.vsel.explicit; - const eb = (try editTextEol(p.editor(), t, allSelRows(t))) orelse return; + const eb = (try editTextEol(e, t, allSelRows(t))) orelse return; const text = eb.text; var rs: [Text.max_selections]modal.Selection = undefined; const got = t.ranges(text, eb.row0, &rs); @@ -1641,8 +1641,8 @@ pub fn normalRotateContents(p: *Pardes, t: *Text, forward: bool, cnt: usize) Err .text = text[@min(src.anchor, src.head)..@max(src.anchor, src.head)], }; } - try pushUndo(p.editor(), t); - const new = try sam.apply(p.gpa, text, chs[0..n]); + try pushUndo(e, t); + const new = try sam.apply(e.gpa, text, chs[0..n]); var cells: [Text.max_selections]Text.Cells = undefined; var delta: i64 = 0; for (chs[0..n], rs[0..n], cells[0..n]) |ch, r, *cell| { @@ -1651,16 +1651,16 @@ pub fn normalRotateContents(p: *Pardes, t: *Text, forward: bool, cnt: usize) Err const to = from + ch.text.len; cell.* = Text.rangeCells(new, if (r.anchor > r.head) .{ .anchor = to, .head = from } else .{ .anchor = from, .head = to }); } - try setEditCells(p, t, new, eb.row0, cells[0..n], if (forward) (got.pri + by) % n else (got.pri + n - by) % n, expl); + try setEditCells(e, t, new, eb.row0, cells[0..n], if (forward) (got.pri + by) % n else (got.pri + n - by) % n, expl); } /// `&`: pad the selections into columns, in one edit (helix /// align_selections). The k-th range of every line is a column; spaces go in /// before each range so its head lands on the column's widest head, measured /// in display cells. A range over several lines aligns nothing. -pub fn normalAlign(p: *Pardes, t: *Text) Error!void { +pub fn normalAlign(e: Editor, t: *Text) Error!void { const expl = t.vsel.active and t.vsel.explicit; - const eb = (try editTextEol(p.editor(), t, allSelRows(t))) orelse return; + const eb = (try editTextEol(e, t, allSelRows(t))) orelse return; const text = eb.text; var rs: [Text.max_selections]modal.Selection = undefined; const got = t.ranges(text, eb.row0, &rs); @@ -1688,7 +1688,7 @@ pub fn normalAlign(p: *Pardes, t: *Text) Error!void { t.select = false; // helix exit_select_mode // each column's head position, left to right for (1..n) |i| widths[i] += widths[i - 1]; - const arena = p.scratch.allocator(); + const arena = e.scratch; var chs: [Text.max_selections]sam.Op = undefined; var m: usize = 0; line = std.math.maxInt(usize); @@ -1709,24 +1709,24 @@ pub fn normalAlign(p: *Pardes, t: *Text) Error!void { m += 1; } if (m == 0) return; - try pushUndo(p.editor(), t); - const new = try sam.apply(p.gpa, text, chs[0..m]); + try pushUndo(e, t); + const new = try sam.apply(e.gpa, text, chs[0..m]); var cells: [Text.max_selections]Text.Cells = undefined; for (rs[0..n], cells[0..n]) |r, *cell| { const c = Text.rangeCells(text, r); cell.* = .{ .cur = mapThroughChanges(chs[0..m], c.cur), .anc = mapThroughChanges(chs[0..m], c.anc) }; } - try setEditCells(p, t, new, eb.row0, cells[0..n], got.pri, expl); + try setEditCells(e, t, new, eb.row0, cells[0..n], got.pri, expl); } -pub fn normalIndent(p: *Pardes, t: *Text, cnt: usize, add: bool) Error!void { +pub fn normalIndent(e: Editor, t: *Text, cnt: usize, add: bool) Error!void { t.select = false; const sr = selRows(t); - const eb = (try editText(p.editor(), t, sr.lo_row, sr.hi_row, -1)) orelse return; + const eb = (try editText(e, t, sr.lo_row, sr.hi_row, -1)) orelse return; const text = eb.text; const range = t.primaryRange(text, eb.row0); const span = Text.rangeLineSpan(text, range); - const arena = p.scratch.allocator(); + const arena = e.scratch; // one run of spaces, sliced per line: `>` never inserts more than this const pad = try arena.alloc(u8, modal.INDENT_W * cnt); @memset(pad, ' '); @@ -1763,16 +1763,16 @@ pub fn normalIndent(p: *Pardes, t: *Text, cnt: usize, add: bool) Error!void { } } if (chs_len == 0) return; - try pushUndo(p.editor(), t); + try pushUndo(e, 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 = try sam.apply(p.gpa, text, chs[0..chs_len]); + const new = try sam.apply(e.gpa, text, chs[0..chs_len]); const nc = mapThroughChanges(chs[0..chs_len], cur_off); const na = mapThroughChanges(chs[0..chs_len], anc_off); - try setEditText(p.editor(), t, new); + try setEditText(e, t, new); const cc = modal.positionAt(new, nc); const ac = modal.positionAt(new, na); t.cur_row = @as(i32, @intCast(cc.row)) + eb.row0; @@ -1786,19 +1786,19 @@ pub fn normalIndent(p: *Pardes, t: *Text, cnt: usize, add: bool) Error!void { t.show(); } -pub fn normalToggleComment(p: *Pardes, t: *Text) Error!void { +pub fn normalToggleComment(e: Editor, t: *Text) Error!void { const expl = t.vsel.active and t.vsel.explicit; t.select = false; // helix exit_select_mode // the buffer must cover every cursor's rows, not just the primary's const b = allSelRows(t); - const surface = try flatSurface(p.editor(), t); + const surface = try flatSurface(e, t); const last_row = @as(i32, @intCast(panes.File.textLineCount(t, surface))) - 1; - const eb = (try editText(p.editor(), t, b.lo_row, @min(b.hi_row + 1, last_row), -1)) orelse return; + const eb = (try editText(e, t, b.lo_row, @min(b.hi_row + 1, last_row), -1)) orelse return; const text = eb.text; var rs: [Text.max_selections]modal.Selection = undefined; const got = t.ranges(text, eb.row0, &rs); const nlines = modal.cursorLineCount(text); - const arena = p.scratch.allocator(); + const arena = e.scratch; // the lines the ranges cover, each ONE ONCE and in order (helix's // min_next_line: two cursors on one line comment it once) const lines = try arena.alloc(usize, nlines); @@ -1818,7 +1818,7 @@ pub fn normalToggleComment(p: *Pardes, t: *Text) Error!void { const ext = if (file) |f| std.Io.Dir.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)) { + for (row.exts) |x| if (std.ascii.eqlIgnoreCase(ext, x)) { token = row.token; break :lang; }; @@ -1854,46 +1854,46 @@ pub fn normalToggleComment(p: *Pardes, t: *Text) Error!void { .{ .q0 = @intCast(at), .q1 = @intCast(at), .text = ins }; chs_len += 1; } - try pushUndo(p.editor(), t); + try pushUndo(e, t); // one edit, and the WHOLE selection rides through it (helix maps the // selection with the transaction) var cells: [Text.max_selections]Text.Cells = undefined; - const new = try sam.apply(p.gpa, text, chs[0..chs_len]); + const new = try sam.apply(e.gpa, text, chs[0..chs_len]); for (rs[0..got.n], cells[0..got.n]) |r, *cell| cell.* = Text.rangeCells(new, .{ .anchor = mapThroughChanges(chs[0..chs_len], r.anchor), .head = mapThroughChanges(chs[0..chs_len], r.head), }); - try setEditCells(p, t, new, eb.row0, cells[0..got.n], got.pri, expl); + try setEditCells(e, t, new, eb.row0, cells[0..got.n], got.pri, expl); } -pub fn normalAdjustNumber(p: *Pardes, t: *Text, delta: i64) Error!void { - const eb = (try editTextEol(p.editor(), t, selRows(t))) orelse return; +pub fn normalAdjustNumber(e: Editor, t: *Text, delta: i64) Error!void { + const eb = (try editTextEol(e, t, selRows(t))) orelse return; const r = t.primaryRange(eb.text, eb.row0); const lo = @min(r.anchor, r.head); const hi = @max(r.anchor, r.head); - const rep = (modal.incrementDecimal(p.scratch.allocator(), eb.text[lo..hi], delta) catch null) orelse return; - try pushUndo(p.editor(), t); + const rep = (modal.incrementDecimal(e.scratch, eb.text[lo..hi], delta) catch null) orelse return; + try pushUndo(e, t); t.select = false; - const new = try modal.spliceAlloc(p.gpa, eb.text, lo, hi, rep); - try setEditText(p.editor(), t, new); + const new = try modal.spliceAlloc(e.gpa, eb.text, lo, hi, rep); + try setEditText(e, t, new); t.setRange(new, eb.row0, .{ .anchor = lo, .head = lo + rep.len }, false); } /// `]Space` / `[Space`: add blank lines below/above, the cursor staying /// on its text line (the selection rides along) -pub fn addNewline(p: *Pardes, t: *Text, below: bool, cnt: usize) Error!void { +pub fn addNewline(e: Editor, t: *Text, below: bool, cnt: usize) Error!void { // above the selection's first line, below its last (helix line_range) const sr = selRows(t); const at = if (below) sr.hi_row else sr.lo_row; - const eb = (try editText(p.editor(), t, at, at, -1)) orelse return; - try pushUndo(p.editor(), t); + const eb = (try editText(e, t, at, at, -1)) orelse return; + try pushUndo(e, t); const row: usize = @intCast(@max(0, at - eb.row0)); - const arena = p.scratch.allocator(); + const arena = e.scratch; const nl = try arena.alloc(u8, cnt); @memset(nl, '\n'); const llen = modal.lineSlice(eb.text, row).len; - const new = try modal.insertAt(p.gpa, eb.text, .{ .row = row, .col = if (below) llen else 0 }, nl); - try setEditText(p.editor(), t, new); + const new = try modal.insertAt(e.gpa, eb.text, .{ .row = row, .col = if (below) llen else 0 }, nl); + try setEditText(e, t, new); if (!below) { // the whole selection moved down; stay on it const n: i32 = @intCast(cnt); @@ -1916,7 +1916,7 @@ fn pairFor(ch: u21) ?struct { o: u8, c: u8 } { }; } -pub fn textobjectSelect(p: *Pardes, t: *Text, text: []const u8, obj: u21, around: bool) Error!void { +pub fn textobjectSelect(e: Editor, t: *Text, text: []const u8, obj: u21, around: bool) Error!void { const range = t.primaryRange(text, 0); // helix's tree-sitter objects, from the grammar's textobjects query const object: ?modal.Normal.Object = switch (obj) { @@ -1933,7 +1933,7 @@ pub fn textobjectSelect(p: *Pardes, t: *Text, text: []const u8, obj: u21, around if (t.what != .body) return; const pane = t.pane() orelse return; const f = if (pane.file) |*file| file else return; - const tree = normal.fileTree(p, f) orelse return; + const tree = normal.fileTree(e.p, f) orelse return; const s = syntax.objectAt(f.path, tree, text, o, around, modal.selectionCursor(text, range)) orelse return; return t.setRange(text, 0, .{ .anchor = s.from, .head = s.to }, false); } @@ -1948,7 +1948,7 @@ pub fn textobjectSelect(p: *Pardes, t: *Text, text: []const u8, obj: u21, around }, else => {}, } - const lines = try paneCursorLines(p.editor(), t); + const lines = try paneCursorLines(e, t); const cur = modal.positionAt(text, modal.selectionCursor(text, range)); const pair: ?modal.Range = switch (obj) { '\'', '"', '`' => modal.enclosingQuote(lines, cur, @intCast(obj)), @@ -1972,26 +1972,26 @@ pub fn textobjectSelect(p: *Pardes, t: *Text, text: []const u8, obj: u21, around /// `ms`: wrap the selection (or the cursor char) in a pair; the wrap /// including the pair becomes the selection -pub fn surroundAdd(p: *Pardes, t: *Text, ch: u21) Error!void { +pub fn surroundAdd(e: Editor, t: *Text, ch: u21) Error!void { const pr = pairFor(ch) orelse return; t.select = false; - const eb = (try editTextEol(p.editor(), t, selRows(t))) orelse return; + const eb = (try editTextEol(e, t, selRows(t))) orelse return; const r = t.primaryRange(eb.text, eb.row0); const lo = @min(r.anchor, r.head); const hi = @max(r.anchor, r.head); - try pushUndo(p.editor(), t); + try pushUndo(e, t); const open = [1]u8{pr.o}; const close = [1]u8{pr.c}; - const new = try sam.apply(p.gpa, eb.text, &.{ .{ .q0 = @intCast(lo), .q1 = @intCast(lo), .text = &open }, .{ .q0 = @intCast(hi), .q1 = @intCast(hi), .text = &close } }); - try setEditText(p.editor(), t, new); + const new = try sam.apply(e.gpa, eb.text, &.{ .{ .q0 = @intCast(lo), .q1 = @intCast(lo), .text = &open }, .{ .q0 = @intCast(hi), .q1 = @intCast(hi), .text = &close } }); + try setEditText(e, t, new); // the wrapped range keeps the direction it had (helix with_direction) t.setRange(new, eb.row0, if (r.head < r.anchor) .{ .anchor = hi + 2, .head = lo } else .{ .anchor = lo, .head = hi + 2 }, false); } /// `md`: delete the enclosing pair's chars; the cursor maps through -pub fn surroundDelete(p: *Pardes, t: *Text, ch: u21) Error!void { +pub fn surroundDelete(e: Editor, t: *Text, ch: u21) Error!void { const pr = pairFor(ch) orelse return; - const lines = try paneCursorLines(p.editor(), t); + const lines = try paneCursorLines(e, t); const cur = t.toModalCursor(); const r = (if (pr.o == pr.c) modal.enclosingQuote(lines, cur, pr.o) @@ -1999,20 +1999,20 @@ pub fn surroundDelete(p: *Pardes, t: *Text, ch: u21) Error!void { 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 = (try editText(p.editor(), t, lo, hi, -1)) orelse return; + const eb = (try editText(e, 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 }; - try pushUndo(p.editor(), t); + try pushUndo(e, 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 }); - const new = try sam.apply(p.gpa, text, &.{ + const new = try sam.apply(e.gpa, text, &.{ .{ .q0 = @intCast(a_off), .q1 = @intCast(modal.nextGrapheme(text, a_off)), .text = "" }, .{ .q0 = @intCast(b_off), .q1 = @intCast(modal.nextGrapheme(text, b_off)), .text = "" }, }); - try setEditText(p.editor(), t, new); + try setEditText(e, t, new); var nc = cur_off; if (nc > b_off) nc -= 1; if (nc > a_off) nc -= 1; @@ -2025,24 +2025,24 @@ pub fn surroundDelete(p: *Pardes, t: *Text, ch: u21) Error!void { } /// `mr`: swap the enclosing pair's chars for 's -pub fn surroundReplace(p: *Pardes, t: *Text, from: u21, to: u21) Error!void { +pub fn surroundReplace(e: Editor, t: *Text, from: u21, to: u21) Error!void { const fp = pairFor(from) orelse return; const tp = pairFor(to) orelse return; - const lines = try paneCursorLines(p.editor(), t); + const lines = try paneCursorLines(e, t); 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 = (try editText(p.editor(), t, @as(i32, @intCast(r.a.row)), @as(i32, @intCast(r.b.row)), -1)) orelse return; + const eb = (try editText(e, 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); - try pushUndo(p.editor(), t); - const out = try p.gpa.dupe(u8, eb.text); + try pushUndo(e, t); + const out = try e.gpa.dupe(u8, eb.text); out[modal.lineStartOffset(out, ar) + r.a.col] = tp.o; out[modal.lineStartOffset(out, br) + r.b.col] = tp.c; - try setEditText(p.editor(), t, out); + try setEditText(e, t, out); } pub fn pushUndo(e: Editor, t: *Text) error{OutOfMemory}!void { @@ -2276,28 +2276,28 @@ test "insert and normal modes edit complete Unicode graphemes" { pane.body.mode = .insert; pane.body.cur_col = 22; // on z, after the CJK grapheme - try insertKey(p, &pane.body, .{ .cp = Key.left }); + try insertKey(p.editor(), &pane.body, .{ .cp = Key.left }); try std.testing.expectEqual(@as(i32, 19), pane.body.cur_col); - try insertKey(p, &pane.body, .{ .cp = Key.left }); + try insertKey(p.editor(), &pane.body, .{ .cp = Key.left }); try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col); - try insertKey(p, &pane.body, .{ .cp = Key.right }); + try insertKey(p.editor(), &pane.body, .{ .cp = Key.right }); try std.testing.expectEqual(@as(i32, 19), pane.body.cur_col); - try insertKey(p, &pane.body, .{ .cp = Key.backspace }); + try insertKey(p.editor(), &pane.body, .{ .cp = Key.backspace }); try std.testing.expectEqualStrings("ae\u{301}界z", pane.file.?.content); try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col); pane.body.mode = .normal; pane.body.cur_col = 1; - try normalDelete(p, &pane.body, false); + try normalDelete(p.editor(), &pane.body, false); try std.testing.expectEqualStrings("a界z", pane.file.?.content); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); - try normalReplaceChar(p, &pane.body, 'λ'); + try normalReplaceChar(p.editor(), &pane.body, 'λ'); try std.testing.expectEqualStrings("aλz", pane.file.?.content); panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "界a")); pane.body.cur_col = 3; pane.body.vsel = .{ .active = true, .row = 0, .col = 0, .explicit = true }; - try normalReplaceChar(p, &pane.body, 'λ'); + try normalReplaceChar(p.editor(), &pane.body, 'λ'); try std.testing.expectEqualStrings("λλ", pane.file.?.content); try std.testing.expectEqual(@as(i32, 2), pane.body.cur_col); try std.testing.expectEqual(@as(i32, 0), pane.body.vsel.col); @@ -2305,7 +2305,7 @@ test "insert and normal modes edit complete Unicode graphemes" { panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "界a")); pane.body.cur_col = 0; pane.body.vsel = .{ .active = true, .row = 0, .col = 3, .explicit = true }; - try normalReplaceChar(p, &pane.body, 'λ'); + try normalReplaceChar(p.editor(), &pane.body, 'λ'); try std.testing.expectEqualStrings("λλ", pane.file.?.content); try std.testing.expectEqual(@as(i32, 0), pane.body.cur_col); try std.testing.expectEqual(@as(i32, 2), pane.body.vsel.col); @@ -2322,7 +2322,7 @@ test "flat text replacement preserves a terminal fragment origin and direction" pane.body.cur_row = 3; pane.body.cur_col = 0; pane.body.vsel = .{ .active = true, .row = 3, .col = 3, .explicit = true }; - try normalReplaceChar(p, &pane.body, 'λ'); + try normalReplaceChar(p.editor(), &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.body.cur_row); @@ -2499,9 +2499,9 @@ test "typing and backspace through the line index keep the text and the index as pane.body.cur_col = @intCast(random.uintLessThan(usize, line.len + 1)); pane.body.cur_pinned = true; if (random.boolean()) { - try insertKey(p, &pane.body, .{ .cp = 'x', .text = "x" }); + try insertKey(p.editor(), &pane.body, .{ .cp = 'x', .text = "x" }); } else { - try insertKey(p, &pane.body, .{ .cp = Key.backspace }); + try insertKey(p.editor(), &pane.body, .{ .cp = Key.backspace }); } // the index the edits kept, against one built from the text const kept = try gpa.dupe(usize, try panes.File.lineIndex(gpa, &pane.file.?)); @@ -2530,7 +2530,7 @@ test "J joins a line with the next, its indent dropped, a space between unless t pane.body.cur_row = case.row; pane.body.cur_col = 0; if (case.rows > 0) pane.body.vsel = .{ .active = true, .row = case.row + case.rows, .col = 0, .explicit = true }; - try normalJoin(p, &pane.body, false); + try normalJoin(p.editor(), &pane.body, false); try std.testing.expectEqualStrings(case.want, pane.file.?.content); } } diff --git a/src/keys.zig b/src/keys.zig index 8a9006dc..03a3b307 100644 --- a/src/keys.zig +++ b/src/keys.zig @@ -43,9 +43,9 @@ pub fn cycleMode(p: *Pardes, id: usize) void { pane.body.mode = .normal; pane.body.normal.clear(); }, - .normal => edit.enterInsert(p, &pane.body, .at, 1) catch |err| p.reportError(id, "edit", err), + .normal => edit.enterInsert(p.editor(), &pane.body, .at, 1) catch |err| p.reportError(id, "edit", err), .insert => { - edit.exitInsert(p, &pane.body); + edit.exitInsert(p.editor(), &pane.body); if (pane.isTerminal()) enterTty(p, id); }, } @@ -232,7 +232,7 @@ pub fn handleKey(p: *Pardes, key: Key) void { pane.focus = .body; } for ([_]*Text{ &pane.body, &pane.tag }) |t| { - if (t.mode == .insert) edit.exitInsert(p, t); + if (t.mode == .insert) edit.exitInsert(p.editor(), t); t.normal.clear(); t.select = false; } @@ -342,7 +342,7 @@ pub fn handleKey(p: *Pardes, key: Key) void { p.setMessage(p.view().active, "name drafted: Enter renames the buffer, Esc drops the draft"); return; } - edit.handleInsert(p, &pane.input, key); + edit.handleInsert(p.editor(), &pane.input, key); return; } if (header == null and pane.prompt != .none) { @@ -365,7 +365,7 @@ pub fn handleKey(p: *Pardes, key: Key) void { } return; } - edit.handleInsert(p, &pane.input, key); + edit.handleInsert(p.editor(), &pane.input, key); if (normal.selRegexArmed(pane)) |a| if (panes.promptTarget(p, pane)) |answered| normal.applySelRegex(p, pane, answered, a.pat, a.mode); return; } @@ -444,9 +444,9 @@ pub fn handleKey(p: *Pardes, key: Key) void { switch (t.mode) { .normal => normal.handleNormal(p, t, key), .insert => if (hit(key, config.escape) and !t.reg_wait) - edit.exitInsert(p, t) + edit.exitInsert(p.editor(), t) else - edit.handleInsert(p, t, key), + edit.handleInsert(p.editor(), t, key), .tty => forwardKey(p, p.view().active, key), } // `.`'s log: the keys of the normal command that entered insert diff --git a/src/lsp/Ask.zig b/src/lsp/Ask.zig index da03c021..2ee33123 100644 --- a/src/lsp/Ask.zig +++ b/src/lsp/Ask.zig @@ -308,7 +308,7 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { } if (rows.len == 0) { 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) catch |err| return p.reportError(w.pane, "complete", err); + pane.body.cur_row == w.row and pane.body.cur_col == w.col) edit.insertTab(p.editor(), &pane.body) catch |err| return p.reportError(w.pane, "complete", err); // Nothing found fails, but for a file with no diagnostics, // which is no failure, and a completion's Tab. const none: ?[]const u8 = switch (w.kind) { diff --git a/src/mouse.zig b/src/mouse.zig index 590f6806..4eb18141 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -412,10 +412,10 @@ fn chordCutPaste(p: *Pardes, cut: bool) edit.Error!void { t.nsel = 0; } if (cut) { - if (t.vsel.active) try edit.normalDelete(p, t, true); + if (t.vsel.active) try edit.normalDelete(p.editor(), t, true); } else if (t.vsel.active) { - try edit.chordReplace(p, t); - } else try edit.pasteText(p, t, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1); + try edit.chordReplace(p.editor(), t); + } else try edit.pasteText(p.editor(), t, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1); return; } if (pane.body.mode == .tty) { @@ -466,9 +466,9 @@ fn chordCutPaste(p: *Pardes, cut: bool) edit.Error!void { pane.body.nsel = 0; } if (cut) { - if (pane.body.vsel.active) try edit.normalDelete(p, &pane.body, true); + if (pane.body.vsel.active) try edit.normalDelete(p.editor(), &pane.body, true); } else if (pane.body.vsel.active) { - try edit.chordReplace(p, &pane.body); + try edit.chordReplace(p.editor(), &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 @@ -491,7 +491,7 @@ fn chordCutPaste(p: *Pardes, cut: bool) edit.Error!void { pane.body.cur_pinned = true; pane.body.sticky_col = -1; pane.ensureCursorVisible(); - } else try edit.pasteText(p, &pane.body, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1); + } else try edit.pasteText(p.editor(), &pane.body, p.registers.text(p.gpa, pardes.Registers.default) orelse return, true, 1); } pub fn handleMouse(p: *Pardes, event: Mouse) void { diff --git a/src/normal.zig b/src/normal.zig index a344269c..29addd66 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -460,7 +460,7 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { t.sticky_col = list[i].sticky; (switch (what) { .normal => |normal_action| executeNormalAction(p, t, normal_action), - .insert => |insert_key| edit.insertKey(p, t, insert_key), + .insert => |insert_key| edit.insertKey(p.editor(), t, insert_key), }) catch |err| p.reportError(p.view().active, "edit", err); if (p.multi_stop) break; if (i == pri) { @@ -956,7 +956,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! pane.clearPointerSelection(sel_slot); pane.sel[sel_slot].state = .none; }; - if (raw_selection and a.role == .yank) return edit.normalYank(p, t); + if (raw_selection and a.role == .yank) return edit.normalYank(p.editor(), t); edit.pinPaneCursor(p.editor(), t); const text = try edit.flatSurface(p.editor(), t); const range = t.primaryRange(text, 0); @@ -1038,19 +1038,19 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! t.find_ch = a.char; return findMove(t, text, range, a.char, t.find_op.?, a.count); }, - .replace_prefix => return edit.normalReplaceChar(p, t, a.char), + .replace_prefix => return edit.normalReplaceChar(p.editor(), t, a.char), // `mm` .match_prefix => { const lines = try edit.paneCursorLines(p.editor(), t); const mc = modal.matchBracket(lines, modal.positionAt(text, cur)) orelse return; return pointMove(t, text, range, modal.offsetAt(text, mc)); }, - .match_inside, .match_around => return edit.textobjectSelect(p, t, text, a.char, a.role == .match_around), - .surround_add => return edit.surroundAdd(p, t, a.char), - .surround_delete => return edit.surroundDelete(p, t, a.char), - .surround_replace => return edit.surroundReplace(p, t, a.from, a.char), + .match_inside, .match_around => return edit.textobjectSelect(p.editor(), t, text, a.char, a.role == .match_around), + .surround_add => return edit.surroundAdd(p.editor(), t, a.char), + .surround_delete => return edit.surroundDelete(p.editor(), t, a.char), + .surround_replace => return edit.surroundReplace(p.editor(), t, a.from, a.char), .goto_paragraph => return t.setRange(text, 0, modal.moveParagraph(text, range, a.count, a.forward, t.select), false), - .add_newline => return edit.addNewline(p, t, a.forward, a.count), + .add_newline => return edit.addNewline(p.editor(), t, a.forward, a.count), .goto_diagnostic, .goto_diagnostic_end => { // Once a Diagnostics query fed them, the diagnostics are this // text's places: ]d and [d step them as n and N do, ]D and [D @@ -1107,7 +1107,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! .open_below => .open_below, else => .open_above, }; - return edit.enterInsert(p, t, where, a.count); + return edit.enterInsert(p.editor(), t, where, a.count); }, .select_mode => { if (t.select) { @@ -1137,24 +1137,24 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! // the body wherever it is pressed, as acme's Look from a tag does. inline .select_regex, .split_regex, .keep_regex, .remove_regex => |role| return startSelRegex(p, pane, t, @field(modal.Normal.RegexMode, @tagName(role)[0 .. @tagName(role).len - "_regex".len])), inline .expand_node, .shrink_node, .next_sibling, .prev_sibling, .all_siblings, .all_children, .parent_node_end, .parent_node_start => |role| return nodeSelect(p, pane, t, @field(modal.Normal.NodeWalk, @tagName(role))), - .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.pasteRegister(p, t, .replace, a.count), - .paste_after => return edit.pasteRegister(p, t, .after, a.count), - .paste_before => return edit.pasteRegister(p, t, .before, a.count), - .switch_case => return edit.normalCase(p, t, .toggle), - .to_lowercase => return edit.normalCase(p, t, .lower), - .to_uppercase => return edit.normalCase(p, t, .upper), - .join_lines => return edit.normalJoin(p, t, false), - .join_select_space => return edit.normalJoin(p, t, true), - .rotate_contents_fwd => return edit.normalRotateContents(p, t, true, a.count), - .rotate_contents_back => return edit.normalRotateContents(p, t, false, a.count), - .align_selections => return edit.normalAlign(p, t), - .indent => return edit.normalIndent(p, t, a.count, true), - .unindent => return edit.normalIndent(p, t, a.count, false), - .comment_toggle => return edit.normalToggleComment(p, t), + .delete => return edit.normalDelete(p.editor(), t, true), + .delete_noyank => return edit.normalDelete(p.editor(), t, false), + .change => return edit.normalChange(p.editor(), t), + .yank => return edit.normalYank(p.editor(), t), + .replace_with_yank => return edit.pasteRegister(p.editor(), t, .replace, a.count), + .paste_after => return edit.pasteRegister(p.editor(), t, .after, a.count), + .paste_before => return edit.pasteRegister(p.editor(), t, .before, a.count), + .switch_case => return edit.normalCase(p.editor(), t, .toggle), + .to_lowercase => return edit.normalCase(p.editor(), t, .lower), + .to_uppercase => return edit.normalCase(p.editor(), t, .upper), + .join_lines => return edit.normalJoin(p.editor(), t, false), + .join_select_space => return edit.normalJoin(p.editor(), t, true), + .rotate_contents_fwd => return edit.normalRotateContents(p.editor(), t, true, a.count), + .rotate_contents_back => return edit.normalRotateContents(p.editor(), t, false, a.count), + .align_selections => return edit.normalAlign(p.editor(), t), + .indent => return edit.normalIndent(p.editor(), t, a.count, true), + .unindent => return edit.normalIndent(p.editor(), t, a.count, false), + .comment_toggle => return edit.normalToggleComment(p.editor(), t), .undo => return edit.undoStep(p.editor(), t, true), .redo => return edit.undoStep(p.editor(), t, false), // Language shortcuts run the same builtins as tags and leader commands. @@ -1165,8 +1165,8 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! .goto_type_definition => return p.lspRequest(v.active, .type_definition, ""), .goto_implementation => return p.lspRequest(v.active, .implementation, ""), .format => return p.lspRequest(v.active, .format, ""), - .increment => return edit.normalAdjustNumber(p, t, @intCast(a.count)), - .decrement => return edit.normalAdjustNumber(p, t, -@as(i64, @intCast(a.count))), + .increment => return edit.normalAdjustNumber(p.editor(), t, @intCast(a.count)), + .decrement => return edit.normalAdjustNumber(p.editor(), t, -@as(i64, @intCast(a.count))), .leader => if (p.macro.replaying == 0) { v.prefix = .leader; v.leader_n = 0; diff --git a/src/tagline.zig b/src/tagline.zig index 84cb3173..d7c657ff 100644 --- a/src/tagline.zig +++ b/src/tagline.zig @@ -365,7 +365,7 @@ pub fn typedIntoName(p: *Pardes, pane: *Pane, key: pardes.Key) bool { const inside = if (back) at > 0 and at <= f.path.len else if (forward or typed) at < f.path.len else false; if (!inside) return false; draftName(p, pane, panes.File.displayWidth(f.path[0..at])); - edit.handleInsert(p, &pane.input, key); + edit.handleInsert(p.editor(), &pane.input, key); return true; } -- cgit v1.3 From b06543725a84ac5ce8cc48810b526c00032247cf Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 05:57:17 -0300 Subject: normal: a normal-mode action splits into the text's roles and the core's (docs/next-editor.md, R2, third slice): textAction takes `e: Editor` and does the 58 roles of the text alone (motions, selections, edits, undo, registers, Esc's and `*`'s own part), textRole says which those are, and executeNormalAction keeps the 34 that reach past the text (views, builtins, prompts, LSP, the look ring, jump labels, macros), handing the rest over; replaySels, handleNormal, searchStep and searchSelection take the context, keys.zig hands `p.editor()`; nothing a key does changes; core-test 810 of 949, shell-test 989 of 992, hxdiff 658 / parity 738 / hxgolf 124 with 0 mismatches, replicas pass --- src/edit.zig | 4 +- src/keys.zig | 2 +- src/normal.zig | 360 +++++++++++++++++++++++++++++++-------------------------- 3 files changed, 196 insertions(+), 170 deletions(-) (limited to 'src/normal.zig') diff --git a/src/edit.zig b/src/edit.zig index 9ae00079..4b0e59fe 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -187,7 +187,7 @@ pub fn clipYank(p: *Pardes, pane: *Pane, main_only: bool) void { return; } if (pane.body.nsel > 0 and !main_only) { - normal.replaySels(p, &pane.body, .{ .normal = .{ .role = .yank } }); + normal.replaySels(p.editor(), &pane.body, .{ .normal = .{ .role = .yank } }); } else { const others = pane.body.nsel; pane.body.nsel = 0; @@ -901,7 +901,7 @@ pub fn enterInsert(e: Editor, t: *Text, where: InsertAt, cnt: usize) Error!void pub fn handleInsert(e: Editor, t: *Text, key: Key) void { if (t.nsel == 0) return insertKey(e, t, key) catch |err| e.reportError(err); - normal.replaySels(e.p, t, .{ .insert = key }); + normal.replaySels(e, t, .{ .insert = key }); } pub fn insertKey(e: Editor, t: *Text, key: Key) Error!void { diff --git a/src/keys.zig b/src/keys.zig index 03a3b307..0277128b 100644 --- a/src/keys.zig +++ b/src/keys.zig @@ -442,7 +442,7 @@ pub fn handleKey(p: *Pardes, key: Key) void { }; const was = t.mode; switch (t.mode) { - .normal => normal.handleNormal(p, t, key), + .normal => normal.handleNormal(p.editor(), t, key), .insert => if (hit(key, config.escape) and !t.reg_wait) edit.exitInsert(p.editor(), t) else diff --git a/src/normal.zig b/src/normal.zig index 29addd66..77f0c24c 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -395,8 +395,8 @@ fn selStart(s: Text.SelRange) struct { row: i32, col: i32 } { return .{ .row = s.row, .col = s.col }; } -pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { - const id = p.view().active; +pub fn replaySels(e: Editor, t: *Text, what: Replay) void { + const id = e.p.view().active; // a header belongs to no pane and cannot go away under the replay const owner = t.pane(); const serial = if (owner) |pane| pane.serial else 0; @@ -438,14 +438,14 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { // 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: [Text.max_selections]struct { cur: usize, anc: usize, sticky: i32 } = undefined; - p.multi_stop = false; + e.multi_stop.* = false; var passes: usize = 0; var i: usize = n; while (i > 0) { i -= 1; - p.multi_first = passes == 0; - p.multi_index = i; - p.multi_count = n; + e.multi_first.* = passes == 0; + e.multi_index.* = i; + e.multi_count.* = n; passes += 1; saved.into(t); t.nsel = 0; // the handler underneath sees ONE selection @@ -459,16 +459,16 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { }; t.sticky_col = list[i].sticky; (switch (what) { - .normal => |normal_action| executeNormalAction(p, t, normal_action), - .insert => |insert_key| edit.insertKey(p.editor(), t, insert_key), - }) catch |err| p.reportError(p.view().active, "edit", err); - if (p.multi_stop) break; + .normal => |normal_action| executeNormalAction(e.p, t, normal_action), + .insert => |insert_key| edit.insertKey(e, t, insert_key), + }) catch |err| e.reportError(err); + if (e.multi_stop.*) break; if (i == pri) { after = KeyState.of(t); after_expl = t.vsel.explicit; } - const text = edit.flatSurface(p.editor(), t) catch { - p.multi_stop = true; + const text = edit.flatSurface(e, t) catch { + e.multi_stop.* = true; break; }; const co = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) }); @@ -478,19 +478,19 @@ pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { co; res[i] = .{ .cur = text.len - @min(co, text.len), .anc = text.len - @min(ao, text.len), .sticky = t.sticky_col }; } - p.multi_first = true; - p.multi_index = 0; - p.multi_count = 1; - if (p.multi_stop) { - p.multi_stop = false; + e.multi_first.* = true; + e.multi_index.* = 0; + e.multi_count.* = 1; + if (e.multi_stop.*) { + e.multi_stop.* = false; if (owner != null) { - const pn = p.panes[id] orelse return; + const pn = e.p.panes[id] orelse return; if (pn.serial != serial) return; } t.nsel = 0; return; } - const text = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(p.view().active, "edit", err); + const text = edit.flatSurface(e, t) catch |err| return e.reportError(err); var rs: [Text.max_selections]modal.Selection = undefined; var st: [Text.max_selections]i32 = undefined; for (res[0..n], 0..) |r, k| { @@ -522,7 +522,7 @@ fn normalInput(key: Key) modal.Normal.Input { return out; } -pub fn handleNormal(p: *Pardes, t: *Text, key: Key) void { +pub fn handleNormal(e: Editor, t: *Text, key: Key) void { // `"` is held by the parser until the command it names arrives const named = t.normal.register; const parsed = modal.Normal.parse(&t.normal, normalInput(key)); @@ -531,11 +531,11 @@ pub fn handleNormal(p: *Pardes, t: *Text, key: Key) void { .action => |value| value, }; t.normal.register = 0; - p.view().register = named; - defer p.view().register = 0; + e.register.* = named; + defer e.register.* = 0; if (t.nsel == 0 or action.once()) - return executeNormalAction(p, t, action) catch |err| p.reportError(p.view().active, "edit", err); - replaySels(p, t, .{ .normal = action }); + return executeNormalAction(e.p, t, action) catch |err| e.reportError(err); + replaySels(e, t, .{ .normal = action }); } fn startSelRegex(p: *Pardes, pane: *Pane, t: *Text, mode: modal.Normal.RegexMode) edit.Error!void { @@ -549,18 +549,18 @@ fn startSelRegex(p: *Pardes, pane: *Pane, t: *Text, mode: modal.Normal.RegexMode /// Search only the primary range, as Helix does. Select mode adds a new /// match and makes it primary; normal mode replaces only the primary. -fn searchStep(p: *Pardes, t: *Text, text: []const u8, forward: bool, count: u32) edit.Error!void { - const v = p.view(); - const name = if (v.register != 0) v.register else p.registers.last_search; - const pat = p.registers.value(name, 0) orelse return; - var re = SearchRegex.compile(p.scratch.allocator(), pat) catch { - p.setMessage(v.active, "invalid search pattern"); +fn searchStep(e: Editor, t: *Text, text: []const u8, forward: bool, count: u32) edit.Error!void { + const v = e.p.view(); + const name = if (e.register.* != 0) e.register.* else e.registers.last_search; + const pat = e.registers.value(name, 0) orelse return; + var re = SearchRegex.compile(e.scratch, pat) catch { + e.p.setMessage(v.active, "invalid search pattern"); return; }; var hay = text; if (for (pat) |c| { if (std.ascii.isUpper(c)) break false; - } else true) hay = try std.ascii.allocLowerString(p.scratch.allocator(), text); + } else true) hay = try std.ascii.allocLowerString(e.scratch, text); for (0..count) |_| { var ranges: [Text.max_selections]modal.Selection = undefined; const got = t.ranges(text, 0, &ranges); @@ -577,7 +577,7 @@ fn searchStep(p: *Pardes, t: *Text, text: []const u8, forward: bool, count: u32) wrapped = true; break :blk lastMatch(&re, hay, from, hay.len); }) orelse { - p.setMessage(v.active, "no more matches"); + e.p.setMessage(v.active, "no more matches"); return; }; if (found.end == 0) return; @@ -592,16 +592,16 @@ fn searchStep(p: *Pardes, t: *Text, text: []const u8, forward: bool, count: u32) ranges[got.pri] = next; t.setRanges(text, ranges[0..got.n], &.{}, got.pri, true); } - if (wrapped) p.setMessage(v.active, "wrapped around document"); + if (wrapped) e.p.setMessage(v.active, "wrapped around document"); } t.show(); } -pub fn searchSelection(p: *Pardes, t: *Text, text: []const u8, boundary: bool) edit.Error!void { +pub fn searchSelection(e: Editor, t: *Text, text: []const u8, boundary: bool) edit.Error!void { var ranges: [Text.max_selections]modal.Selection = undefined; const got = t.ranges(text, 0, &ranges); var pattern: std.ArrayList(u8) = .empty; - const arena = p.scratch.allocator(); + const arena = e.scratch; for (ranges[0..got.n], 0..) |r, i| { const from = @min(r.anchor, r.head); const to = @min(text.len, @max(r.anchor, r.head)); @@ -610,9 +610,9 @@ pub fn searchSelection(p: *Pardes, t: *Text, text: []const u8, boundary: bool) e try appendSearchLiteral(&pattern, arena, text[from..to]); if (boundary and to < text.len and modal.searchWordBefore(text, to) and !modal.searchWordAt(text, to)) try pattern.appendSlice(arena, "\\b"); } - const name = if (p.view().register != 0) p.view().register else '/'; - try p.registers.put(p.gpa, name, pattern.items, 0, 1, true); - p.registers.last_search = name; + const name = if (e.register.* != 0) e.register.* else '/'; + try e.registers.put(e.gpa, name, pattern.items, 0, 1, true); + e.registers.last_search = name; } fn multiSelAction(t: *Text, text: []const u8, role: modal.Normal.Role, cnt: usize) void { @@ -945,20 +945,21 @@ fn shrinkSelToLineBounds(t: *Text, text: []const u8, range: modal.Selection) voi t.setRange(text, 0, r, expl); } -fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error!void { - const v = p.view(); - // 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 = t.pane() orelse p.panes[v.active] orelse return; - const raw_selection = t.what == .body and pane.rawPointerText(pane.sel[sel_slot]) != null; - const before = .{ t.cur_row, t.cur_col, t.vsel, t.select, t.nsel, t.mode }; - defer if (raw_selection and !std.meta.eql(before, .{ t.cur_row, t.cur_col, t.vsel, t.select, t.nsel, t.mode })) { - pane.clearPointerSelection(sel_slot); - pane.sel[sel_slot].state = .none; +/// Whether a normal-mode role is the text's alone (`textAction`), or +/// reaches past it: a view, a builtin, a prompt, a language server, the +/// look ring, the jump labels, a macro. +pub fn textRole(role: modal.Normal.Role) bool { + return switch (role) { + .all_children, .all_siblings, .append_output, .command_line, .expand_node, .format, .goto_callstack, .goto_class, .goto_comment, .goto_declaration, .goto_definition, .goto_diagnostic, .goto_diagnostic_end, .goto_entry, .goto_function, .goto_implementation, .goto_parameter, .goto_references, .goto_test, .goto_type_definition, .goto_view_bottom, .goto_view_top, .goto_word, .goto_xml_element, .half_page_down, .half_page_up, .insert_output, .keep_pipe, .keep_regex, .leader, .macro_record, .macro_replay, .next_sibling, .page_down, .page_up, .parent_node_end, .parent_node_start, .pipe_selection, .pipe_selection_to, .prev_sibling, .remove_regex, .repeat_insert, .search, .search_next, .search_prev, .select_regex, .shrink_node, .split_regex, .view_bottom, .view_center, .view_middle, .view_scroll_down, .view_scroll_up, .view_top => false, + else => true, }; - if (raw_selection and a.role == .yank) return edit.normalYank(p.editor(), t); - edit.pinPaneCursor(p.editor(), t); - const text = try edit.flatSurface(p.editor(), t); +} + +/// A normal-mode action of the text's own (`textRole`): a motion, a +/// selection, an edit, an undo, a register. +pub fn textAction(e: Editor, t: *Text, a: modal.Normal.Action) edit.Error!void { + edit.pinPaneCursor(e, t); + const text = try edit.flatSurface(e, t); const range = t.primaryRange(text, 0); const cur = modal.selectionCursor(text, range); @@ -966,9 +967,9 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! .escape => { t.select = false; // typed again by a macro, Esc is only helix's - if (p.macro.replaying > 0) return; - tagline.exitHeader(p); // out of a header too, as Shift-Esc - return exec.runBuiltin(p, .Last, v.active, "", null); + if (e.p.macro.replaying > 0) return; + tagline.exitHeader(e.p); // out of a header too, as Shift-Esc + return exec.runBuiltin(e.p, .Last, e.p.view().active, "", null); }, // gg and G: a count names the line; bare G is no move (helix) .goto_file_start, .goto_line => { @@ -991,43 +992,17 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! if (nw == slice.len) return; return pointMove(t, text, range, ls + nw); }, - .goto_line_down => return verticalMove(t, text, range, true, a.count, edit.paneWrapWidth(p.editor(), t)), - .goto_line_up => return verticalMove(t, text, range, false, a.count, edit.paneWrapWidth(p.editor(), t)), + .goto_line_down => return verticalMove(t, text, range, true, a.count, edit.paneWrapWidth(e, t)), + .goto_line_up => return verticalMove(t, text, range, false, a.count, edit.paneWrapWidth(e, t)), .goto_column => { const line = modal.lineAtOffset(text, cur); const ls = modal.lineStartOffset(text, line); return pointMove(t, text, range, ls + modal.graphemeAtColumn(text[ls..modal.lineEndOffset(text, line)], @as(usize, a.count) - 1)); }, - .goto_view_top => return gotoWindow(t, text, range, .top, a.count), - .goto_view_bottom => return gotoWindow(t, text, range, .bottom, a.count), .goto_last_modification => { const at = t.last_edit orelse return; return pointMove(t, text, range, modal.offsetAt(text, .{ .row = @intCast(@max(0, at.row)), .col = @intCast(@max(0, at.col)) })); }, - // helix align_view: the cursor's row goes `above` rows down the - // view, the middle of an odd one and the upper middle of an even one - .view_top, .view_center, .view_bottom => if (t.what == .body) { - const above: i32 = switch (a.role) { - .view_top => 0, - .view_center => @divTrunc(@as(i32, pane.rows) - 1, 2), - else => @as(i32, pane.rows) - 1, - }; - pane.scrollBy(t.cur_row - (pane.scroll() + above)); - pane.ensureCursorVisible(); - }, - // helix align_view_middle: the cursor's column to the middle of an - // unwrapped view - .view_middle => if (t.what == .body) { - panes.File.geometry(pane); - if (pane.body_wrapped) return; - const line = modal.lineAtOffset(text, cur); - const slice = text[modal.lineStartOffset(text, line)..modal.lineEndOffset(text, line)]; - const w: usize = @intCast(@max(1, @as(i32, pane.cols) - @as(i32, panes.File.gutterWidth(pane)))); - const col = panes.File.rawDisplayCol(slice, @intCast(@max(0, t.cur_col))); - pane.hscroll = @intCast(panes.File.rawAtDisplay(slice, col -| w / 2)); - }, - .view_scroll_down => if (t.what == .body) return t.scrollViewMove(text, range, 1), - .view_scroll_up => if (t.what == .body) return t.scrollViewMove(text, range, -1), .find_char_fwd, .find_char_back, .till_char_fwd, .till_char_back => { t.find_op = switch (a.role) { .find_char_fwd => .forward, @@ -1038,37 +1013,19 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! t.find_ch = a.char; return findMove(t, text, range, a.char, t.find_op.?, a.count); }, - .replace_prefix => return edit.normalReplaceChar(p.editor(), t, a.char), + .replace_prefix => return edit.normalReplaceChar(e, t, a.char), // `mm` .match_prefix => { - const lines = try edit.paneCursorLines(p.editor(), t); + const lines = try edit.paneCursorLines(e, t); const mc = modal.matchBracket(lines, modal.positionAt(text, cur)) orelse return; return pointMove(t, text, range, modal.offsetAt(text, mc)); }, - .match_inside, .match_around => return edit.textobjectSelect(p.editor(), t, text, a.char, a.role == .match_around), - .surround_add => return edit.surroundAdd(p.editor(), t, a.char), - .surround_delete => return edit.surroundDelete(p.editor(), t, a.char), - .surround_replace => return edit.surroundReplace(p.editor(), t, a.from, a.char), + .match_inside, .match_around => return edit.textobjectSelect(e, t, text, a.char, a.role == .match_around), + .surround_add => return edit.surroundAdd(e, t, a.char), + .surround_delete => return edit.surroundDelete(e, t, a.char), + .surround_replace => return edit.surroundReplace(e, t, a.from, a.char), .goto_paragraph => return t.setRange(text, 0, modal.moveParagraph(text, range, a.count, a.forward, t.select), false), - .add_newline => return edit.addNewline(p.editor(), t, a.forward, a.count), - .goto_diagnostic, .goto_diagnostic_end => { - // Once a Diagnostics query fed them, the diagnostics are this - // text's places: ]d and [d step them as n and N do, ]D and [D - // go to the last and the first. Until then, asked for. - const set = &pane.places; - const fed = set.started and set.provenance == .list and if (p.paneBySerial(set.from)) |qid| - (if (p.panes[qid].?.query) |q| q.source == .diagnostics else false) - else - false; - if (!fed) return p.lspRequest(v.active, .diagnostics, ""); - if (a.role == .goto_diagnostic) return set.step(p, pane, a.forward, 1, false); - if (set.hits.items.len == 0) return; - set.goTo(pane, if (a.forward) set.hits.items.len - 1 else 0, false); - }, - inline .goto_function, .goto_class, .goto_parameter, .goto_comment, .goto_test, .goto_entry, .goto_xml_element => |role| { - const object = @field(modal.Normal.Object, @tagName(role)["goto_".len..]); - return objectJump(p, pane, t, text, range, object, a.forward, a.count); - }, + .add_newline => return edit.addNewline(e, t, a.forward, a.count), .move_left, .move_right => { var target = cur; for (0..a.count) |_| target = if (a.role == .move_left) modal.prevGrapheme(text, target) else modal.nextGrapheme(text, target); @@ -1093,11 +1050,6 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! if (!moved) return; return t.setRange(text, 0, repeated, false); }, - // These four move exactly one viewport unit, whatever the count. - .half_page_down => return halfPageMove(t, text, range, true), - .half_page_up => return halfPageMove(t, text, range, false), - .page_down => return t.scrollViewMove(text, range, @as(i32, pane.rows)), - .page_up => return t.scrollViewMove(text, range, -@as(i32, pane.rows)), .insert, .append, .insert_line_start, .insert_line_end, .open_below, .open_above => { const where: edit.InsertAt = switch (a.role) { .insert => .at, @@ -1107,7 +1059,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! .open_below => .open_below, else => .open_above, }; - return edit.enterInsert(p.editor(), t, where, a.count); + return edit.enterInsert(e, t, where, a.count); }, .select_mode => { if (t.select) { @@ -1133,30 +1085,118 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! .select_all => return t.setRange(text, 0, .{ .anchor = 0, .head = text.len }, false), .keep_primary_sel => return t.dropSels(), .copy_sel_below, .copy_sel_above, .remove_primary_sel, .rotate_sel_fwd, .rotate_sel_back, .split_sel_newline, .merge_sels, .merge_consecutive_sels, .trim_sels, .ensure_forward => return multiSelAction(t, text, a.role, a.count), + .delete => return edit.normalDelete(e, t, true), + .delete_noyank => return edit.normalDelete(e, t, false), + .change => return edit.normalChange(e, t), + .yank => return edit.normalYank(e, t), + .replace_with_yank => return edit.pasteRegister(e, t, .replace, a.count), + .paste_after => return edit.pasteRegister(e, t, .after, a.count), + .paste_before => return edit.pasteRegister(e, t, .before, a.count), + .switch_case => return edit.normalCase(e, t, .toggle), + .to_lowercase => return edit.normalCase(e, t, .lower), + .to_uppercase => return edit.normalCase(e, t, .upper), + .join_lines => return edit.normalJoin(e, t, false), + .join_select_space => return edit.normalJoin(e, t, true), + .rotate_contents_fwd => return edit.normalRotateContents(e, t, true, a.count), + .rotate_contents_back => return edit.normalRotateContents(e, t, false, a.count), + .align_selections => return edit.normalAlign(e, t), + .indent => return edit.normalIndent(e, t, a.count, true), + .unindent => return edit.normalIndent(e, t, a.count, false), + .comment_toggle => return edit.normalToggleComment(e, t), + .undo => return edit.undoStep(e, t, true), + .redo => return edit.undoStep(e, t, false), + .increment => return edit.normalAdjustNumber(e, t, @intCast(a.count)), + .decrement => return edit.normalAdjustNumber(e, t, -@as(i64, @intCast(a.count))), + .search_selection, .search_selection_word => { + try searchSelection(e, t, text, a.role == .search_selection_word); + // The pattern is line 1 of this text's query pane, made or + // reused, the keyboard staying here: n and N step its places. + const pane = t.pane() orelse return; + if (t.what == .body and pane.file != null and pane.query == null) { + const name = if (e.register.* != 0) e.register.* else '/'; + const pat = e.registers.value(name, 0) orelse return; + panes.Query.open(e.p, e.p.view().active, .text, pat, false); + pane.places.provenance = .search; + } + }, + // prefix keys: what they begin is the command + .goto_prefix, .view_prefix, .next_prefix, .prev_prefix, .register_prefix, .view_prefix_sticky => {}, + else => unreachable, // the core's (textRole) + } +} + +fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error!void { + const v = p.view(); + // 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 = t.pane() orelse p.panes[v.active] orelse return; + const raw_selection = t.what == .body and pane.rawPointerText(pane.sel[sel_slot]) != null; + const before = .{ t.cur_row, t.cur_col, t.vsel, t.select, t.nsel, t.mode }; + defer if (raw_selection and !std.meta.eql(before, .{ t.cur_row, t.cur_col, t.vsel, t.select, t.nsel, t.mode })) { + pane.clearPointerSelection(sel_slot); + pane.sel[sel_slot].state = .none; + }; + if (raw_selection and a.role == .yank) return edit.normalYank(p.editor(), t); + if (textRole(a.role)) return textAction(p.editor(), t, a); + edit.pinPaneCursor(p.editor(), t); + const text = try edit.flatSurface(p.editor(), t); + const range = t.primaryRange(text, 0); + const cur = modal.selectionCursor(text, range); + + switch (a.role) { + .goto_view_top => return gotoWindow(t, text, range, .top, a.count), + .goto_view_bottom => return gotoWindow(t, text, range, .bottom, a.count), + // helix align_view: the cursor's row goes `above` rows down the + // view, the middle of an odd one and the upper middle of an even one + .view_top, .view_center, .view_bottom => if (t.what == .body) { + const above: i32 = switch (a.role) { + .view_top => 0, + .view_center => @divTrunc(@as(i32, pane.rows) - 1, 2), + else => @as(i32, pane.rows) - 1, + }; + pane.scrollBy(t.cur_row - (pane.scroll() + above)); + pane.ensureCursorVisible(); + }, + // helix align_view_middle: the cursor's column to the middle of an + // unwrapped view + .view_middle => if (t.what == .body) { + panes.File.geometry(pane); + if (pane.body_wrapped) return; + const line = modal.lineAtOffset(text, cur); + const slice = text[modal.lineStartOffset(text, line)..modal.lineEndOffset(text, line)]; + const w: usize = @intCast(@max(1, @as(i32, pane.cols) - @as(i32, panes.File.gutterWidth(pane)))); + const col = panes.File.rawDisplayCol(slice, @intCast(@max(0, t.cur_col))); + pane.hscroll = @intCast(panes.File.rawAtDisplay(slice, col -| w / 2)); + }, + .view_scroll_down => if (t.what == .body) return t.scrollViewMove(text, range, 1), + .view_scroll_up => if (t.what == .body) return t.scrollViewMove(text, range, -1), + .goto_diagnostic, .goto_diagnostic_end => { + // Once a Diagnostics query fed them, the diagnostics are this + // text's places: ]d and [d step them as n and N do, ]D and [D + // go to the last and the first. Until then, asked for. + const set = &pane.places; + const fed = set.started and set.provenance == .list and if (p.paneBySerial(set.from)) |qid| + (if (p.panes[qid].?.query) |q| q.source == .diagnostics else false) + else + false; + if (!fed) return p.lspRequest(v.active, .diagnostics, ""); + if (a.role == .goto_diagnostic) return set.step(p, pane, a.forward, 1, false); + if (set.hits.items.len == 0) return; + set.goTo(pane, if (a.forward) set.hits.items.len - 1 else 0, false); + }, + inline .goto_function, .goto_class, .goto_parameter, .goto_comment, .goto_test, .goto_entry, .goto_xml_element => |role| { + const object = @field(modal.Normal.Object, @tagName(role)["goto_".len..]); + return objectJump(p, pane, t, text, range, object, a.forward, a.count); + }, + // These four move exactly one viewport unit, whatever the count. + .half_page_down => return halfPageMove(t, text, range, true), + .half_page_up => return halfPageMove(t, text, range, false), + .page_down => return t.scrollViewMove(text, range, @as(i32, pane.rows)), + .page_up => return t.scrollViewMove(text, range, -@as(i32, pane.rows)), // s, S and | answer for the text they are pressed in; `/` searches // the body wherever it is pressed, as acme's Look from a tag does. inline .select_regex, .split_regex, .keep_regex, .remove_regex => |role| return startSelRegex(p, pane, t, @field(modal.Normal.RegexMode, @tagName(role)[0 .. @tagName(role).len - "_regex".len])), inline .expand_node, .shrink_node, .next_sibling, .prev_sibling, .all_siblings, .all_children, .parent_node_end, .parent_node_start => |role| return nodeSelect(p, pane, t, @field(modal.Normal.NodeWalk, @tagName(role))), - .delete => return edit.normalDelete(p.editor(), t, true), - .delete_noyank => return edit.normalDelete(p.editor(), t, false), - .change => return edit.normalChange(p.editor(), t), - .yank => return edit.normalYank(p.editor(), t), - .replace_with_yank => return edit.pasteRegister(p.editor(), t, .replace, a.count), - .paste_after => return edit.pasteRegister(p.editor(), t, .after, a.count), - .paste_before => return edit.pasteRegister(p.editor(), t, .before, a.count), - .switch_case => return edit.normalCase(p.editor(), t, .toggle), - .to_lowercase => return edit.normalCase(p.editor(), t, .lower), - .to_uppercase => return edit.normalCase(p.editor(), t, .upper), - .join_lines => return edit.normalJoin(p.editor(), t, false), - .join_select_space => return edit.normalJoin(p.editor(), t, true), - .rotate_contents_fwd => return edit.normalRotateContents(p.editor(), t, true, a.count), - .rotate_contents_back => return edit.normalRotateContents(p.editor(), t, false, a.count), - .align_selections => return edit.normalAlign(p.editor(), t), - .indent => return edit.normalIndent(p.editor(), t, a.count, true), - .unindent => return edit.normalIndent(p.editor(), t, a.count, false), - .comment_toggle => return edit.normalToggleComment(p.editor(), t), - .undo => return edit.undoStep(p.editor(), t, true), - .redo => return edit.undoStep(p.editor(), t, false), // Language shortcuts run the same builtins as tags and leader commands. .goto_definition => return exec.runBuiltin(p, .Def, v.active, "", null), .goto_references => return exec.runBuiltin(p, .Refs, v.active, "", null), @@ -1165,8 +1205,6 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! .goto_type_definition => return p.lspRequest(v.active, .type_definition, ""), .goto_implementation => return p.lspRequest(v.active, .implementation, ""), .format => return p.lspRequest(v.active, .format, ""), - .increment => return edit.normalAdjustNumber(p.editor(), t, @intCast(a.count)), - .decrement => return edit.normalAdjustNumber(p.editor(), t, -@as(i64, @intCast(a.count))), .leader => if (p.macro.replaying == 0) { v.prefix = .leader; v.leader_n = 0; @@ -1197,18 +1235,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! else if (t.what == .body and pane.file != null and pane.places.answersN(p, pane)) return pane.places.step(p, pane, a.role == .search_next, a.count, t.select) else - return searchStep(p, t, text, a.role == .search_next, a.count), - .search_selection, .search_selection_word => { - try searchSelection(p, t, text, a.role == .search_selection_word); - // The pattern is line 1 of this text's query pane, made or - // reused, the keyboard staying here: n and N step its places. - if (t.what == .body and pane.file != null and pane.query == null) { - const name = if (v.register != 0) v.register else '/'; - const pat = p.registers.value(name, 0) orelse return; - panes.Query.open(p, v.active, .text, pat, false); - pane.places.provenance = .search; - } - }, + return searchStep(p.editor(), t, text, a.role == .search_next, a.count), .goto_word => return startJump(p, pane, t), .macro_record => { const m = &p.macro; @@ -1247,8 +1274,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! for (0..a.count) |_| keyboard.replayKeys(p, keys[typed .. keys.len - 1]); keyboard.replayKeys(p, keys[keys.len - 1 ..]); }, - // prefix keys: what they begin is the command - .goto_prefix, .view_prefix, .next_prefix, .prev_prefix, .register_prefix, .view_prefix_sticky => {}, + else => unreachable, // the text's (textAction) } } @@ -1333,12 +1359,12 @@ test "flat text movement and selection replay need no scratch rows" { p.scratch = .init(denied.allocator()); pane.body.cur_row = 4094; - handleNormal(p, &pane.body, .{ .cp = 'l' }); + handleNormal(p.editor(), &pane.body, .{ .cp = 'l' }); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); - handleNormal(p, &pane.body, .{ .cp = 'j' }); + handleNormal(p.editor(), &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' }); + handleNormal(p.editor(), &pane.body, .{ .cp = 'h' }); try std.testing.expectEqual(@as(i32, 0), pane.body.cur_col); try executeNormalAction(p, &pane.body, .{ .role = .match_inside, .char = 'w' }); try std.testing.expectEqual(@as(i32, 2), pane.body.cur_col); @@ -1350,8 +1376,8 @@ test "flat text movement and selection replay need no scratch rows" { pane.body.nsel = 1; _ = pane.body.reserveSels(); pane.body.sels[0] = .{ .row = 3072, .col = 0, .arow = 3072, .acol = 0 }; - handleNormal(p, &pane.body, .{ .cp = 'l' }); - handleNormal(p, &pane.body, .{ .cp = 'j' }); + handleNormal(p.editor(), &pane.body, .{ .cp = 'l' }); + handleNormal(p.editor(), &pane.body, .{ .cp = 'j' }); try std.testing.expectEqual(@as(u16, 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); @@ -1454,19 +1480,19 @@ test "one cursor holds no room for other ranges; a second range makes it and one const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 }); defer p.deinit(); const pane = try p.setTestFile("alpha beta\nalpha beta\n"); - for ("wxe%;gg") |cp| handleNormal(p, &pane.body, .{ .cp = cp }); + for ("wxe%;gg") |cp| handleNormal(p.editor(), &pane.body, .{ .cp = cp }); try std.testing.expectEqual(@as(usize, 0), pane.body.sels.len); - handleNormal(p, &pane.body, .{ .cp = 'C' }); + handleNormal(p.editor(), &pane.body, .{ .cp = 'C' }); try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); try std.testing.expect(pane.body.sels.len > 0); - handleNormal(p, &pane.body, .{ .cp = 'l' }); // replayed at both, still two + handleNormal(p.editor(), &pane.body, .{ .cp = 'l' }); // replayed at both, still two try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); - handleNormal(p, &pane.body, .{ .cp = ',' }); + handleNormal(p.editor(), &pane.body, .{ .cp = ',' }); try std.testing.expectEqual(@as(usize, 0), pane.body.sels.len); - handleNormal(p, &pane.body, .{ .cp = 'C' }); - handleNormal(p, &pane.body, .{ .cp = ';' }); - handleNormal(p, &pane.body, .{ .cp = 'x' }); // x at both: still two lines - handleNormal(p, &pane.body, .{ .cp = '_', .alt = true }); // merged to one + handleNormal(p.editor(), &pane.body, .{ .cp = 'C' }); + handleNormal(p.editor(), &pane.body, .{ .cp = ';' }); + handleNormal(p.editor(), &pane.body, .{ .cp = 'x' }); // x at both: still two lines + handleNormal(p.editor(), &pane.body, .{ .cp = '_', .alt = true }); // merged to one try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); try std.testing.expectEqual(@as(usize, 0), pane.body.sels.len); } @@ -1477,9 +1503,9 @@ test "cursors that land on one place are one: a key typed there is typed once, a defer p.deinit(); const pane = try p.setTestFile("ab\ncd\n"); // A cursor below, then both up: the second lands on the first. - handleNormal(p, &pane.body, .{ .cp = 'C' }); + handleNormal(p.editor(), &pane.body, .{ .cp = 'C' }); try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); - handleNormal(p, &pane.body, .{ .cp = 'k' }); + handleNormal(p.editor(), &pane.body, .{ .cp = 'k' }); try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); p.update(.{ .key = .{ .cp = 'i', .text = "i" } }); p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); @@ -1492,10 +1518,10 @@ test "r and Delete take whole graphemes" { defer p.deinit(); const pane = try p.setTestFile("A" ++ "e\u{301}" ++ "👩🏽\u{200d}🚀" ++ "🇧🇷" ++ "界" ++ "Z\n"); // é, the astronaut and the flag: three graphemes, three 界 - for ("lv2lr") |c| handleNormal(p, &pane.body, .{ .cp = c }); - handleNormal(p, &pane.body, .{ .cp = '界' }); + for ("lv2lr") |c| handleNormal(p.editor(), &pane.body, .{ .cp = c }); + handleNormal(p.editor(), &pane.body, .{ .cp = '界' }); try std.testing.expectEqualStrings("A界界界界Z\n", pane.file.?.content); - for ("u0li") |c| handleNormal(p, &pane.body, .{ .cp = c }); + for ("u0li") |c| handleNormal(p.editor(), &pane.body, .{ .cp = c }); p.update(.{ .key = .{ .cp = Key.delete } }); try std.testing.expectEqualStrings("A" ++ "👩🏽\u{200d}🚀" ++ "🇧🇷" ++ "界" ++ "Z\n", pane.file.?.content); } -- cgit v1.3 From 56274a68fb7a418625f01d479ced9fbfc19383f2 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 06:01:44 -0300 Subject: lib: the text pane as a library, `pardes-editor` (docs/next-editor.md, R5): src/lib_editor.zig is an editor a program keeps as plain data (`Editor(capacity)`: a gap buffer for the text, Text's cursor fields by name, two byte rings of whole-text snapshots for undo and redo, registers as records; no pointer, no allocator), thawed into a Text and Registers in the allocator a call is handed, run through normal.zig and edit.zig as a pane's keys run, and frozen back, a key that does not fit refused whole (`key`, `run`, `selectRegex`, `setText`, `setRegister`; `Outcome` done, pending, unbound, action, refused), and `Syntax`, a parse derived from a grammar handed in; the seam is `pardes_config.lib`, true in the library's build alone: Text.pane is null at compile time there, a body's characters and undo are its own (flatSurface, editText, setEditTextSpan, pushUndo, undoStep), bodyFile and filePane are none, Esc and `*` do the text's part only and `+` is a plain register, and config.zig's check of the builtins' leader paths is the editor's; normal.textKey is the mode dispatch keys.zig and the library share, handleNormal hands back the parse and runAction runs an action across the ranges, and applySelRegex's search over the ranges is selectByRegex, which the library calls with a pattern; build.zig: `lib` in the options, mvzr's patch and uucode as functions (patchedMvzr, uucodeModule) the editor's module takes too, editorModule, and `library` exports `pardes-editor` to a package that asks (`.editor = true`: it fetches uucode, mvzr and vaxis, of which it compiles the grapheme width), so a pardes-syntax consumer fetches what it did; test/lib: a value typed into, copied elsewhere and its memory gone, types on equal to one never moved, undo past the ring and redo back, a text that does not fit refused with the value unchanged, an action handed back and a regex done by the caller, a language handed in parsed and coloured; core-test 811 of 950, shell-test 990 of 993, hxdiff 658 / parity 738 / hxgolf 124 with 0 mismatches, replicas pass, lib-test 8 of 8 --- build.zig | 278 ++++++++++++++++---------- src/Editor.zig | 17 +- src/Text.zig | 5 +- src/config.zig | 6 +- src/edit.zig | 43 ++-- src/keys.zig | 6 +- src/lib_editor.zig | 550 ++++++++++++++++++++++++++++++++++++++++++++++++++++ src/normal.zig | 104 ++++++---- test/lib/build.zig | 24 ++- test/lib/editor.zig | 144 ++++++++++++++ 10 files changed, 1010 insertions(+), 167 deletions(-) create mode 100644 src/lib_editor.zig create mode 100644 test/lib/editor.zig (limited to 'src/normal.zig') diff --git a/build.zig b/build.zig index afc4e4f3..6a9d4d9f 100644 --- a/build.zig +++ b/build.zig @@ -338,94 +338,7 @@ pub fn build(b: *std.Build) void { // each entry to matchPattern, which its backtracking recurses through, // spends a step, and with none left the match fails and says so // (src/regexp.zig). A bump that moves the anchor stops the build. - const mvzr_mod = mvzr: { - const dep = b.dependency("mvzr", .{ .target = target, .optimize = optimize }); - const src = configureRead(b, io, dep.builder.root, "src/mvzr.zig", 1 << 20) catch @panic("read mvzr"); - const anchor = "fn matchPattern(patt: []const RegOp, sets: []const CharSet, haystack: []const u8, i_in: usize) ?OpMatch {\n"; - const at = (std.mem.indexOf(u8, src, anchor) orelse @panic("mvzr's matchPattern changed: redo its step budget in build.zig")) + anchor.len; - const spend = - \\ if (steps_left == 0) { - \\ exhausted = true; - \\ return null; - \\ } - \\ steps_left -= 1; - \\ - ; - const budget = - \\ - \\/// pardes's patch (its build.zig): matchPattern entries left before a - \\/// match gives up, and whether one did. Set by the caller per search. - \\pub threadlocal var steps_left: u64 = std.math.maxInt(u64); - \\pub threadlocal var exhausted: bool = false; - \\ - ; - const budgeted = b.fmt("{s}{s}{s}{s}", .{ src[0..at], spend, src[at..], budget }); - // A group's greedy match never gave back to what follows the group: - // on `aab`, `(a+)ab` missed where `a+ab` matched. hasAlt counts the - // group's own `)` as an alternative, so every group with pattern - // after it takes matchGroup's alternatives branch, which tries each - // alternative's one (greedy) match and gives up. When the rest fails - // after it, try that alternative's shorter matches, longest first - // (docs/mvzr-group-backtrack.md is the report for upstream). - const group_anchor = - \\ const next_match = matchPattern(next_patt, sets, haystack, m1.i); - \\ if (next_match) |m2| { - \\ // Whole group matches, and we can use m2.j - \\ return m2; - \\ } else { // Try our next pattern, if any. - \\ - ; - const group_backoff = - \\ const next_match = matchPattern(next_patt, sets, haystack, m1.i); - \\ if (next_match) |m2| { - \\ // Whole group matches, and we can use m2.j - \\ return m2; - \\ } else { // Try our next pattern, if any. - \\ // pardes's patch (its build.zig): back the group off. - \\ var e = m1.i; - \\ while (e > i) { - \\ e -= 1; - \\ const shorter = matchAlt(remaining_patt, sets, haystack[0..e], i) orelse continue; - \\ if (shorter.i != e) continue; - \\ if (matchPattern(next_patt, sets, haystack, e)) |whole| return whole; - \\ } - \\ - ; - if (std.mem.count(u8, budgeted, group_anchor) != 1) @panic("mvzr's matchGroup changed: redo its group backtracking in build.zig"); - const backed = std.mem.replaceOwned(u8, b.allocator, budgeted, group_anchor, group_backoff) catch @panic("OOM"); - // `$` is refused anywhere but last, so `h$|zz` was a bad pattern - // while `zz|h$` was fine. An alternative or a group ends at `|` and - // `)`, and the matcher's `.end` ends the alternative it is in, so - // `$` may stand before either (docs/mvzr-group-backtrack.md). - const end_anchor = - \\ '$' => { - \\ if (i + 1 < in.len) { - \\ - ; - const end_before_alt = - \\ '$' => { - \\ // pardes's patch (its build.zig): `$` may end an alternative. - \\ if (i + 1 < in.len and in[i + 1] != '|' and in[i + 1] != ')') { - \\ - ; - if (std.mem.count(u8, backed, end_anchor) != 1) @panic("mvzr's parser changed: redo its `$` before `|` in build.zig"); - var patched = std.mem.replaceOwned(u8, b.allocator, backed, end_anchor, end_before_alt) catch @panic("OOM"); - // Zig 0.17 removed `**`; mvzr still has it (its PR #16 replaces it upstream). - // A class's range ending at `\xff` counted to 256 in a u8, an - // overflow (a panic in a safe build, a runaway loop in a fast one): - // `[\x80-\xff]` in any search took the editor down. - for ([_][3][]const u8{ - .{ "for (c1..c2 + 1) |c_range|", "for (c1..@as(usize, c2) + 1) |c_range|", "1" }, - .{ "[1]RegOp{.{ .unused = {} }} ** ops", "@splat(.{ .unused = {} })", "1" }, - .{ "[1]CharSet{.{ .low = 0, .hi = 0 }} ** char_sets", "@splat(.{ .low = 0, .hi = 0 })", "1" }, - .{ "\"a\" ** 2048", "&@as([2048]u8, @splat('a'))", "2" }, - .{ "\"12345,\" ** 255", "std.mem.asBytes(&@as([255][6]u8, @splat(\"12345,\".*)))", "1" }, - }) |edit| { - if (std.mem.count(u8, patched, edit[0]) != std.fmt.parseInt(usize, edit[2], 10) catch unreachable) std.debug.panic("mvzr changed at `{s}`: redo its `**` patch in build.zig", .{edit[0]}); - patched = std.mem.replaceOwned(u8, b.allocator, patched, edit[0], edit[1]) catch @panic("OOM"); - } - break :mvzr b.createModule(.{ .root_source_file = b.addWriteFiles().add("mvzr.zig", patched), .target = target, .optimize = optimize }); - }; + const mvzr_mod = patchedMvzr(b, io, b.dependency("mvzr", .{ .target = target, .optimize = optimize }), target, optimize); // The C heap every C library with an allocator hook is handed: the core's // tree-sitter and fonts, and pdf.zig's MuPDF, which is a module of its own. @@ -540,18 +453,7 @@ pub fn build(b: *std.Build) void { const no_pdf: ?*std.Build.Step = if (pdf_addon == null) &b.addFail("this step needs the pdf addon, over MuPDF: add -Dpdf (it is fetched once, and on from then)").step else null; if (no_pdf) |s| for ([_]*std.Build.Step{ mupdf_check, pdf_pointer_bench_step, pdf_scroll_bench_step }) |step| step.dependOn(s); - const uucode_config = b.path("uucode_config.zig"); - const uucode_tables = b.dependency("uucode", .{ - .target = target, - .optimize = optimize, - .build_config_path = uucode_config, - }).namedLazyPath("tables.zig"); - const uucode_mod = b.dependency("uucode", .{ - .target = target, - .optimize = optimize, - .build_config_path = uucode_config, - .tables_path = uucode_tables, - }).module("uucode"); + const uucode_mod = uucodeModule(b, target, optimize).?; const vaxis_dep = b.dependency("vaxis", .{ .target = target, @@ -2028,6 +1930,9 @@ const ShellConfig = struct { /// `Build` word's, stamped with the commit (see `stamp_commit`). change: ?[]const u8, built: ?[]const u8, + /// The library's editor (src/lib_editor.zig): a text with no pane, so + /// the core is not compiled (src/Editor.zig). + lib: bool = false, }; fn shellOptions(b: *std.Build, cfg: ShellConfig, platform: Platform) *std.Build.Step.Options { @@ -2047,6 +1952,7 @@ fn shellOptions(b: *std.Build, cfg: ShellConfig, platform: Platform) *std.Build. o.addOption(?[]const u8, "change", cfg.change); o.addOption(?[]const u8, "built", cfg.built); o.addOption([]const u8, "deps", deps_text); + o.addOption(bool, "lib", cfg.lib); return o; } @@ -2214,13 +2120,183 @@ fn library(b: *std.Build) void { .built = null, }, .tui)); const ts = treeSitter(b, io, target, if (optimize == .debug) .fast else optimize, tree_sitter_grammars); + const themes = generatedThemes(b, io, target, optimize); wireCore(mod, .{ - .themes = generatedThemes(b, io, target, optimize), + .themes = themes, .tree_sitter = ts.mod, .ts_libs = ts.libs.items, .ts_queries = ts.queries, .c_heap = b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("src/c_heap.zig") }), }); + // The editor, `pardes-editor`, to a package that asks for it: uucode, + // mvzr and vaxis (with what its build names) are fetched then and only + // then. Of vaxis it takes the grapheme width, which uucode alone feeds. + if (!(b.option(bool, "editor", "also export `pardes-editor`, the text pane as a library (fetches uucode, mvzr and vaxis)") orelse false)) return; + const uucode = uucodeModule(b, target, optimize) orelse return; + const mvzr = patchedMvzr(b, io, b.lazyDependency("mvzr", .{ .target = target, .optimize = optimize }) orelse return, target, optimize); + const vaxis_dep = b.lazyDependency("vaxis", .{ .target = target, .optimize = optimize, .external_uucode = true }) orelse return; + const width = b.addWriteFiles(); + _ = width.addCopyFile(vaxis_dep.path("src/gwidth.zig"), "gwidth.zig"); + const vaxis = b.createModule(.{ + .target = target, + .optimize = optimize, + .root_source_file = width.add("vaxis.zig", "pub const gwidth = @import(\"gwidth.zig\");\n"), + .imports = &.{.{ .name = "uucode", .module = uucode }}, + }); + _ = editorModule(b, "pardes-editor", target, optimize, .{ + .tree_sitter_grammars = tree_sitter_grammars, + .tracy = false, + .workspace_tag = null, + .prebuilt_shaders = false, + .embed_sources = false, + .commit = null, + .change = null, + .built = null, + }, .{ .themes = themes, .tree_sitter = ts.mod, .ts_libs = ts.libs.items, .ts_queries = ts.queries, .uucode = uucode, .mvzr = mvzr, .vaxis = vaxis }); +} + +fn patchedMvzr(b: *std.Build, io: std.Io, dep: *std.Build.Dependency, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) *std.Build.Module { + const src = configureRead(b, io, dep.builder.root, "src/mvzr.zig", 1 << 20) catch @panic("read mvzr"); + const anchor = "fn matchPattern(patt: []const RegOp, sets: []const CharSet, haystack: []const u8, i_in: usize) ?OpMatch {\n"; + const at = (std.mem.indexOf(u8, src, anchor) orelse @panic("mvzr's matchPattern changed: redo its step budget in build.zig")) + anchor.len; + const spend = + \\ if (steps_left == 0) { + \\ exhausted = true; + \\ return null; + \\ } + \\ steps_left -= 1; + \\ + ; + const budget = + \\ + \\/// pardes's patch (its build.zig): matchPattern entries left before a + \\/// match gives up, and whether one did. Set by the caller per search. + \\pub threadlocal var steps_left: u64 = std.math.maxInt(u64); + \\pub threadlocal var exhausted: bool = false; + \\ + ; + const budgeted = b.fmt("{s}{s}{s}{s}", .{ src[0..at], spend, src[at..], budget }); + // A group's greedy match never gave back to what follows the group: + // on `aab`, `(a+)ab` missed where `a+ab` matched. hasAlt counts the + // group's own `)` as an alternative, so every group with pattern + // after it takes matchGroup's alternatives branch, which tries each + // alternative's one (greedy) match and gives up. When the rest fails + // after it, try that alternative's shorter matches, longest first + // (docs/mvzr-group-backtrack.md is the report for upstream). + const group_anchor = + \\ const next_match = matchPattern(next_patt, sets, haystack, m1.i); + \\ if (next_match) |m2| { + \\ // Whole group matches, and we can use m2.j + \\ return m2; + \\ } else { // Try our next pattern, if any. + \\ + ; + const group_backoff = + \\ const next_match = matchPattern(next_patt, sets, haystack, m1.i); + \\ if (next_match) |m2| { + \\ // Whole group matches, and we can use m2.j + \\ return m2; + \\ } else { // Try our next pattern, if any. + \\ // pardes's patch (its build.zig): back the group off. + \\ var e = m1.i; + \\ while (e > i) { + \\ e -= 1; + \\ const shorter = matchAlt(remaining_patt, sets, haystack[0..e], i) orelse continue; + \\ if (shorter.i != e) continue; + \\ if (matchPattern(next_patt, sets, haystack, e)) |whole| return whole; + \\ } + \\ + ; + if (std.mem.count(u8, budgeted, group_anchor) != 1) @panic("mvzr's matchGroup changed: redo its group backtracking in build.zig"); + const backed = std.mem.replaceOwned(u8, b.allocator, budgeted, group_anchor, group_backoff) catch @panic("OOM"); + // `$` is refused anywhere but last, so `h$|zz` was a bad pattern + // while `zz|h$` was fine. An alternative or a group ends at `|` and + // `)`, and the matcher's `.end` ends the alternative it is in, so + // `$` may stand before either (docs/mvzr-group-backtrack.md). + const end_anchor = + \\ '$' => { + \\ if (i + 1 < in.len) { + \\ + ; + const end_before_alt = + \\ '$' => { + \\ // pardes's patch (its build.zig): `$` may end an alternative. + \\ if (i + 1 < in.len and in[i + 1] != '|' and in[i + 1] != ')') { + \\ + ; + if (std.mem.count(u8, backed, end_anchor) != 1) @panic("mvzr's parser changed: redo its `$` before `|` in build.zig"); + var patched = std.mem.replaceOwned(u8, b.allocator, backed, end_anchor, end_before_alt) catch @panic("OOM"); + // Zig 0.17 removed `**`; mvzr still has it (its PR #16 replaces it upstream). + // A class's range ending at `\xff` counted to 256 in a u8, an + // overflow (a panic in a safe build, a runaway loop in a fast one): + // `[\x80-\xff]` in any search took the editor down. + for ([_][3][]const u8{ + .{ "for (c1..c2 + 1) |c_range|", "for (c1..@as(usize, c2) + 1) |c_range|", "1" }, + .{ "[1]RegOp{.{ .unused = {} }} ** ops", "@splat(.{ .unused = {} })", "1" }, + .{ "[1]CharSet{.{ .low = 0, .hi = 0 }} ** char_sets", "@splat(.{ .low = 0, .hi = 0 })", "1" }, + .{ "\"a\" ** 2048", "&@as([2048]u8, @splat('a'))", "2" }, + .{ "\"12345,\" ** 255", "std.mem.asBytes(&@as([255][6]u8, @splat(\"12345,\".*)))", "1" }, + }) |edit| { + if (std.mem.count(u8, patched, edit[0]) != std.fmt.parseInt(usize, edit[2], 10) catch unreachable) std.debug.panic("mvzr changed at `{s}`: redo its `**` patch in build.zig", .{edit[0]}); + patched = std.mem.replaceOwned(u8, b.allocator, patched, edit[0], edit[1]) catch @panic("OOM"); + } + return b.createModule(.{ .root_source_file = b.addWriteFiles().add("mvzr.zig", patched), .target = target, .optimize = optimize }); +} + +/// uucode with pardes's configuration (uucode_config.zig), which ghostty +/// and vaxis share; null while it is still to be fetched. +fn uucodeModule(b: *std.Build, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode) ?*std.Build.Module { + const uucode_config = b.path("uucode_config.zig"); + const uucode_tables = (b.lazyDependency("uucode", .{ + .target = target, + .optimize = optimize, + .build_config_path = uucode_config, + }) orelse return null).namedLazyPath("tables.zig"); + return (b.lazyDependency("uucode", .{ + .target = target, + .optimize = optimize, + .build_config_path = uucode_config, + .tables_path = uucode_tables, + }) orelse return null).module("uucode"); +} + +/// The editor as a library (src/lib_editor.zig, docs/next-editor.md): the +/// text pane's own code built with `lib`, so no pane and no core, over +/// tree-sitter, uucode and mvzr, with pardes-syntax in it as `.syntax`. +/// `library` exports it to a package that asks; hxdiff runs its cases on it. +fn editorModule(b: *std.Build, name: ?[]const u8, target: std.Build.ResolvedTarget, optimize: std.builtin.OptimizeMode, cfg: ShellConfig, d: struct { + themes: *std.Build.Module, + tree_sitter: ?*std.Build.Module, + ts_libs: []const *std.Build.Step.Compile, + ts_queries: ?*std.Build.Step.Options, + uucode: *std.Build.Module, + mvzr: *std.Build.Module, + /// vaxis's, or a module of its grapheme width alone (`library`): a + /// cell's width for j and k's goal column. + vaxis: *std.Build.Module, +}) *std.Build.Module { + const options: std.Build.Module.CreateOptions = .{ + .target = target, + .optimize = optimize, + .root_source_file = b.path("src/lib_editor.zig"), + .link_libc = true, + }; + const mod = if (name) |n| b.addModule(n, options) else b.createModule(options); + var lib_cfg = cfg; + lib_cfg.lib = true; + mod.addOptions("pardes_config", shellOptions(b, lib_cfg, .tui)); + wireCore(mod, .{ + .plain = b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("src/plain/plain.zig") }), + .themes = d.themes, + .tree_sitter = d.tree_sitter, + .ts_libs = d.ts_libs, + .ts_queries = d.ts_queries, + .mvzr = d.mvzr, + .uucode = d.uucode, + .vaxis = d.vaxis, + .c_heap = b.createModule(.{ .target = target, .optimize = optimize, .root_source_file = b.path("src/c_heap.zig") }), + }); + return mod; } fn wireCore(m: *std.Build.Module, d: struct { diff --git a/src/Editor.zig b/src/Editor.zig index 559ea196..014d1923 100644 --- a/src/Editor.zig +++ b/src/Editor.zig @@ -6,7 +6,12 @@ //! sketch stores (src/lib_editor.zig). Nothing here is kept between calls. const std = @import("std"); const Registers = @import("Registers.zig"); -const Pardes = @import("Core.zig"); + +/// The library's build (build.zig `library`): a text with no pane and no +/// core, its characters its own. Where an edit reaches a pane it branches +/// on this at compile time, so the library never compiles the core. +pub const lib = @import("pardes_config").lib; +const Pardes = if (lib) void else @import("Core.zig"); const Editor = @This(); @@ -30,7 +35,10 @@ multi_count: *usize, /// edit.retireEditText. retired_edit: *?[]u8, /// The core the text's pane is in: what an edit reaches past its text with. -p: *Pardes, +p: if (lib) void else *Pardes, +/// The library's: an edit failed (its allocator ran out) and the key is +/// refused. +failed: if (lib) *bool else void, pub fn of(p: *Pardes) Editor { return .{ @@ -44,11 +52,16 @@ pub fn of(p: *Pardes) Editor { .multi_count = &p.multi_count, .retired_edit = &p.retired_edit, .p = p, + .failed = {}, }; } /// An edit that failed, said on the message row of the pane the keyboard /// is in. pub fn reportError(e: Editor, err: anyerror) void { + if (comptime lib) { + e.failed.* = true; + return; + } e.p.reportError(e.p.view().active, "edit", err); } diff --git a/src/Text.zig b/src/Text.zig index 271269ab..fd08bb71 100644 --- a/src/Text.zig +++ b/src/Text.zig @@ -110,7 +110,10 @@ refused: bool = false, /// The window this text belongs to (acme's t->w). A column's or the /// workspace's tag belongs to none, and the optional makes every caller /// say what it does then. -pub fn pane(t: *Text) ?*Pane { +pub inline fn pane(t: *Text) ?*Pane { + // the library's text has none (lib_editor.zig): known at compile time, + // so what an edit does with a pane is not compiled there + if (comptime @import("pardes_config").lib) return null; return switch (t.what) { .body => @alignCast(@fieldParentPtr("body", t)), .tag => @alignCast(@fieldParentPtr("tag", t)), diff --git a/src/config.zig b/src/config.zig index c7078d8e..43a68dd3 100644 --- a/src/config.zig +++ b/src/config.zig @@ -4,7 +4,7 @@ const layout = @import("layout.zig"); const limits = @import("memory.zig").limits; const pardes = @import("pardes.zig"); const builtins = @import("builtins.zig"); -const Key = pardes.Key; +const Key = @import("plain").Key; const Mouse = pardes.Mouse; const Builtin = builtins.registry.Builtin(); @@ -38,8 +38,8 @@ pub const leader_args = [_]struct { path: []const u8, cmd: Builtin, arg: []const comptime { @setEvalBranchQuota(20_000); // A path here is a leaf: no builtin's path is it or runs past it, and - // none of it is a builtin's whole path. - for (leader_args) |la| for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |path| { + // none of it is a builtin's whole path. The library has no builtins. + if (!@import("pardes_config").lib) for (leader_args) |la| for (std.enums.values(Builtin)) |b| if (leader_path.get(b)) |path| { if (std.mem.startsWith(u8, path, la.path) or std.mem.startsWith(u8, la.path, path)) @compileError("leader_args path collides with " ++ @tagName(b) ++ ": " ++ la.path); }; diff --git a/src/edit.zig b/src/edit.zig index 4b0e59fe..4a48cfd4 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -17,19 +17,19 @@ const syntax = @import("syntax.zig"); const indents = @import("indent.zig"); const platform = pardes.platform; const Pane = panes.Pane; -const Text = panes.Text; +const Text = @import("Text.zig"); const Layer = @import("Layer.zig"); const TagHit = pardes.TagHit; const BOX_H = pardes.BOX_H; const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; const Mouse = pardes.Mouse; -const Key = pardes.Key; -const hit = pardes.hit; +const Key = @import("plain").Key; +const hit = @import("Event.zig").hit; const sel_slot = pardes.sel_slot; const Effect = pardes.Effect; const Pardes = pardes.Pardes; -const Registers = pardes.Registers; -const Editor = pardes.Editor; +const Registers = @import("Registers.zig"); +const Editor = @import("Editor.zig"); /// An edit's failure, memory or a terminal's rows not read, said by its key. pub const Error = error{ OutOfMemory, WriteFailed, UnknownPoint }; @@ -45,7 +45,8 @@ pub fn setYank(e: Editor, text: []const u8) error{OutOfMemory}!void { else => {}, } try e.registers.put(e.gpa, name, text, e.multi_index.*, e.multi_count.*, e.multi_first.*); - if (name == '+' and e.multi_first.*) e.p.emit(.{ .set_clipboard = {} }); + // the library's `+` is a register its caller fills and reads + if (comptime !Editor.lib) if (name == '+' and e.multi_first.*) e.p.emit(.{ .set_clipboard = {} }); } /// Value `i` of register `name` as the command at range `i` reads it, the @@ -526,11 +527,12 @@ pub fn terminalLines(p: *Pardes, pane: *Pane) ![]const []const u8 { pub fn flatSurface(e: Editor, t: *Text) Error![]const u8 { switch (t.what) { - .body => {}, + // the library's text has no pane: its characters are its own + .body => if (comptime Editor.lib) return t.own orelse "", // the tag as it is shown: the keyboard reaches its prefix too .tag => return if (t.pane()) |pane| try tagline.tagText(e.p, e.scratch, pane) else "", .input => return t.own orelse "", - .column, .workspace => return t.own orelse tagline.headerDefault(e.p, t.what), + .column, .workspace => return t.own orelse if (comptime Editor.lib) "" else tagline.headerDefault(e.p, t.what), } const pane = t.pane() orelse return ""; if (pane.file) |f| return f.content; @@ -574,7 +576,7 @@ fn editText(e: Editor, t: *Text, lo: i32, hi: i32, col: i32) Error!?panes.EditTe } if (t.what != .body and t.what != .input and t.own == null) t.own = try e.gpa.dupe(u8, try flatSurface(e, t)); - if (t.what != .body) return .{ .text = t.own orelse &.{}, .row0 = 0 }; + if (t.what != .body or comptime Editor.lib) return .{ .text = t.own orelse &.{}, .row0 = 0 }; const pane = t.pane() orelse return null; if (pane.file) |f| return .{ .text = f.content, .row0 = 0 }; if (pane.addon != null) return null; @@ -692,6 +694,16 @@ fn setEditTextSpan(e: Editor, t: *Text, new: []u8, known_end: ?modal.Cursor, spa t.own = new; return; } + if (comptime Editor.lib) { + // the library's text, its own, where the edit ended found as a + // file's is (below) + const found = span orelse panes.File.spanOf(t.own orelse "", new); + const end = known_end orelse modal.positionAt(new, new.len - found.tail); + t.last_edit = .{ .row = @intCast(end.row), .col = @intCast(end.col) }; + if (t.own) |old| e.gpa.free(old); + t.own = new; + return; + } const pane = t.pane() orelse return retireEditText(e, new); // A live query pane's rows are its line 1's (Query.zig): an edit there // is refused, as a tag's prefix refuses one, and one from line 1 into @@ -733,7 +745,8 @@ fn setEditTextSpan(e: Editor, t: *Text, new: []u8, known_end: ?modal.Cursor, spa /// The file whose text `t` edits in place (File.replace), the bytes it puts /// in and no copy of the text: a file's body, not a live query's (whose /// edits `setEditTextSpan` cuts to its line 1). -fn bodyFile(t: *Text) ?*panes.File.State { +inline fn bodyFile(t: *Text) ?*panes.File.State { + if (comptime Editor.lib) return null; if (t.what != .body) return null; const pane = t.pane() orelse return null; const f = if (pane.file) |*file| file else return null; @@ -1814,7 +1827,7 @@ pub fn normalToggleComment(e: Editor, t: *Text) Error!void { } next = @max(next, end); } - const file = if (t.what != .body) null else if (t.pane()) |pane| pane.file else null; + const file = if (Editor.lib or t.what != .body) null else if (t.pane()) |pane| pane.file else null; const ext = if (file) |f| std.Io.Dir.path.extension(f.path) else ""; var token: []const u8 = config.comment_token_default; lang: for (config.comment_tokens) |row| { @@ -2049,8 +2062,11 @@ pub fn pushUndo(e: Editor, t: *Text) error{OutOfMemory}!void { // one keystroke, one undo step — even when it edited at ten cursors. if (!e.multi_first.*) return; switch (t.what) { - // A B1 chord took its one undo point when it began (mouse.zig). - .body => if (e.p.view().chord_hold) return, + // A B1 chord took its one undo point when it began (mouse.zig); + // the library's text keeps its own undo, as a tag does. + .body => if (comptime Editor.lib) + return t.remember(e.gpa, if (t.own) |own| .{ .text = own } else null) + else if (e.p.view().chord_hold) return, .tag, .column, .workspace => return t.remember(e.gpa, if (t.own) |own| .{ .text = own } else null), // a prompt's answer is typed once and gone; it keeps no history .input => return, @@ -2063,6 +2079,7 @@ pub fn pushUndo(e: Editor, t: *Text) error{OutOfMemory}!void { /// Undo (back) or redo one step of the text's history: its file's, its /// terminal overlay's, or a tag's or header's own. pub fn undoStep(e: Editor, t: *Text, back: bool) error{OutOfMemory}!void { + if (comptime Editor.lib) return stepOwn(e, t, back); if (t.what == .tag or t.what == .column or t.what == .workspace) return stepOwn(e, t, back); if (t.what != .body) return; const pane = t.pane() orelse return; diff --git a/src/keys.zig b/src/keys.zig index 0277128b..05148fed 100644 --- a/src/keys.zig +++ b/src/keys.zig @@ -442,11 +442,7 @@ pub fn handleKey(p: *Pardes, key: Key) void { }; const was = t.mode; switch (t.mode) { - .normal => normal.handleNormal(p.editor(), t, key), - .insert => if (hit(key, config.escape) and !t.reg_wait) - edit.exitInsert(p.editor(), t) - else - edit.handleInsert(p.editor(), t, key), + .normal, .insert => _ = normal.textKey(p.editor(), t, key), .tty => forwardKey(p, p.view().active, key), } // `.`'s log: the keys of the normal command that entered insert diff --git a/src/lib_editor.zig b/src/lib_editor.zig new file mode 100644 index 00000000..5430285a --- /dev/null +++ b/src/lib_editor.zig @@ -0,0 +1,550 @@ +//! pardes's text pane as a library: the `pardes-editor` module a package +//! that depends on pardes imports (build.zig's `library` with `.editor = +//! true`, docs/next-editor.md). In-memory editing with helix's keys: no +//! files, commands, builtins, prompts or views, which come back to the +//! caller as an `action`. Nothing is copied here: a key runs the editor's +//! own normal.zig and edit.zig, built with `pardes_config.lib`, where a +//! text has no pane and its characters are its own. +//! +//! The editor is a value of plain data (`Editor(capacity)`): no pointer, +//! no allocator, every capacity in its type, so it can be kept where a +//! program keeps its state, copied anywhere, and outlive the code that +//! made it. Each call is handed an allocator it may use and drop (a +//! frame's arena): the value is thawed into the structures pardes edits, +//! the key runs, and they are frozen back. +const std = @import("std"); +const modal = @import("modal.zig"); +const Text = @import("Text.zig"); +const Registers = @import("Registers.zig"); +const Context = @import("Editor.zig"); +const normal = @import("normal.zig"); +const edit = @import("edit.zig"); +const syntax_impl = @import("syntax.zig"); + +/// pardes's syntax (src/lib_syntax.zig): its grammars, highlighting, +/// themes and line arithmetic. A file belongs to one module, so a package +/// imports this module or `pardes-syntax`, not both. +pub const syntax = @import("lib_syntax.zig"); +/// A key read: its codepoint or one of the specials (`Key.enter`, +/// `Key.left`...), the text it types, its modifiers. +pub const Key = @import("plain").Key; +/// A range as helix has it: byte offsets between characters. +pub const Selection = modal.Selection; +pub const Role = modal.Normal.Role; +/// What a normal-mode key means: a role, its count and the character it +/// takes. Built by the caller too, for `run`. +pub const Action = modal.Normal.Action; +pub const RegexMode = modal.Normal.RegexMode; +pub const max_selections = Text.max_selections; +/// A grammar handed in at run time (syntax.zig): its tree-sitter +/// language and its queries' sources, told by `ext`. +pub const Language = syntax_impl.Language; + +pub const Capacity = struct { + /// Bytes of text. + text: u32 = 64 * 1024, + /// Bytes of undo, and as many again of redo: whole-text snapshots, the + /// oldest dropped to make room. At least `text`, so every text that + /// fits is a snapshot that fits. + undo: u32 = 256 * 1024, + /// Bytes of every register's values together. + registers: u32 = 16 * 1024, + /// Ranges, the primary among them. + selections: u16 = 256, +}; + +/// Why a key was not taken: what it made does not fit the value's +/// capacities, or the allocator handed in ran out. The value is as it was +/// before the key. +pub const Refusal = enum { text_full, registers_full, selections_full, out_of_memory }; + +pub const Outcome = union(enum) { + /// The key did what helix does with it (a motion, an edit, a mode). + done, + /// A count, a prefix (`g`, `m`, `"x`) or a pair's character is awaited: + /// `pending()` says which. + pending, + /// Helix binds nothing to it: the caller's to give a meaning. + unbound: Key, + /// Bound, but not the text's to do (a view, `:`, `/`, `s`, LSP, a + /// macro): the caller's. The text and its ranges are as they were. + action: Action, + refused: Refusal, +}; + +pub const Mode = enum { normal, insert, select }; + +/// Text's fields that say where the cursor and the ranges are and what is +/// pending, kept here under their names: thaw and freeze copy each. +pub const Cursor = struct { + mode: Text.Mode = .normal, + cur_pinned: bool = false, + cur_row: i32 = 0, + cur_col: i32 = 0, + vsel: Text.CharSel = .{}, + nsel: u16 = 0, + select: bool = false, + sticky_col: i32 = -1, + restore_cursor: bool = false, + last_edit: @FieldType(Text, "last_edit") = null, + reg_wait: bool = false, + normal: modal.Normal.State = .{}, + find_op: ?modal.Normal.Find = null, + find_ch: u21 = 0, +}; + +/// Records of whole bytes in a ring, each `[len][payload][len]`, the newest +/// at `head`: pushing over a full ring drops the oldest. A record keeps its +/// place while it is held, so a push changes the pages it is written to and +/// no others. +pub fn Ring(comptime size: u32) type { + return struct { + const R = @This(); + bytes: [size]u8 = @splat(0), + head: u32 = 0, + used: u32 = 0, + count: u32 = 0, + + fn copyOut(r: *const R, at: u32, out: []u8) void { + const first = @min(out.len, size - at); + @memcpy(out[0..first], r.bytes[at..][0..first]); + @memcpy(out[first..], r.bytes[0 .. out.len - first]); + } + + fn copyIn(r: *R, at: u32, in: []const u8) void { + const first: u32 = @intCast(@min(in.len, size - at)); + @memcpy(r.bytes[at..][0..first], in[0..first]); + @memcpy(r.bytes[0 .. in.len - first], in[first..]); + } + + fn lenAt(r: *const R, at: u32) u32 { + var b: [4]u8 = undefined; + r.copyOut(at, &b); + return std.mem.readInt(u32, &b, .little); + } + + /// Where the record `skip` records below the newest ends. + fn endOf(r: *const R, skip: u32) u32 { + var at = r.head; + for (0..skip) |_| at = (at + size - (r.lenAt((at + size - 4) % size) + 8)) % size; + return at; + } + + /// The payload of the record `skip` below the newest, copied out. + pub fn get(r: *const R, a: std.mem.Allocator, skip: u32) ![]u8 { + const end = r.endOf(skip); + const len = r.lenAt((end + size - 4) % size); + const out = try a.alloc(u8, len); + r.copyOut((end + size - 4 - len) % size, out); + return out; + } + + pub fn pop(r: *R) void { + if (r.count == 0) return; + const len = r.lenAt((r.head + size - 4) % size); + r.head = (r.head + size - (len + 8)) % size; + r.used -= len + 8; + r.count -= 1; + } + + /// False when the payload alone is more than the ring holds. + pub fn fits(len: usize) bool { + return len + 8 <= size; + } + + pub fn push(r: *R, payload: []const u8) void { + std.debug.assert(fits(payload.len)); + const len: u32 = @intCast(payload.len); + while (r.used + len + 8 > size) { + const tail = (r.head + size - r.used) % size; + r.used -= r.lenAt(tail) + 8; + r.count -= 1; + } + var n: [4]u8 = undefined; + std.mem.writeInt(u32, &n, len, .little); + r.copyIn(r.head, &n); + r.copyIn((r.head + 4) % size, payload); + r.copyIn((r.head + 4 + len) % size, &n); + r.head = (r.head + len + 8) % size; + r.used += len + 8; + r.count += 1; + } + + pub fn clear(r: *R) void { + r.used = 0; + r.count = 0; + } + }; +} + +/// A snapshot's place in a ring record, before its text. +const SnapMeta = extern struct { cur_row: i32, cur_col: i32, vrow: i32, vcol: i32, active: u8, explicit: u8, has_text: u8, _: u8 = 0 }; + +fn snapBytes(a: std.mem.Allocator, s: Text.Snapshot) ![]u8 { + const text = if (s.ovl) |o| o.text else ""; + const out = try a.alloc(u8, @sizeOf(SnapMeta) + text.len); + const meta: SnapMeta = .{ + .cur_row = s.cur_row, + .cur_col = s.cur_col, + .vrow = s.vsel.row, + .vcol = s.vsel.col, + .active = @intFromBool(s.vsel.active), + .explicit = @intFromBool(s.vsel.explicit), + .has_text = @intFromBool(s.ovl != null), + }; + @memcpy(out[0..@sizeOf(SnapMeta)], std.mem.asBytes(&meta)); + @memcpy(out[@sizeOf(SnapMeta)..], text); + return out; +} + +fn snapOf(bytes: []u8) Text.Snapshot { + var meta: SnapMeta = undefined; + @memcpy(std.mem.asBytes(&meta), bytes[0..@sizeOf(SnapMeta)]); + return .{ + .ovl = if (meta.has_text != 0) .{ .text = bytes[@sizeOf(SnapMeta)..] } else null, + .cur_row = meta.cur_row, + .cur_col = meta.cur_col, + .vsel = .{ .active = meta.active != 0, .row = meta.vrow, .col = meta.vcol, .explicit = meta.explicit != 0 }, + }; +} + +/// What a key runs on: the value thawed (`Text`, `Registers`), the replay's +/// state, and what was thawed from the rings, to tell what the key did to +/// them. +const Live = struct { + text: Text, + registers: Registers = .{}, + register: u21 = 0, + multi_first: bool = true, + multi_stop: bool = false, + multi_index: usize = 0, + multi_count: usize = 1, + retired_edit: ?[]u8 = null, + failed: bool = false, + undo_thawed: usize = 0, + redo_thawed: usize = 0, + /// The ring records thawed, by their text's address: a snapshot still + /// in a history after the key is one of them when its text is. + undo_from: [1]?[*]const u8 = @splat(null), + redo_from: [2]?[*]const u8 = @splat(null), + + fn context(l: *Live, a: std.mem.Allocator) Context { + return .{ + .gpa = a, + .scratch = a, + .registers = &l.registers, + .register = &l.register, + .multi_first = &l.multi_first, + .multi_stop = &l.multi_stop, + .multi_index = &l.multi_index, + .multi_count = &l.multi_count, + .retired_edit = &l.retired_edit, + .p = {}, + .failed = &l.failed, + }; + } +}; + +fn textPtr(s: Text.Snapshot) ?[*]const u8 { + return if (s.ovl) |o| o.text.ptr else null; +} + +pub fn Editor(comptime cap: Capacity) type { + if (cap.undo < cap.text + @sizeOf(SnapMeta) + 8) @compileError("pardes-editor: an undo ring holds at least one whole text"); + if (cap.selections < 1 or cap.selections > Text.max_selections) @compileError("pardes-editor: 1 to max_selections ranges"); + return struct { + const Self = @This(); + pub const capacity = cap; + + /// The text as a gap buffer: `front` bytes at its start and `back` + /// at its end, the gap where the last edit was, so that typing + /// changes the page it types into and not every page after it. + text: [cap.text]u8 = @splat(0), + front: u32 = 0, + back: u32 = 0, + /// One more for each key that changed the text: what a parse of it + /// (`Syntax`) is kept against. + revision: u32 = 0, + cursor: Cursor = .{}, + /// The ranges beside the primary, `cursor.nsel` of them. + sels: [cap.selections - 1]Text.SelRange = @splat(.{ .row = 0, .col = 0, .arow = 0, .acol = 0 }), + undo: Ring(cap.undo) = .{}, + redo: Ring(cap.undo) = .{}, + /// Every register, `[name][count]` then each value `[len][bytes]`. + registers: [cap.registers]u8 = @splat(0), + registers_len: u32 = 0, + last_search: u21 = '/', + + pub fn len(ed: *const Self) usize { + return ed.front + ed.back; + } + + /// The text, copied whole into `out` (at least `len()` bytes). + pub fn read(ed: *const Self, out: []u8) []u8 { + @memcpy(out[0..ed.front], ed.text[0..ed.front]); + @memcpy(out[ed.front..][0..ed.back], ed.text[cap.text - ed.back ..]); + return out[0..ed.len()]; + } + + /// The text in `a`'s memory. + pub fn bytes(ed: *const Self, a: std.mem.Allocator) error{OutOfMemory}![]u8 { + return ed.read(try a.alloc(u8, ed.len())); + } + + /// A new text, nothing to undo, the cursor at its start, the + /// registers kept. + pub fn load(ed: *Self, text: []const u8) error{TextFull}!void { + if (text.len > cap.text) return error.TextFull; + @memcpy(ed.text[0..text.len], text); + ed.front = @intCast(text.len); + ed.back = 0; + ed.revision +%= 1; + ed.cursor = .{}; + ed.undo.clear(); + ed.redo.clear(); + } + + pub fn mode(ed: *const Self) Mode { + return switch (ed.cursor.mode) { + .insert => .insert, + else => if (ed.cursor.select) .select else .normal, + }; + } + + /// What the next key completes, null when nothing is awaited. + pub fn pending(ed: *const Self) ?Role { + return ed.cursor.normal.match_sub orelse ed.cursor.normal.prefix; + } + + /// The ranges in document order and which is the primary. + pub fn ranges(ed: *const Self, a: std.mem.Allocator, out: *[max_selections]Selection) error{OutOfMemory}!struct { n: usize, primary: usize } { + const live = try ed.thaw(a); + const got = live.text.ranges(live.text.own.?, 0, out); + return .{ .n = got.n, .primary = got.pri }; + } + + /// A key, as a text pane in normal or insert mode takes it. + pub fn key(ed: *Self, a: std.mem.Allocator, k: Key) Outcome { + const live = ed.thaw(a) catch return .{ .refused = .out_of_memory }; + const parsed = normal.textKey(live.context(a), &live.text, k); + switch (parsed) { + .unbound => return ed.keep(a, live, .{ .unbound = k }), + .pending => return ed.keep(a, live, .pending), + .ignored => return ed.keep(a, live, .done), + .action => |act| { + if (!normal.textRole(act.role)) { + // the parse's state goes on; nothing ran + ed.cursor.normal = live.text.normal; + return .{ .action = act }; + } + return ed.keep(a, live, .done); + }, + } + } + + /// A normal-mode action, as its key would run it: across every + /// range unless it is the selection's as a whole. + pub fn run(ed: *Self, a: std.mem.Allocator, act: Action) Outcome { + if (!normal.textRole(act.role)) return .{ .action = act }; + const live = ed.thaw(a) catch return .{ .refused = .out_of_memory }; + normal.runAction(live.context(a), &live.text, act); + return ed.keep(a, live, .done); + } + + /// helix's `s` (select), `S` (split), `K` (keep) and `Alt-K` + /// (remove) with `pattern` over the ranges there are. + pub fn selectRegex(ed: *Self, a: std.mem.Allocator, pattern: []const u8, how: RegexMode) Outcome { + const live = ed.thaw(a) catch return .{ .refused = .out_of_memory }; + const t = &live.text; + var snap: [max_selections]Selection = undefined; + const got = t.ranges(t.own.?, 0, &snap); + normal.selectByRegex(live.context(a), t, snap[0..got.n], got.pri, t.vsel.active and t.vsel.explicit, pattern, how); + return ed.keep(a, live, .done); + } + + /// Replace the whole text with `text`, as one step to undo. + pub fn setText(ed: *Self, a: std.mem.Allocator, text: []const u8) Outcome { + const live = ed.thaw(a) catch return .{ .refused = .out_of_memory }; + const e = live.context(a); + const t = &live.text; + edit.pushUndo(e, t) catch return .{ .refused = .out_of_memory }; + edit.setEditText(e, t, a.dupe(u8, text) catch return .{ .refused = .out_of_memory }) catch return .{ .refused = .out_of_memory }; + t.clampCursor(t.own.?, 0); + return ed.keep(a, live, .done); + } + + /// The register `name`'s values, one per range that wrote it. + pub fn register(ed: *const Self, a: std.mem.Allocator, name: u21) error{OutOfMemory}!?[]const []const u8 { + var r: Registers = .{}; + try ed.readRegisters(a, &r); + const reg = r.get(name) orelse return null; + return @ptrCast(reg.values); + } + + /// Write register `name` (the system clipboard's `+`, a pattern's + /// `/`): one value. + pub fn setRegister(ed: *Self, a: std.mem.Allocator, name: u21, value: []const u8) Outcome { + const live = ed.thaw(a) catch return .{ .refused = .out_of_memory }; + live.registers.put(a, name, value, 0, 1, true) catch return .{ .refused = .out_of_memory }; + return ed.keep(a, live, .done); + } + + fn thaw(ed: *const Self, a: std.mem.Allocator) error{OutOfMemory}!*Live { + const live = try a.create(Live); + live.* = .{ .text = .{ .what = .body, .own = try ed.bytes(a), .gpa = a } }; + const t = &live.text; + inline for (@typeInfo(Cursor).@"struct".field_names) |name| @field(t, name) = @field(ed.cursor, name); + if (ed.cursor.nsel > 0) { + t.sels = try a.alloc(Text.SelRange, Text.max_selections - 1); + @memcpy(t.sels[0..ed.cursor.nsel], ed.sels[0..ed.cursor.nsel]); + } + // Of the histories, what one key can reach: the snapshot an + // undo goes back to (or a new one is compared with), and the + // two newest a redo has, which tell a redo (one gone) from + // an edit forgetting them (both). + if (ed.undo.count > 0) { + t.ed_undo[0] = snapOf(try ed.undo.get(a, 0)); + t.ed_undo_len = 1; + live.undo_thawed = 1; + live.undo_from[0] = textPtr(t.ed_undo[0]); + } + const nr = @min(ed.redo.count, 2); + for (0..nr) |i| { + t.ed_redo[i] = snapOf(try ed.redo.get(a, @intCast(nr - 1 - i))); + live.redo_from[i] = textPtr(t.ed_redo[i]); + } + t.ed_redo_len = nr; + live.redo_thawed = nr; + try ed.readRegisters(a, &live.registers); + return live; + } + + fn readRegisters(ed: *const Self, a: std.mem.Allocator, r: *Registers) error{OutOfMemory}!void { + r.last_search = ed.last_search; + var at: usize = 0; + const b = ed.registers[0..ed.registers_len]; + while (at < b.len) { + const name: u21 = @intCast(std.mem.readInt(u32, b[at..][0..4], .little)); + const n = std.mem.readInt(u32, b[at + 4 ..][0..4], .little); + at += 8; + const values = try a.alloc([]u8, n); + for (values) |*v| { + const l = std.mem.readInt(u32, b[at..][0..4], .little); + v.* = try a.dupe(u8, b[at + 4 ..][0..l]); + at += 4 + l; + } + try r.list.append(a, .{ .name = name, .values = values }); + } + } + + /// How many of `thawed` snapshots are still at the bottom of + /// `now`, in order. + fn kept(from: []const ?[*]const u8, now: []const Text.Snapshot) usize { + var k: usize = 0; + while (k < from.len and k < now.len and textPtr(now[k]) == from[k]) k += 1; + return k; + } + + /// Freeze what the key made back into `ed`: all of it fits, or + /// none of it is written and the key is refused. + fn keep(ed: *Self, a: std.mem.Allocator, live: *Live, out: Outcome) Outcome { + const t = &live.text; + if (live.failed) return .{ .refused = .out_of_memory }; + const text = t.own orelse ""; + if (text.len > cap.text) return .{ .refused = .text_full }; + if (t.nsel > cap.selections - 1) return .{ .refused = .selections_full }; + var regs: std.ArrayList(u8) = .empty; + for (live.registers.list.items) |reg| { + var w: [4]u8 = undefined; + std.mem.writeInt(u32, &w, reg.name, .little); + regs.appendSlice(a, &w) catch return .{ .refused = .out_of_memory }; + std.mem.writeInt(u32, &w, @intCast(reg.values.len), .little); + regs.appendSlice(a, &w) catch return .{ .refused = .out_of_memory }; + for (reg.values) |v| { + std.mem.writeInt(u32, &w, @intCast(v.len), .little); + regs.appendSlice(a, &w) catch return .{ .refused = .out_of_memory }; + regs.appendSlice(a, v) catch return .{ .refused = .out_of_memory }; + } + } + if (regs.items.len > cap.registers) return .{ .refused = .registers_full }; + const undo_kept = kept(live.undo_from[0..live.undo_thawed], t.ed_undo[0..t.ed_undo_len]); + const redo_kept = kept(live.redo_from[0..live.redo_thawed], t.ed_redo[0..t.ed_redo_len]); + var undo_new: [Text.history_max][]u8 = undefined; + var redo_new: [Text.history_max][]u8 = undefined; + for (t.ed_undo[undo_kept..t.ed_undo_len], 0..) |s, i| undo_new[i] = snapBytes(a, s) catch return .{ .refused = .out_of_memory }; + for (t.ed_redo[redo_kept..t.ed_redo_len], 0..) |s, i| redo_new[i] = snapBytes(a, s) catch return .{ .refused = .out_of_memory }; + const nu = t.ed_undo_len - undo_kept; + const nr = t.ed_redo_len - redo_kept; + + // Everything fits: write it. + const old = ed.bytes(a) catch return .{ .refused = .out_of_memory }; + if (!std.mem.eql(u8, old, text)) { + // ponytail: O(text) a key, the text compared and placed + // whole; a DSL of a few KiB does not notice. The way up is + // one Buffer under File and the library (the survey's R3): + // the splice journal and line index pardes has for files. + var head: usize = 0; + while (head < old.len and head < text.len and old[head] == text[head]) head += 1; + var tail: usize = 0; + while (tail < old.len - head and tail < text.len - head and old[old.len - 1 - tail] == text[text.len - 1 - tail]) tail += 1; + // the gap goes where the edit ended + const front = text.len - tail; + @memcpy(ed.text[0..front], text[0..front]); + @memcpy(ed.text[cap.text - tail ..], text[front..]); + ed.front = @intCast(front); + ed.back = @intCast(tail); + ed.revision +%= 1; + } + inline for (@typeInfo(Cursor).@"struct".field_names) |name| @field(ed.cursor, name) = @field(t, name); + @memcpy(ed.sels[0..t.nsel], t.sels[0..t.nsel]); + if (live.undo_thawed > undo_kept) ed.undo.pop(); + for (undo_new[0..nu]) |s| ed.undo.push(s); + // both thawed redos gone: an edit forgot them all + if (live.redo_thawed == 2 and redo_kept == 0) ed.redo.clear() else for (redo_kept..live.redo_thawed) |_| ed.redo.pop(); + for (redo_new[0..nr]) |s| ed.redo.push(s); + @memcpy(ed.registers[0..regs.items.len], regs.items); + ed.registers_len = @intCast(regs.items.len); + ed.last_search = live.registers.last_search; + return out; + } + }; +} + +/// A text's parse, made again from its bytes and a `Language` when the +/// text has changed: derived, never stored (a tree holds pointers into +/// the grammar's code, which a reload unloads). Drop it (`forget`) at a +/// reload. +pub const Syntax = struct { + tree: ?*syntax.ts.Tree = null, + revision: u32 = 0, + + /// The tree of `ed`'s text in `lang`, parsed again when the text has + /// changed since the last; null when the language cannot parse. + pub fn parse(s: *Syntax, a: std.mem.Allocator, ed: anytype, lang: Language) ?*syntax.ts.Tree { + if (s.tree != null and s.revision == ed.revision) return s.tree; + if (s.tree) |tree| tree.destroy(); + s.tree = null; + const text = ed.bytes(a) catch return null; + if (!syntax_impl.addLanguage(lang)) return null; + var buf: [64]u8 = undefined; + s.tree = @ptrCast(@alignCast(syntax_impl.parseTree(lang.path(&buf), text, null) orelse return null)); + s.revision = ed.revision; + return s.tree; + } + + /// One `Syn` a byte of `ed`'s text from `from` to `to`, in `a`. + pub fn colors(a: std.mem.Allocator, ed: anytype, lang: Language, from: usize, to: usize) ![]syntax.Syn { + const text = try ed.bytes(a); + if (!syntax_impl.addLanguage(lang)) return error.TooManyLanguages; + var buf: [64]u8 = undefined; + return @ptrCast(try syntax_impl.highlightFileRange(a, lang.path(&buf), text, from, to)); + } + + /// The tree gone, and every language handed in (at a reload: their + /// code is about to go). + pub fn forget(s: *Syntax) void { + if (s.tree) |tree| tree.destroy(); + s.* = .{}; + syntax_impl.forgetLanguages(); + } +}; diff --git a/src/normal.zig b/src/normal.zig index 77f0c24c..c4c00824 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -14,14 +14,14 @@ const edit = @import("edit.zig"); const config = @import("config.zig"); const keyboard = @import("keys.zig"); const Pane = panes.Pane; -const Text = panes.Text; -const File = panes.File; -const Key = pardes.Key; -const hit = pardes.hit; +const Text = @import("Text.zig"); +const File = @import("File.zig"); +const Key = @import("plain").Key; +const hit = @import("Event.zig").hit; const sel_slot = pardes.sel_slot; const Pardes = pardes.Pardes; const Macro = pardes.Macro; -const Editor = pardes.Editor; +const Editor = @import("Editor.zig"); fn isPrefix(key: Key, cp: u21) bool { return key.cp == cp and !key.ctrl and !key.alt; @@ -55,8 +55,13 @@ pub fn selRegexArmed(pane: *Pane) ?struct { pat: []const u8, mode: modal.Normal. /// had when s/S/K/Alt-K was pressed; the prompt's snapshot of them lives on /// `pane`. pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, mode: modal.Normal.RegexMode) void { - const text = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(p.view().active, "edit", err); - const snap = pane.sel_snap[0..pane.nsel_snap]; + selectByRegex(p.editor(), t, pane.sel_snap[0..pane.nsel_snap], pane.sel_snap_pri, pane.sel_snap_expl, pat, mode); +} + +/// Select (or split on, keep or remove by) `pat` inside `snap`, the +/// ranges there were (primary `pri`) when s/S/K/Alt-K was pressed. +pub fn selectByRegex(e: Editor, t: *Text, snap: []modal.Selection, pri: usize, expl: bool, pat: []const u8, mode: modal.Normal.RegexMode) void { + const text = edit.flatSurface(e, t) catch |err| return e.reportError(err); var out: [Text.max_selections]modal.Selection = undefined; var m: usize = 0; if (regexp.Regex.compile(pat)) |compiled| { @@ -64,7 +69,7 @@ pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, mode: m var hay_all = text; if (for (pat) |c| { if (std.ascii.isUpper(c)) break false; - } else true) hay_all = std.ascii.allocLowerString(p.scratch.allocator(), text) catch |err| return p.reportError(p.view().active, "edit", err); + } else true) hay_all = std.ascii.allocLowerString(e.scratch, text) catch |err| return e.reportError(err); for (snap) |r| { const from = @min(r.anchor, r.head); const to = @min(@max(r.anchor, r.head), text.len); @@ -111,7 +116,7 @@ pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, mode: m r.anchor = @min(r.anchor, text.len); r.head = @min(r.head, text.len); } - return t.setRanges(text, snap, &.{}, pane.sel_snap_pri, pane.sel_snap_expl); + return t.setRanges(text, snap, &.{}, pri, expl); } t.setRanges(text, out[0..m], &.{}, 0, true); // helix keeps primary 0 (its own TODO) } @@ -396,7 +401,7 @@ fn selStart(s: Text.SelRange) struct { row: i32, col: i32 } { } pub fn replaySels(e: Editor, t: *Text, what: Replay) void { - const id = e.p.view().active; + const id = if (comptime Editor.lib) 0 else e.p.view().active; // a header belongs to no pane and cannot go away under the replay const owner = t.pane(); const serial = if (owner) |pane| pane.serial else 0; @@ -459,7 +464,7 @@ pub fn replaySels(e: Editor, t: *Text, what: Replay) void { }; t.sticky_col = list[i].sticky; (switch (what) { - .normal => |normal_action| executeNormalAction(e.p, t, normal_action), + .normal => |normal_action| actionPass(e, t, normal_action), .insert => |insert_key| edit.insertKey(e, t, insert_key), }) catch |err| e.reportError(err); if (e.multi_stop.*) break; @@ -522,22 +527,53 @@ fn normalInput(key: Key) modal.Normal.Input { return out; } -pub fn handleNormal(e: Editor, t: *Text, key: Key) void { +/// A key in a text's normal or insert mode, as keys.zig hands it on after +/// its own intercepts, and as the library takes it (lib_editor.zig): what +/// the parse made of it, `.ignored` for a key typed in insert mode. +pub fn textKey(e: Editor, t: *Text, key: Key) modal.Normal.Result { + switch (t.mode) { + .normal => return handleNormal(e, t, key), + .insert => if (hit(key, config.escape) and !t.reg_wait) + edit.exitInsert(e, t) + else + edit.handleInsert(e, t, key), + .tty => unreachable, // the terminal's (keys.zig) + } + return .ignored; +} + +pub fn handleNormal(e: Editor, t: *Text, key: Key) modal.Normal.Result { // `"` is held by the parser until the command it names arrives const named = t.normal.register; const parsed = modal.Normal.parse(&t.normal, normalInput(key)); const action = switch (parsed) { - .pending, .ignored, .unbound => return, + .pending, .ignored, .unbound => return parsed, .action => |value| value, }; t.normal.register = 0; + // the core's roles are the library's caller's + if (comptime Editor.lib) if (!textRole(action.role)) return parsed; e.register.* = named; defer e.register.* = 0; + runAction(e, t, action); + return parsed; +} + +/// A normal-mode action run across every range, or once for the +/// selection as a whole. +pub fn runAction(e: Editor, t: *Text, action: modal.Normal.Action) void { if (t.nsel == 0 or action.once()) - return executeNormalAction(e.p, t, action) catch |err| e.reportError(err); + return actionPass(e, t, action) catch |err| e.reportError(err); replaySels(e, t, .{ .normal = action }); } +/// One pass of an action: the core's, which hands the text its own roles; +/// the library has the text's alone. +fn actionPass(e: Editor, t: *Text, action: modal.Normal.Action) edit.Error!void { + if (comptime Editor.lib) return textAction(e, t, action); + return executeNormalAction(e.p, t, action); +} + fn startSelRegex(p: *Pardes, pane: *Pane, t: *Text, mode: modal.Normal.RegexMode) edit.Error!void { const text = try edit.flatSurface(p.editor(), t); const got = t.ranges(text, 0, &pane.sel_snap); @@ -805,7 +841,8 @@ fn findMove(t: *Text, text: []const u8, range: modal.Selection, ch: u21, kind: m /// The file pane whose text `text` is, when `t` is its body: its rows are /// measured through their table pads (File.rowPads), so j and k keep the /// column a table shows, not the one its source has. -fn filePane(t: *Text, text: []const u8) ?*const Pane { +inline fn filePane(t: *Text, text: []const u8) ?*const Pane { + if (comptime Editor.lib) return null; if (t.what != .body) return null; const fp = t.pane() orelse return null; const f = if (fp.file) |*file| file else return null; @@ -966,6 +1003,7 @@ pub fn textAction(e: Editor, t: *Text, a: modal.Normal.Action) edit.Error!void { switch (a.role) { .escape => { t.select = false; + if (comptime Editor.lib) return; // typed again by a macro, Esc is only helix's if (e.p.macro.replaying > 0) return; tagline.exitHeader(e.p); // out of a header too, as Shift-Esc @@ -1359,12 +1397,12 @@ test "flat text movement and selection replay need no scratch rows" { p.scratch = .init(denied.allocator()); pane.body.cur_row = 4094; - handleNormal(p.editor(), &pane.body, .{ .cp = 'l' }); + _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'l' }); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); - handleNormal(p.editor(), &pane.body, .{ .cp = 'j' }); + _ = handleNormal(p.editor(), &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.editor(), &pane.body, .{ .cp = 'h' }); + _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'h' }); try std.testing.expectEqual(@as(i32, 0), pane.body.cur_col); try executeNormalAction(p, &pane.body, .{ .role = .match_inside, .char = 'w' }); try std.testing.expectEqual(@as(i32, 2), pane.body.cur_col); @@ -1376,8 +1414,8 @@ test "flat text movement and selection replay need no scratch rows" { pane.body.nsel = 1; _ = pane.body.reserveSels(); pane.body.sels[0] = .{ .row = 3072, .col = 0, .arow = 3072, .acol = 0 }; - handleNormal(p.editor(), &pane.body, .{ .cp = 'l' }); - handleNormal(p.editor(), &pane.body, .{ .cp = 'j' }); + _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'l' }); + _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'j' }); try std.testing.expectEqual(@as(u16, 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); @@ -1480,19 +1518,19 @@ test "one cursor holds no room for other ranges; a second range makes it and one const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 }); defer p.deinit(); const pane = try p.setTestFile("alpha beta\nalpha beta\n"); - for ("wxe%;gg") |cp| handleNormal(p.editor(), &pane.body, .{ .cp = cp }); + for ("wxe%;gg") |cp| _ = handleNormal(p.editor(), &pane.body, .{ .cp = cp }); try std.testing.expectEqual(@as(usize, 0), pane.body.sels.len); - handleNormal(p.editor(), &pane.body, .{ .cp = 'C' }); + _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'C' }); try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); try std.testing.expect(pane.body.sels.len > 0); - handleNormal(p.editor(), &pane.body, .{ .cp = 'l' }); // replayed at both, still two + _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'l' }); // replayed at both, still two try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); - handleNormal(p.editor(), &pane.body, .{ .cp = ',' }); + _ = handleNormal(p.editor(), &pane.body, .{ .cp = ',' }); try std.testing.expectEqual(@as(usize, 0), pane.body.sels.len); - handleNormal(p.editor(), &pane.body, .{ .cp = 'C' }); - handleNormal(p.editor(), &pane.body, .{ .cp = ';' }); - handleNormal(p.editor(), &pane.body, .{ .cp = 'x' }); // x at both: still two lines - handleNormal(p.editor(), &pane.body, .{ .cp = '_', .alt = true }); // merged to one + _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'C' }); + _ = handleNormal(p.editor(), &pane.body, .{ .cp = ';' }); + _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'x' }); // x at both: still two lines + _ = handleNormal(p.editor(), &pane.body, .{ .cp = '_', .alt = true }); // merged to one try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); try std.testing.expectEqual(@as(usize, 0), pane.body.sels.len); } @@ -1503,9 +1541,9 @@ test "cursors that land on one place are one: a key typed there is typed once, a defer p.deinit(); const pane = try p.setTestFile("ab\ncd\n"); // A cursor below, then both up: the second lands on the first. - handleNormal(p.editor(), &pane.body, .{ .cp = 'C' }); + _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'C' }); try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); - handleNormal(p.editor(), &pane.body, .{ .cp = 'k' }); + _ = handleNormal(p.editor(), &pane.body, .{ .cp = 'k' }); try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); p.update(.{ .key = .{ .cp = 'i', .text = "i" } }); p.update(.{ .key = .{ .cp = 'x', .text = "x" } }); @@ -1518,10 +1556,10 @@ test "r and Delete take whole graphemes" { defer p.deinit(); const pane = try p.setTestFile("A" ++ "e\u{301}" ++ "👩🏽\u{200d}🚀" ++ "🇧🇷" ++ "界" ++ "Z\n"); // é, the astronaut and the flag: three graphemes, three 界 - for ("lv2lr") |c| handleNormal(p.editor(), &pane.body, .{ .cp = c }); - handleNormal(p.editor(), &pane.body, .{ .cp = '界' }); + for ("lv2lr") |c| _ = handleNormal(p.editor(), &pane.body, .{ .cp = c }); + _ = handleNormal(p.editor(), &pane.body, .{ .cp = '界' }); try std.testing.expectEqualStrings("A界界界界Z\n", pane.file.?.content); - for ("u0li") |c| handleNormal(p.editor(), &pane.body, .{ .cp = c }); + for ("u0li") |c| _ = handleNormal(p.editor(), &pane.body, .{ .cp = c }); p.update(.{ .key = .{ .cp = Key.delete } }); try std.testing.expectEqualStrings("A" ++ "👩🏽\u{200d}🚀" ++ "🇧🇷" ++ "界" ++ "Z\n", pane.file.?.content); } diff --git a/test/lib/build.zig b/test/lib/build.zig index 6cd8d6e5..6f590eda 100644 --- a/test/lib/build.zig +++ b/test/lib/build.zig @@ -1,18 +1,24 @@ //! A package that depends on pardes for its library, as a program that draws //! source text itself would: pardes's `lib-test` step runs `zig build test` //! here, so the `pardes-syntax` module is built the way such a package -//! builds it (build.zig's `library`), with the minimal grammars. +//! builds it (build.zig's `library`), with the minimal grammars, and +//! `pardes-editor`, the text pane as a library, which it asks for. const std = @import("std"); pub fn build(b: *std.Build) void { const target = b.standardTargetOptions(.{}); const optimize = b.standardOptimizeOption(.{}); - const pardes = b.dependency("pardes", .{ .target = target, .optimize = optimize, .@"tree-sitter" = .minimal }); - const tests = b.addTest(.{ .root_module = b.createModule(.{ - .target = target, - .optimize = optimize, - .root_source_file = b.path("lib.zig"), - .imports = &.{.{ .name = "pardes-syntax", .module = pardes.module("pardes-syntax") }}, - }) }); - b.step("test", "colour, outline and walk a C and a Zig source through pardes's library").dependOn(&b.addRunArtifact(tests).step); + const pardes = b.dependency("pardes", .{ .target = target, .optimize = optimize, .@"tree-sitter" = .minimal, .editor = true }); + const step = b.step("test", "colour, outline and walk a C and a Zig source through pardes's library, and edit a text with its editor"); + // A file belongs to one module: the syntax alone, and the editor (which + // has it as `.syntax`), each a test of its own. + for ([_][2][]const u8{ .{ "lib.zig", "pardes-syntax" }, .{ "editor.zig", "pardes-editor" } }) |t| { + const tests = b.addTest(.{ .root_module = b.createModule(.{ + .target = target, + .optimize = optimize, + .root_source_file = b.path(t[0]), + .imports = &.{.{ .name = t[1], .module = pardes.module(t[1]) }}, + }) }); + step.dependOn(&b.addRunArtifact(tests).step); + } } diff --git a/test/lib/editor.zig b/test/lib/editor.zig new file mode 100644 index 00000000..412e5109 --- /dev/null +++ b/test/lib/editor.zig @@ -0,0 +1,144 @@ +//! The editor as a package that depends on pardes takes it +//! (`pardes-editor`): a value of plain data a program keeps, typed into a +//! key at a time with an arena each call, copied anywhere, refused whole at +//! its capacities (docs/next-editor.md). +const std = @import("std"); +const pe = @import("pardes-editor"); + +const Ed = pe.Editor(.{ .text = 4096, .undo = 8192, .registers = 1024, .selections = 16 }); + +/// Keys in helix's notation, the few these tests type: printables, and +/// ``, ``, ``. +fn typeKeys(ed: anytype, gpa: std.mem.Allocator, keys: []const u8) !void { + var i: usize = 0; + while (i < keys.len) { + var k: pe.Key = .{ .cp = keys[i], .text = keys[i .. i + 1] }; + inline for (.{ .{ "", pe.Key.escape }, .{ "", pe.Key.enter }, .{ "", pe.Key.backspace } }) |special| { + if (std.mem.startsWith(u8, keys[i..], special[0])) k = .{ .cp = special[1] }; + } + i += if (k.text.len == 0) std.mem.indexOfScalarPos(u8, keys, i, '>').? + 1 - i else 1; + // every call its own arena, gone after it: nothing of a key outlives it + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + switch (ed.key(arena.allocator(), k)) { + .refused => return error.Refused, + else => {}, + } + } +} + +fn text(ed: anytype, buf: []u8) []const u8 { + return ed.read(buf); +} + +const first = "ifn main() { let x = 1;}ggxyp" ++ "wwCcfoo"; +const second = "%dpuuUjjAbar" ++ "ggiqu"; + +test "a value copied elsewhere, its old memory gone, types on as one never moved" { + const gpa = std.testing.allocator; + const still = try gpa.create(Ed); + defer gpa.destroy(still); + still.* = .{}; + try typeKeys(still, gpa, first); + try typeKeys(still, gpa, second); + + const before = try gpa.create(Ed); + before.* = .{}; + try typeKeys(before, gpa, first); + const moved = try gpa.create(Ed); + defer gpa.destroy(moved); + @memcpy(std.mem.asBytes(moved), std.mem.asBytes(before)); + @memset(std.mem.asBytes(before), 0xAA); + gpa.destroy(before); + try typeKeys(moved, gpa, second); + + try std.testing.expectEqualSlices(u8, std.mem.asBytes(still), std.mem.asBytes(moved)); + var buf: [4096]u8 = undefined; + // `%d` then `p`, both undone, the delete redone: `A` types into nothing + try std.testing.expectEqualStrings("bar", text(moved, &buf)); +} + +test "undo goes back as far as the ring holds, and redo all the way again" { + const gpa = std.testing.allocator; + const ed = try gpa.create(Ed); + defer gpa.destroy(ed); + ed.* = .{}; + const xs: [1000]u8 = @splat('x'); + try ed.load(&xs); + // thirty edits, each a snapshot of a thousand bytes: an 8 KiB ring + // keeps the last few + for (0..30) |_| try typeKeys(ed, gpa, "ia"); + var buf: [4096]u8 = undefined; + var last: [4096]u8 = undefined; + const final = text(ed, &last); + try std.testing.expectEqual(1030, final.len); + try std.testing.expect(ed.undo.count < 30); + const kept = ed.undo.count; + for (0..40) |_| try typeKeys(ed, gpa, "u"); + try std.testing.expectEqual(1030 - kept, text(ed, &buf).len); + for (0..40) |_| try typeKeys(ed, gpa, "U"); + try std.testing.expectEqualStrings(final, text(ed, &buf)); +} + +test "a key whose text would not fit is refused, and the value is as it was" { + const gpa = std.testing.allocator; + const ed = try gpa.create(Ed); + defer gpa.destroy(ed); + ed.* = .{}; + const ys: [5000]u8 = @splat('y'); + try std.testing.expectError(error.TextFull, ed.load(&ys)); + try ed.load(ys[0..4094]); + try typeKeys(ed, gpa, "iab"); + const kept = try gpa.create(Ed); + defer gpa.destroy(kept); + kept.* = ed.*; + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + try std.testing.expectEqual(pe.Outcome{ .refused = .text_full }, ed.key(arena.allocator(), .{ .cp = 'c', .text = "c" })); + try std.testing.expectEqualSlices(u8, std.mem.asBytes(kept), std.mem.asBytes(ed)); +} + +test "what is not the text's comes back, and the caller can do it" { + const gpa = std.testing.allocator; + const ed = try gpa.create(Ed); + defer gpa.destroy(ed); + ed.* = .{}; + try ed.load("one two one\n"); + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + try std.testing.expectEqual(pe.Role.command_line, ed.key(a, .{ .cp = ':', .text = ":" }).action.role); + _ = ed.key(a, .{ .cp = '%', .text = "%" }); + try std.testing.expectEqual(pe.Role.select_regex, ed.key(a, .{ .cp = 's', .text = "s" }).action.role); + _ = ed.selectRegex(a, "one", .select); + var out: [pe.max_selections]pe.Selection = undefined; + const got = try ed.ranges(a, &out); + try std.testing.expectEqual(2, got.n); + try std.testing.expectEqual(pe.Selection{ .anchor = 8, .head = 11 }, out[1]); + try std.testing.expectEqual(pe.Mode.normal, ed.mode()); + _ = ed.key(a, .{ .cp = 'g', .text = "g" }); + try std.testing.expectEqual(pe.Role.goto_prefix, ed.pending().?); +} + +extern fn tree_sitter_c() *const pe.syntax.ts.Language; + +test "a language handed in at run time parses and colours the text" { + const gpa = std.testing.allocator; + const ed = try gpa.create(Ed); + defer gpa.destroy(ed); + ed.* = .{}; + try ed.load("int f() { return 1; }\n"); + pe.syntax.start(gpa); + defer pe.syntax.stop(); + const lang: pe.Language = .{ .name = "mine", .ext = ".mine", .ts = tree_sitter_c(), .highlights = "\"return\" @keyword (number_literal) @number" }; + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + var syn: pe.Syntax = .{}; + defer syn.forget(); + const tree = syn.parse(arena.allocator(), ed, lang) orelse return error.NoTree; + try std.testing.expectEqualStrings("translation_unit", tree.rootNode().kind()); + const colors = try pe.Syntax.colors(arena.allocator(), ed, lang, 0, ed.len()); + try std.testing.expectEqual(pe.syntax.Syn.keyword, colors[10]); + try std.testing.expectEqual(pe.syntax.Syn.number, colors[17]); + try std.testing.expectEqual(pe.syntax.Syn.none, colors[0]); +} -- cgit v1.3 From f233d87376bbdfde3918f803e31b52a214ea9bdb Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 07:24:58 -0300 Subject: +171 -73 lib: the tree-sitter walks run in the library on a parse its caller hands in (docs/next-editor.md): `key(a, syn, k)` and `run(a, syn, act)` take a `?*Syntax`, which keeps the grammar it parses in, the tree, made on the first walk after the text changes, and helix's object_selections (Alt-o's history, for Alt-i to go back the way it came) in the page allocator; with one, Alt-o, Alt-i, Alt-n, Alt-p, Alt-a, Alt-I, Alt-e, Alt-b and `]f` and kin run in the library, and `mif` and kin find the grammar's textobjects; without, they come back as actions, as before; normal.nodeTree is the parse they read, a file's (fileTree) in pardes and the one handed in in the library, `Editor.Tree` its tree, path and history, so nodeSelect and objectJump take the editor's context and are textAction's, textRole saying the walks are the text's with a parse at hand, and edit.textobjectSelect reads it too; NodeStep moves to Editor.zig (File.zig names it); nothing a pane does changes; hxlib hands each case a parse with no grammar (a case's text has none): 538 of 658 compared with 0 mismatches (expand_node's one case moved from the caller's), --parity 618 of 738 with 0 mismatches; test/lib: Alt-o and Alt-i on C, back the way they came, `maf` from a textobjects query handed in, and Alt-o without a parse the caller's; core-test 811 of 950, shell-test 990 of 993, hxdiff 658 / parity 738 / hxgolf 124 with 0 mismatches, replicas pass, lib-test pass Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- src/Editor.zig | 13 +++++++++ src/File.zig | 2 +- src/edit.zig | 9 ++---- src/lib_editor.zig | 79 +++++++++++++++++++++++++++++++++++++++-------------- src/normal.zig | 74 +++++++++++++++++++++++++++---------------------- test/hxlib.zig | 11 ++++++-- test/lib/bench.zig | 8 +++--- test/lib/editor.zig | 48 ++++++++++++++++++++++++++++---- 8 files changed, 171 insertions(+), 73 deletions(-) (limited to 'src/normal.zig') diff --git a/src/Editor.zig b/src/Editor.zig index 014d1923..b7c7057d 100644 --- a/src/Editor.zig +++ b/src/Editor.zig @@ -12,9 +12,18 @@ const Registers = @import("Registers.zig"); /// on this at compile time, so the library never compiles the core. pub const lib = @import("pardes_config").lib; const Pardes = if (lib) void else @import("Core.zig"); +const Syntax = if (lib) @import("lib_editor.zig").Syntax else void; +const modal = @import("modal.zig"); const Editor = @This(); +/// A text's parse as the tree-sitter walks read it (normal.nodeTree): the +/// tree, a path its grammar's queries are found by, and helix's +/// object_selections, what Alt-o grew from for Alt-i to go back to, its +/// ranges in `gpa`. Dropped with the tree when the text changes. +pub const Tree = struct { root: *anyopaque, path: []const u8, history: *std.ArrayList(NodeStep), gpa: std.mem.Allocator }; +pub const NodeStep = struct { ranges: []modal.Selection, primary: usize }; + gpa: std.mem.Allocator, /// What an edit makes and drops: the update's scratch. scratch: std.mem.Allocator, @@ -39,6 +48,9 @@ p: if (lib) void else *Pardes, /// The library's: an edit failed (its allocator ran out) and the key is /// refused. failed: if (lib) *bool else void, +/// The library's: the parse its caller handed in, which the tree-sitter +/// walks read; null, and they are the caller's (`textRole`). +syntax: if (lib) ?*Syntax else void, pub fn of(p: *Pardes) Editor { return .{ @@ -53,6 +65,7 @@ pub fn of(p: *Pardes) Editor { .retired_edit = &p.retired_edit, .p = p, .failed = {}, + .syntax = {}, }; } diff --git a/src/File.zig b/src/File.zig index 0c3c3a2f..d049fc27 100644 --- a/src/File.zig +++ b/src/File.zig @@ -181,7 +181,7 @@ pub const State = struct { follow: bool = false, }; -pub const NodeStep = struct { ranges: []modal.Selection, primary: usize }; +pub const NodeStep = @import("Editor.zig").NodeStep; pub fn graphemeDisplayWidth(grapheme: []const u8) usize { if (std.mem.eql(u8, grapheme, "\t")) return config.tab_now; diff --git a/src/edit.zig b/src/edit.zig index 105b9abf..8c59ffa1 100644 --- a/src/edit.zig +++ b/src/edit.zig @@ -1261,7 +1261,7 @@ fn insertEdit(e: Editor, t: *Text, key: Key) Error!void { const pane = t.pane() orelse break :smart; const f = pane.file orelse break :smart; if (!syntax.supportsPath(f.path)) break :smart; - return normal.nodeSelect(e.p, pane, t, .parent_node_end); + return normal.nodeSelect(e, t, f.content, .parent_node_end); } try insertTab(e, t); }, @@ -1943,11 +1943,8 @@ pub fn textobjectSelect(e: Editor, t: *Text, text: []const u8, obj: u21, around: else => null, }; if (object) |o| { - if (t.what != .body) return; - const pane = t.pane() orelse return; - const f = if (pane.file) |*file| file else return; - const tree = normal.fileTree(e.p, f) orelse return; - const s = syntax.objectAt(f.path, tree, text, o, around, modal.selectionCursor(text, range)) orelse return; + const tree = normal.nodeTree(e, t, text) orelse return; + const s = syntax.objectAt(tree.path, tree.root, text, o, around, modal.selectionCursor(text, range)) orelse return; return t.setRange(text, 0, .{ .anchor = s.from, .head = s.to }, false); } switch (obj) { diff --git a/src/lib_editor.zig b/src/lib_editor.zig index 86e494e1..f9149ef0 100644 --- a/src/lib_editor.zig +++ b/src/lib_editor.zig @@ -221,6 +221,7 @@ const Live = struct { multi_count: usize = 1, retired_edit: ?[]u8 = null, failed: bool = false, + syntax: ?*Syntax = null, undo_thawed: usize = 0, redo_thawed: usize = 0, /// The ring records thawed, by their text's address: a snapshot still @@ -241,6 +242,7 @@ const Live = struct { .retired_edit = &l.retired_edit, .p = {}, .failed = &l.failed, + .syntax = l.syntax, }; } }; @@ -318,21 +320,24 @@ pub fn Editor(comptime cap: Capacity) type { /// The ranges in document order and which is the primary. pub fn ranges(ed: *const Self, a: std.mem.Allocator, out: *[max_selections]Selection) error{OutOfMemory}!struct { n: usize, primary: usize } { - const live = try ed.thaw(a); + const live = try ed.thaw(a, null); const got = live.text.ranges(live.text.own.?, 0, out); return .{ .n = got.n, .primary = got.pri }; } - /// A key, as a text pane in normal or insert mode takes it. - pub fn key(ed: *Self, a: std.mem.Allocator, k: Key) Outcome { - const live = ed.thaw(a) catch return .{ .refused = .out_of_memory }; + /// A key, as a text pane in normal or insert mode takes it. With + /// `syn`, the tree-sitter walks (Alt-o and kin, `]f`, `mif`) run on + /// its parse, made again if the text has changed; without, they + /// come back as actions (`mif` does nothing). + pub fn key(ed: *Self, a: std.mem.Allocator, syn: ?*Syntax, k: Key) Outcome { + const live = ed.thaw(a, syn) catch return .{ .refused = .out_of_memory }; const parsed = normal.textKey(live.context(a), &live.text, k); switch (parsed) { .unbound => return ed.keep(a, live, .{ .unbound = k }), .pending => return ed.keep(a, live, .pending), .ignored => return ed.keep(a, live, .done), .action => |act| { - if (!normal.textRole(act.role)) { + if (!normal.textRole(act.role, syn != null)) { // the parse's state goes on; nothing ran ed.cursor.normal = live.text.normal; return .{ .action = act }; @@ -344,9 +349,9 @@ pub fn Editor(comptime cap: Capacity) type { /// A normal-mode action, as its key would run it: across every /// range unless it is the selection's as a whole. - pub fn run(ed: *Self, a: std.mem.Allocator, act: Action) Outcome { - if (!normal.textRole(act.role)) return .{ .action = act }; - const live = ed.thaw(a) catch return .{ .refused = .out_of_memory }; + pub fn run(ed: *Self, a: std.mem.Allocator, syn: ?*Syntax, act: Action) Outcome { + if (!normal.textRole(act.role, syn != null)) return .{ .action = act }; + const live = ed.thaw(a, syn) catch return .{ .refused = .out_of_memory }; normal.runAction(live.context(a), &live.text, act); return ed.keep(a, live, .done); } @@ -354,7 +359,7 @@ pub fn Editor(comptime cap: Capacity) type { /// helix's `s` (select), `S` (split), `K` (keep) and `Alt-K` /// (remove) with `pattern` over the ranges there are. pub fn selectRegex(ed: *Self, a: std.mem.Allocator, pattern: []const u8, how: RegexMode) Outcome { - const live = ed.thaw(a) catch return .{ .refused = .out_of_memory }; + const live = ed.thaw(a, null) catch return .{ .refused = .out_of_memory }; const t = &live.text; // as pardes's prompt answers it (look.submitSearch): helix // keeps the pattern in `/` @@ -370,7 +375,7 @@ pub fn Editor(comptime cap: Capacity) type { /// Replace the whole text with `text`, as one step to undo. pub fn setText(ed: *Self, a: std.mem.Allocator, text: []const u8) Outcome { - const live = ed.thaw(a) catch return .{ .refused = .out_of_memory }; + const live = ed.thaw(a, null) catch return .{ .refused = .out_of_memory }; const e = live.context(a); const t = &live.text; edit.pushUndo(e, t) catch return .{ .refused = .out_of_memory }; @@ -390,14 +395,15 @@ pub fn Editor(comptime cap: Capacity) type { /// Write register `name` (the system clipboard's `+`, a pattern's /// `/`): one value. pub fn setRegister(ed: *Self, a: std.mem.Allocator, name: u21, value: []const u8) Outcome { - const live = ed.thaw(a) catch return .{ .refused = .out_of_memory }; + const live = ed.thaw(a, null) catch return .{ .refused = .out_of_memory }; live.registers.put(a, name, value, 0, 1, true) catch return .{ .refused = .out_of_memory }; return ed.keep(a, live, .done); } - fn thaw(ed: *const Self, a: std.mem.Allocator) error{OutOfMemory}!*Live { + fn thaw(ed: *const Self, a: std.mem.Allocator, syn: ?*Syntax) error{OutOfMemory}!*Live { const live = try a.create(Live); - live.* = .{ .text = .{ .what = .body, .own = try ed.bytes(a), .gpa = a } }; + live.* = .{ .text = .{ .what = .body, .own = try ed.bytes(a), .gpa = a }, .syntax = syn }; + if (syn) |s| s.at(ed.revision); const t = &live.text; inline for (@typeInfo(Cursor).@"struct".field_names) |name| @field(t, name) = @field(ed.cursor, name); if (ed.cursor.nsel > 0) { @@ -523,19 +529,50 @@ pub fn Editor(comptime cap: Capacity) type { pub const Syntax = struct { tree: ?*syntax.ts.Tree = null, revision: u32 = 0, + /// The grammar the tree is parsed in: the last `parse`'s, or set by a + /// caller that hands this to `key` before parsing. None, and a walk + /// does nothing, as in a text without a grammar. + lang: ?Language = null, + /// helix's object_selections, what Alt-o grew from for Alt-i to go back + /// to (normal.nodeSelect): the tree's, dropped with it. In the page + /// allocator, which holds nothing of the code that made it. + history: std.ArrayList(Context.NodeStep) = .empty, + path: [64]u8 = undefined, /// The tree of `ed`'s text in `lang`, parsed again when the text has /// changed since the last; null when the language cannot parse. pub fn parse(s: *Syntax, a: std.mem.Allocator, ed: anytype, lang: Language) ?*syntax.ts.Tree { - if (s.tree != null and s.revision == ed.revision) return s.tree; + s.lang = lang; + s.at(ed.revision); + if (s.tree == null) _ = s.walkTree(ed.bytes(a) catch return null); + return s.tree; + } + + /// What is kept of another revision of the text dropped: the tree and + /// Alt-o's history. + fn at(s: *Syntax, revision: u32) void { + if (s.revision == revision) return; + s.drop(); + s.revision = revision; + } + + fn drop(s: *Syntax) void { if (s.tree) |tree| tree.destroy(); s.tree = null; - const text = ed.bytes(a) catch return null; - if (!syntax_impl.addLanguage(lang)) return null; - var buf: [64]u8 = undefined; - s.tree = @ptrCast(@alignCast(syntax_impl.parseTree(lang.path(&buf), text, null) orelse return null)); - s.revision = ed.revision; - return s.tree; + for (s.history.items) |step| std.heap.page_allocator.free(step.ranges); + s.history.clearAndFree(std.heap.page_allocator); + } + + /// The parse of `text`, the text at `revision`, as a key's walks read + /// it (normal.nodeTree): made the first time one asks for it. + pub fn walkTree(s: *Syntax, text: []const u8) ?Context.Tree { + const lang = s.lang orelse return null; + const path = lang.path(&s.path); + if (s.tree == null) { + if (!syntax_impl.addLanguage(lang)) return null; + s.tree = @ptrCast(@alignCast(syntax_impl.parseTree(path, text, null) orelse return null)); + } + return .{ .root = s.tree.?, .path = path, .history = &s.history, .gpa = std.heap.page_allocator }; } /// One `Syn` a byte of `ed`'s text from `from` to `to`, in `a`. @@ -549,7 +586,7 @@ pub const Syntax = struct { /// The tree gone, and every language handed in (at a reload: their /// code is about to go). pub fn forget(s: *Syntax) void { - if (s.tree) |tree| tree.destroy(); + s.drop(); s.* = .{}; syntax_impl.forgetLanguages(); } diff --git a/src/normal.zig b/src/normal.zig index c4c00824..70933607 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -225,16 +225,25 @@ pub fn fileTree(p: *Pardes, f: *panes.File.State) ?*anyopaque { return f.node_tree; } +/// The parse a body's tree-sitter walks read: its file's (`fileTree`), or +/// in the library the one its caller handed in (lib_editor.Syntax); null +/// without a grammar, and the walk leaves the ranges as they are. +pub fn nodeTree(e: Editor, t: *Text, text: []const u8) ?Editor.Tree { + if (t.what != .body) return null; + if (comptime Editor.lib) return (e.syntax orelse return null).walkTree(text); + const pane = t.pane() orelse return null; + const f = if (pane.file) |*file| file else return null; + return .{ .root = fileTree(e.p, f) orelse return null, .path = f.path, .history = &f.node_history, .gpa = e.gpa }; +} + /// `]f`/`[f` and kin (helix goto_ts_object): to the next object starting /// after the cursor or the previous one ending before it, count times; select /// mode stretches the range to it. -fn objectJump(p: *Pardes, pane: *Pane, t: *Text, text: []const u8, range: modal.Selection, object: modal.Normal.Object, forward: bool, count: u32) void { - if (t.what != .body) return; - const f = if (pane.file) |*file| file else return; - const tree = fileTree(p, f) orelse return; +fn objectJump(e: Editor, t: *Text, text: []const u8, range: modal.Selection, object: modal.Normal.Object, forward: bool, count: u32) void { + const tree = nodeTree(e, t, text) orelse return; var last = range; for (0..count) |_| { - const s = syntax.objectNext(f.path, tree, text, object, forward, modal.selectionCursor(text, last)) orelse break; + const s = syntax.objectNext(tree.path, tree.root, text, object, forward, modal.selectionCursor(text, last)) orelse break; const next: modal.Selection = .{ .anchor = s.from, .head = s.to }; if (std.meta.eql(next, last)) break; last = next; @@ -248,21 +257,19 @@ fn objectJump(p: *Pardes, pane: *Pane, t: *Text, text: []const u8, range: modal. t.setRange(text, 0, out, false); } -/// helix's tree-sitter selection keys: every range walks the file's parse, -/// which is made on the first of these keys after an edit and kept, never -/// made again for a key that changed nothing. A range the tree has nothing -/// to say about stays as it was; a text without a grammar, all of them. -pub fn nodeSelect(p: *Pardes, pane: *Pane, t: *Text, walk: modal.Normal.NodeWalk) edit.Error!void { - if (t.what != .body) return; - const f = if (pane.file) |*file| file else return; - const tree = fileTree(p, f) orelse return; - const text = f.content; +/// helix's tree-sitter selection keys: every range walks the text's parse +/// (`nodeTree`), which is made on the first of these keys after an edit and +/// kept, never made again for a key that changed nothing. A range the tree +/// has nothing to say about stays as it was; a text without a grammar, all +/// of them. +pub fn nodeSelect(e: Editor, t: *Text, text: []const u8, walk: modal.Normal.NodeWalk) edit.Error!void { + const tree = nodeTree(e, t, text) orelse return; const expl = t.vsel.active and t.vsel.explicit; - const arena = p.scratch.allocator(); + const arena = e.scratch; const rs = try arena.alloc(modal.Selection, Text.max_selections); const got = t.ranges(text, 0, rs[0..Text.max_selections]); - if (walk == .shrink_node) if (f.node_history.pop()) |prev| { - defer p.gpa.free(prev.ranges); + if (walk == .shrink_node) if (tree.history.pop()) |prev| { + defer tree.gpa.free(prev.ranges); // back to what Alt-o grew from, while the selection still holds it const holds = for (prev.ranges) |pr| { const pf = @min(pr.anchor, pr.head); @@ -273,8 +280,8 @@ pub fn nodeSelect(p: *Pardes, pane: *Pane, t: *Text, walk: modal.Normal.NodeWalk break false; } else true; if (holds) return t.setRanges(text, prev.ranges, &.{}, prev.primary, expl); - for (f.node_history.items) |step| p.gpa.free(step.ranges); - f.node_history.clearRetainingCapacity(); + for (tree.history.items) |step| tree.gpa.free(step.ranges); + tree.history.clearRetainingCapacity(); }; const out = try arena.alloc(modal.Selection, Text.max_selections); const spans = try arena.alloc(syntax.Span, Text.max_selections); @@ -284,7 +291,7 @@ pub fn nodeSelect(p: *Pardes, pane: *Pane, t: *Text, walk: modal.Normal.NodeWalk const from = @min(r.anchor, r.head); const to = @max(r.anchor, r.head); const back = r.head < r.anchor; - const n = syntax.walkNodes(tree, walk, from, to, modal.selectionCursor(text, r), spans[0 .. out.len - m]); + const n = syntax.walkNodes(tree.root, walk, from, to, modal.selectionCursor(text, r), spans[0 .. out.len - m]); if (n == 0) { out[m] = r; m += 1; @@ -312,8 +319,8 @@ pub fn nodeSelect(p: *Pardes, pane: *Pane, t: *Text, walk: modal.Normal.NodeWalk } const same = m == got.n and std.mem.eql(u8, std.mem.sliceAsBytes(out[0..m]), std.mem.sliceAsBytes(rs[0..m])); if (walk == .expand_node and !same) remember: { - const ranges = p.gpa.dupe(modal.Selection, rs[0..got.n]) catch break :remember; - f.node_history.append(p.gpa, .{ .ranges = ranges, .primary = got.pri }) catch p.gpa.free(ranges); + const ranges = tree.gpa.dupe(modal.Selection, rs[0..got.n]) catch break :remember; + tree.history.append(tree.gpa, .{ .ranges = ranges, .primary = got.pri }) catch tree.gpa.free(ranges); } t.setRanges(text, out[0..m], &.{}, @min(got.pri, m - 1), expl); } @@ -552,7 +559,7 @@ pub fn handleNormal(e: Editor, t: *Text, key: Key) modal.Normal.Result { }; t.normal.register = 0; // the core's roles are the library's caller's - if (comptime Editor.lib) if (!textRole(action.role)) return parsed; + if (comptime Editor.lib) if (!textRole(action.role, e.syntax != null)) return parsed; e.register.* = named; defer e.register.* = 0; runAction(e, t, action); @@ -984,10 +991,13 @@ fn shrinkSelToLineBounds(t: *Text, text: []const u8, range: modal.Selection) voi /// Whether a normal-mode role is the text's alone (`textAction`), or /// reaches past it: a view, a builtin, a prompt, a language server, the -/// look ring, the jump labels, a macro. -pub fn textRole(role: modal.Normal.Role) bool { +/// look ring, the jump labels, a macro. The tree-sitter walks are the +/// text's with a parse at hand (`tree`, `nodeTree`): a pane's file has +/// one, the library's caller may hand one in. +pub fn textRole(role: modal.Normal.Role, tree: bool) bool { return switch (role) { - .all_children, .all_siblings, .append_output, .command_line, .expand_node, .format, .goto_callstack, .goto_class, .goto_comment, .goto_declaration, .goto_definition, .goto_diagnostic, .goto_diagnostic_end, .goto_entry, .goto_function, .goto_implementation, .goto_parameter, .goto_references, .goto_test, .goto_type_definition, .goto_view_bottom, .goto_view_top, .goto_word, .goto_xml_element, .half_page_down, .half_page_up, .insert_output, .keep_pipe, .keep_regex, .leader, .macro_record, .macro_replay, .next_sibling, .page_down, .page_up, .parent_node_end, .parent_node_start, .pipe_selection, .pipe_selection_to, .prev_sibling, .remove_regex, .repeat_insert, .search, .search_next, .search_prev, .select_regex, .shrink_node, .split_regex, .view_bottom, .view_center, .view_middle, .view_scroll_down, .view_scroll_up, .view_top => false, + .all_children, .all_siblings, .expand_node, .goto_class, .goto_comment, .goto_entry, .goto_function, .goto_parameter, .goto_test, .goto_xml_element, .next_sibling, .parent_node_end, .parent_node_start, .prev_sibling, .shrink_node => tree, + .append_output, .command_line, .format, .goto_callstack, .goto_declaration, .goto_definition, .goto_diagnostic, .goto_diagnostic_end, .goto_implementation, .goto_references, .goto_type_definition, .goto_view_bottom, .goto_view_top, .goto_word, .half_page_down, .half_page_up, .insert_output, .keep_pipe, .keep_regex, .leader, .macro_record, .macro_replay, .page_down, .page_up, .pipe_selection, .pipe_selection_to, .remove_regex, .repeat_insert, .search, .search_next, .search_prev, .select_regex, .split_regex, .view_bottom, .view_center, .view_middle, .view_scroll_down, .view_scroll_up, .view_top => false, else => true, }; } @@ -1059,6 +1069,11 @@ pub fn textAction(e: Editor, t: *Text, a: modal.Normal.Action) edit.Error!void { return pointMove(t, text, range, modal.offsetAt(text, mc)); }, .match_inside, .match_around => return edit.textobjectSelect(e, t, text, a.char, a.role == .match_around), + inline .goto_function, .goto_class, .goto_parameter, .goto_comment, .goto_test, .goto_entry, .goto_xml_element => |role| { + const object = @field(modal.Normal.Object, @tagName(role)["goto_".len..]); + return objectJump(e, t, text, range, object, a.forward, a.count); + }, + inline .expand_node, .shrink_node, .next_sibling, .prev_sibling, .all_siblings, .all_children, .parent_node_end, .parent_node_start => |role| return nodeSelect(e, t, text, @field(modal.Normal.NodeWalk, @tagName(role))), .surround_add => return edit.surroundAdd(e, t, a.char), .surround_delete => return edit.surroundDelete(e, t, a.char), .surround_replace => return edit.surroundReplace(e, t, a.from, a.char), @@ -1175,7 +1190,7 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! pane.sel[sel_slot].state = .none; }; if (raw_selection and a.role == .yank) return edit.normalYank(p.editor(), t); - if (textRole(a.role)) return textAction(p.editor(), t, a); + if (textRole(a.role, true)) return textAction(p.editor(), t, a); edit.pinPaneCursor(p.editor(), t); const text = try edit.flatSurface(p.editor(), t); const range = t.primaryRange(text, 0); @@ -1222,10 +1237,6 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! if (set.hits.items.len == 0) return; set.goTo(pane, if (a.forward) set.hits.items.len - 1 else 0, false); }, - inline .goto_function, .goto_class, .goto_parameter, .goto_comment, .goto_test, .goto_entry, .goto_xml_element => |role| { - const object = @field(modal.Normal.Object, @tagName(role)["goto_".len..]); - return objectJump(p, pane, t, text, range, object, a.forward, a.count); - }, // These four move exactly one viewport unit, whatever the count. .half_page_down => return halfPageMove(t, text, range, true), .half_page_up => return halfPageMove(t, text, range, false), @@ -1234,7 +1245,6 @@ fn executeNormalAction(p: *Pardes, t: *Text, a: modal.Normal.Action) edit.Error! // s, S and | answer for the text they are pressed in; `/` searches // the body wherever it is pressed, as acme's Look from a tag does. inline .select_regex, .split_regex, .keep_regex, .remove_regex => |role| return startSelRegex(p, pane, t, @field(modal.Normal.RegexMode, @tagName(role)[0 .. @tagName(role).len - "_regex".len])), - inline .expand_node, .shrink_node, .next_sibling, .prev_sibling, .all_siblings, .all_children, .parent_node_end, .parent_node_start => |role| return nodeSelect(p, pane, t, @field(modal.Normal.NodeWalk, @tagName(role))), // Language shortcuts run the same builtins as tags and leader commands. .goto_definition => return exec.runBuiltin(p, .Def, v.active, "", null), .goto_references => return exec.runBuiltin(p, .Refs, v.active, "", null), diff --git a/test/hxlib.zig b/test/hxlib.zig index 423851d7..b6c1bfd3 100644 --- a/test/hxlib.zig +++ b/test/hxlib.zig @@ -4,8 +4,10 @@ //! against helix's goldens or the file pane (`zig build hxlib`). The //! library does what an app would with the actions it hands back that a //! case needs: s, S, K and Alt-K take the keys up to as their -//! pattern. A case that reaches any other action (a view, `:`, `/`, LSP, a -//! macro) is the app's from there: printed as skipped, with the role. +//! pattern, and the tree-sitter walks run on the app's parse (a case's text +//! has no grammar). A case that reaches any other action (a view, `:`, +//! `/`, LSP, a macro) is the app's from there: printed as skipped, with the +//! role. const std = @import("std"); const pe = @import("pardes-editor"); const hxkeys = @import("hxkeys.zig"); @@ -60,6 +62,9 @@ pub fn main(init: std.process.Init) !void { fn runCase(a: std.mem.Allocator, ed: *Ed, case: Case) ![]u8 { ed.* = .{}; try ed.load(case.text); + // the app's parse: a case's text has no grammar (no path), so the + // tree-sitter walks run and leave the ranges, as a file pane's do + var syn: pe.Syntax = .{}; var i: usize = 0; while (try hxkeys.next(pe.Key, case.keys, &i)) |k| { // a page key in insert mode moves a view, which the library has not @@ -67,7 +72,7 @@ fn runCase(a: std.mem.Allocator, ed: *Ed, case: Case) ![]u8 { return std.json.Stringify.valueAlloc(a, Skip{ .name = case.name, .skip = "insert page key" }, .{}); var call = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer call.deinit(); - switch (ed.key(call.allocator(), k)) { + switch (ed.key(call.allocator(), &syn, k)) { .done, .pending, .unbound => {}, .refused => |why| return std.json.Stringify.valueAlloc(a, Skip{ .name = case.name, .skip = @tagName(why) }, .{}), .action => |act| switch (act.role) { diff --git a/test/lib/bench.zig b/test/lib/bench.zig index f2127dc4..7e945064 100644 --- a/test/lib/bench.zig +++ b/test/lib/bench.zig @@ -34,10 +34,10 @@ pub fn main(init: std.process.Init) !void { var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); // to the middle, into insert mode - for ([_]pe.Key{ .{ .cp = '%', .text = "%" }, .{ .cp = ';', .text = ";" } }) |k| _ = ed.key(arena.allocator(), k); + for ([_]pe.Key{ .{ .cp = '%', .text = "%" }, .{ .cp = ';', .text = ";" } }) |k| _ = ed.key(arena.allocator(), null, k); var to_middle: [8]u8 = undefined; - for (std.fmt.bufPrint(&to_middle, "{d}G", .{text.items.len / 2 / 32}) catch unreachable) |c| _ = ed.key(arena.allocator(), .{ .cp = c, .text = &.{c} }); - _ = ed.key(arena.allocator(), .{ .cp = 'i', .text = "i" }); + for (std.fmt.bufPrint(&to_middle, "{d}G", .{text.items.len / 2 / 32}) catch unreachable) |c| _ = ed.key(arena.allocator(), null, .{ .cp = c, .text = &.{c} }); + _ = ed.key(arena.allocator(), null, .{ .cp = 'i', .text = "i" }); _ = arena.reset(.free_all); if (keys == 0) return; @@ -48,7 +48,7 @@ pub fn main(init: std.process.Init) !void { for (0..keys) |n| { if (count_pages) before.* = ed.*; const t0 = now(); - const out = ed.key(arena.allocator(), .{ .cp = 'a' + @as(u21, @intCast(n % 26)), .text = &.{'a' + @as(u8, @intCast(n % 26))} }); + const out = ed.key(arena.allocator(), null, .{ .cp = 'a' + @as(u21, @intCast(n % 26)), .text = &.{'a' + @as(u8, @intCast(n % 26))} }); key_ns += now() - t0; if (out != .done) return error.NotTyped; _ = arena.reset(.retain_capacity); diff --git a/test/lib/editor.zig b/test/lib/editor.zig index 412e5109..2b234cd8 100644 --- a/test/lib/editor.zig +++ b/test/lib/editor.zig @@ -20,7 +20,7 @@ fn typeKeys(ed: anytype, gpa: std.mem.Allocator, keys: []const u8) !void { // every call its own arena, gone after it: nothing of a key outlives it var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); - switch (ed.key(arena.allocator(), k)) { + switch (ed.key(arena.allocator(), null, k)) { .refused => return error.Refused, else => {}, } @@ -94,7 +94,7 @@ test "a key whose text would not fit is refused, and the value is as it was" { kept.* = ed.*; var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); - try std.testing.expectEqual(pe.Outcome{ .refused = .text_full }, ed.key(arena.allocator(), .{ .cp = 'c', .text = "c" })); + try std.testing.expectEqual(pe.Outcome{ .refused = .text_full }, ed.key(arena.allocator(), null, .{ .cp = 'c', .text = "c" })); try std.testing.expectEqualSlices(u8, std.mem.asBytes(kept), std.mem.asBytes(ed)); } @@ -107,16 +107,16 @@ test "what is not the text's comes back, and the caller can do it" { var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const a = arena.allocator(); - try std.testing.expectEqual(pe.Role.command_line, ed.key(a, .{ .cp = ':', .text = ":" }).action.role); - _ = ed.key(a, .{ .cp = '%', .text = "%" }); - try std.testing.expectEqual(pe.Role.select_regex, ed.key(a, .{ .cp = 's', .text = "s" }).action.role); + try std.testing.expectEqual(pe.Role.command_line, ed.key(a, null, .{ .cp = ':', .text = ":" }).action.role); + _ = ed.key(a, null, .{ .cp = '%', .text = "%" }); + try std.testing.expectEqual(pe.Role.select_regex, ed.key(a, null, .{ .cp = 's', .text = "s" }).action.role); _ = ed.selectRegex(a, "one", .select); var out: [pe.max_selections]pe.Selection = undefined; const got = try ed.ranges(a, &out); try std.testing.expectEqual(2, got.n); try std.testing.expectEqual(pe.Selection{ .anchor = 8, .head = 11 }, out[1]); try std.testing.expectEqual(pe.Mode.normal, ed.mode()); - _ = ed.key(a, .{ .cp = 'g', .text = "g" }); + _ = ed.key(a, null, .{ .cp = 'g', .text = "g" }); try std.testing.expectEqual(pe.Role.goto_prefix, ed.pending().?); } @@ -142,3 +142,39 @@ test "a language handed in at run time parses and colours the text" { try std.testing.expectEqual(pe.syntax.Syn.number, colors[17]); try std.testing.expectEqual(pe.syntax.Syn.none, colors[0]); } + +test "with a parse handed in, the tree-sitter walks run in the library; without, they are the caller's" { + const gpa = std.testing.allocator; + const ed = try gpa.create(Ed); + defer gpa.destroy(ed); + ed.* = .{}; + try ed.load("int f() { return 1 + 2; }\n"); + pe.syntax.start(gpa); + defer pe.syntax.stop(); + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const a = arena.allocator(); + const alt_o: pe.Key = .{ .cp = 'o', .alt = true }; + const alt_i: pe.Key = .{ .cp = 'i', .alt = true }; + try std.testing.expectEqual(pe.Role.expand_node, ed.key(a, null, alt_o).action.role); + var syn: pe.Syntax = .{ .lang = .{ .name = "mine", .ext = ".mine", .ts = tree_sitter_c(), .textobjects = "(function_definition body: (_) @function.inside) @function.around" } }; + defer syn.forget(); + for ("21l") |c| _ = ed.key(a, &syn, .{ .cp = c, .text = &.{c} }); + var out: [pe.max_selections]pe.Selection = undefined; + // `2`, then `1 + 2`, then `return 1 + 2;`; Alt-i goes back the way it + // came (helix's object_selections: not the first child, `1`) + for ([_]struct { pe.Key, pe.Selection }{ + .{ alt_o, .{ .anchor = 17, .head = 22 } }, + .{ alt_o, .{ .anchor = 10, .head = 23 } }, + .{ alt_i, .{ .anchor = 17, .head = 22 } }, + .{ alt_i, .{ .anchor = 21, .head = 22 } }, + }) |step| { + try std.testing.expectEqual(pe.Outcome.done, ed.key(a, &syn, step[0])); + _ = try ed.ranges(a, &out); + try std.testing.expectEqual(step[1], out[0]); + } + // the grammar's textobjects handed in: `maf`, the function around + for ("maf") |c| _ = ed.key(a, &syn, .{ .cp = c, .text = &.{c} }); + _ = try ed.ranges(a, &out); + try std.testing.expectEqual(pe.Selection{ .anchor = 0, .head = 25 }, out[0]); +} -- cgit v1.3