diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-17 07:44:55 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-17 12:15:01 -0300 |
| commit | 0db7861d9da09e059fa1b9e40fff5cd52add27f2 (patch) | |
| tree | 6e95dfa36e07b3234b1d5cdb990b11f95c184a3f /src/normal.zig | |
| parent | d3742ddf2b3a85eb3935cb35e958fa27f1293a6b (diff) | |
| parent | dee94c740bdaea61ff35b4e0a7f1d2815c9ee441 (diff) | |
| download | pardes-0db7861d9da09e059fa1b9e40fff5cd52add27f2.tar.gz pardes-0db7861d9da09e059fa1b9e40fff5cd52add27f2.zip | |
integration: the text pane a library (pardes-editor), with the GPU move, the terminal, the plumber and the diff work
A merge of pardes-next (wmrtztwl) and editor-lib (rlumrxuq), no conflicts. Gated against the baseline of the integration line (.scratch/sketch/gpu/mbase): the merge with the library before its follow-up, in full: frame corpus 77/77 identical in Debug and in ReleaseFast, the gated window -0.019% instructions (threshold 0.5%), unit-test on gui 1584/1592 with no failure the baseline has not; this merge: corpus 77/77 in Debug, unit-test on gui 1584/1592, on tui core-test 811/950 (139 skipped), shell-test 990/993, lib-test, hxdiff 658, parity 738, hxgolf 124, hxlib 538 and its parity 618, all 0 mismatches, replicas pass.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'src/normal.zig')
| -rw-r--r-- | src/normal.zig | 483 |
1 files changed, 279 insertions, 204 deletions
diff --git a/src/normal.zig b/src/normal.zig index dbd35fb5..70933607 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -14,21 +14,22 @@ 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 = @import("Editor.zig"); 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 { @@ -54,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, 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| { @@ -63,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); @@ -110,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) } @@ -219,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; @@ -242,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); @@ -267,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); @@ -278,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; @@ -306,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); } @@ -316,7 +329,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); @@ -342,7 +355,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); @@ -394,8 +407,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 = 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; @@ -437,14 +450,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 @@ -458,16 +471,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, t, insert_key), - }) catch |err| p.reportError(p.view().active, "edit", err); - if (p.multi_stop) break; + .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; if (i == pri) { after = KeyState.of(t); after_expl = t.vsel.explicit; } - const text = edit.flatSurface(p, 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)) }); @@ -477,19 +490,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, 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| { @@ -521,24 +534,55 @@ fn normalInput(key: Key) modal.Normal.Input { return out; } -pub fn handleNormal(p: *Pardes, 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 { // `"<reg>` 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; - p.view().register = named; - defer p.view().register = 0; + // the core's roles are the library's caller's + if (comptime Editor.lib) if (!textRole(action.role, e.syntax != null)) 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(p, t, action) catch |err| p.reportError(p.view().active, "edit", err); - replaySels(p, t, .{ .normal = action }); + 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, 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); @@ -548,18 +592,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); @@ -576,7 +620,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; @@ -591,16 +635,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)); @@ -609,9 +653,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 { @@ -804,7 +848,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; @@ -944,30 +989,35 @@ 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. 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, .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, }; - if (raw_selection and a.role == .yank) return edit.normalYank(p, t); - edit.pinPaneCursor(p, t); - const text = try edit.flatSurface(p, 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); switch (a.role) { .escape => { t.select = false; + if (comptime Editor.lib) return; // 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 => { @@ -990,43 +1040,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, 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(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, @@ -1037,37 +1061,24 @@ 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(e, t, a.char), // `mm` .match_prefix => { - const lines = try edit.paneCursorLines(p, 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, 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), - .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), - .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); - }, + .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(p, pane, t, text, range, object, a.forward, a.count); + 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), + .goto_paragraph => return t.setRange(text, 0, modal.moveParagraph(text, range, a.count, a.forward, t.select), false), + .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); @@ -1092,11 +1103,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, @@ -1106,7 +1112,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(e, t, where, a.count); }, .select_mode => { if (t.select) { @@ -1132,30 +1138,113 @@ 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, 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); + 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); + }, + // 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, 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), - .undo => return edit.undoStep(p, t, true), - .redo => return edit.undoStep(p, 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), @@ -1164,8 +1253,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, t, @intCast(a.count)), - .decrement => return edit.normalAdjustNumber(p, t, -@as(i64, @intCast(a.count))), .leader => if (p.macro.replaying == 0) { v.prefix = .leader; v.leader_n = 0; @@ -1196,18 +1283,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; @@ -1246,8 +1322,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) } } @@ -1332,12 +1407,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); @@ -1349,8 +1424,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); @@ -1453,19 +1528,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); } @@ -1476,9 +1551,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" } }); @@ -1491,10 +1566,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); } |
