//! Helix normal mode: a key read against the configured bindings becomes //! modal actions, replayed across every selection, and each action is done //! to the pane (a kind's pane takes its own keys first, Kind.key). const pardes = @import("pardes.zig"); const tagline = @import("tagline.zig"); const exec = @import("exec.zig"); const look = @import("look.zig"); const std = @import("std"); const regexp = @import("regexp.zig"); const syntax = @import("syntax.zig"); const modal = @import("modal.zig"); const panes = @import("panes.zig"); const edit = @import("edit.zig"); const config = @import("config.zig"); const keyboard = @import("keys.zig"); const Pane = panes.Pane; const Text = panes.Text; const Key = pardes.Key; const hit = pardes.hit; const sel_slot = pardes.sel_slot; const Pardes = pardes.Pardes; const Macro = pardes.Macro; 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; } fn regexMarker(mode: modal.Normal.RegexMode) []const u8 { return switch (mode) { .select => config.select_marker, .split => config.split_marker, .keep => config.keep_marker, .remove => config.remove_marker, }; } pub fn selRegexArmed(pane: *Pane) ?struct { pat: []const u8, mode: modal.Normal.RegexMode } { if (pane.prompt != .search or pane.nsel_snap == 0) return null; const armed = pane.input.own orelse ""; const mode: modal.Normal.RegexMode = for (std.enums.values(modal.Normal.RegexMode)) |m| { if (std.mem.startsWith(u8, armed, regexMarker(m))) break m; } else return null; const slash = std.mem.indexOfScalar(u8, armed, '/') orelse return null; return .{ .pat = armed[slash + 1 ..], .mode = mode }; } /// Select (or split on, keep or remove by) `pat` inside the selections `t` /// 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]; var out: [Text.max_selections]modal.Selection = undefined; var m: usize = 0; if (regexp.Regex.compile(pat)) |compiled| { var re = compiled; 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); for (snap) |r| { const from = @min(r.anchor, r.head); const to = @min(@max(r.anchor, r.head), text.len); if (from >= to) continue; if (mode == .keep or mode == .remove) { // helix keep_or_remove_matches: the range stays when a match // starts inside it (K), or when none does (Alt-K) const hit_at = re.find(hay_all, from, to, to) catch null; const found = if (hit_at) |h| h.start < to else false; if (found == (mode == .keep) and m < Text.max_selections) { out[m] = r; m += 1; } continue; } // Searched as sam searches, the way addr does (regexp.zig): the // text around the selection still says where its lines begin. var at = from; var piece = from; // split: where the next piece begins while (at < to and m < Text.max_selections) { // A search too slow to finish keeps what it found so far. const hit_at = (re.find(hay_all, at, to, to) catch break) orelse break; if (mode == .split) { out[m] = .{ .anchor = piece, .head = hit_at.start }; m += 1; piece = hit_at.end; } else if (hit_at.start != to) { out[m] = .{ .anchor = hit_at.start, .head = hit_at.end }; m += 1; } // an empty match would otherwise never advance at = if (hit_at.end > hit_at.start) hit_at.end else hit_at.end + 1; } if (mode == .split and piece < to and m < Text.max_selections) { out[m] = .{ .anchor = piece, .head = to }; m += 1; } } } else |_| {} if (m == 0) { // the text CAN move under an armed prompt (a tag chord runs a // builtin), and these are raw offsets into the surface as it was for (snap) |*r| { 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); } t.setRanges(text, out[0..m], &.{}, 0, true); // helix keeps primary 0 (its own TODO) } fn lastMatch(re: *SearchRegex, hay: []const u8, from: usize, to: usize) ?regexp.Regex.Match { var last: ?regexp.Regex.Match = null; var at = from; while (at <= to) { const found = re.find(hay, at, to) orelse break; last = found; at = if (found.end > found.start) found.end else modal.nextGrapheme(hay, found.end); if (at <= found.start) break; } return last; } // mvzr's word boundary is ASCII-only. Strip outer boundaries and check // them against Unicode characters for search-selection patterns. A pane's // Places keep one of these, compiled with the gpa, for as long as they live. pub const SearchRegex = struct { const Branch = struct { re: regexp.Regex, start_word: bool, end_word: bool }; branches: []Branch, pub fn compile(arena: std.mem.Allocator, pattern: []const u8) !SearchRegex { if (std.mem.indexOf(u8, pattern, "\\b") == null) { const branches = try arena.alloc(Branch, 1); branches[0] = try branch(pattern); return .{ .branches = branches }; } var branches: std.ArrayList(Branch) = .empty; errdefer branches.deinit(arena); var from: usize = 0; var depth: usize = 0; var escaped = false; var in_class = false; for (pattern, 0..) |c, i| { if (escaped) { escaped = false; continue; } if (c == '\\') { escaped = true; continue; } if (c == '[') in_class = true else if (c == ']') in_class = false; if (in_class) continue; if (c == '(') depth += 1 else if (c == ')') depth -|= 1; if (c == '|' and depth == 0) { try branches.append(arena, try branch(pattern[from..i])); from = i + 1; } } try branches.append(arena, try branch(pattern[from..])); for (branches.items) |*b| b.re.steps = regexp.Regex.budget / branches.items.len; return .{ .branches = try branches.toOwnedSlice(arena) }; } fn branch(pattern: []const u8) !Branch { var pat = pattern; const start = std.mem.startsWith(u8, pat, "\\b"); if (start) pat = pat[2..]; const end = std.mem.endsWith(u8, pat, "\\b") and !std.mem.endsWith(u8, pat, "\\\\b"); if (end) pat = pat[0 .. pat.len - 2]; return .{ .re = try regexp.Regex.compile(pat), .start_word = start, .end_word = end }; } pub fn find(self: *SearchRegex, hay: []const u8, from: usize, to: usize) ?regexp.Regex.Match { var best: ?regexp.Regex.Match = null; for (self.branches) |*b| { var at = from; while (at <= to) { const found = (b.re.find(hay, at, to, to) catch break) orelse break; if ((!b.start_word or modal.searchWordBefore(hay, found.start) != modal.searchWordAt(hay, found.start)) and (!b.end_word or modal.searchWordBefore(hay, found.end) != modal.searchWordAt(hay, found.end))) { if (best == null or found.start < best.?.start) best = found; break; } at = modal.nextGrapheme(hay, found.start); if (at <= found.start) break; } } return best; } }; pub fn appendSearchLiteral(out: *std.ArrayList(u8), arena: std.mem.Allocator, text: []const u8) !void { for (text) |c| { if (std.mem.indexOfScalar(u8, "\\^$.[]()|*+?{}", c) != null) try out.append(arena, '\\'); if (c == '\n') try out.appendSlice(arena, "\\n") else try out.append(arena, c); } } /// The file's parse, made on the first key that walks it after an edit and /// kept until the next: never made again for a key that changed nothing. pub fn fileTree(p: *Pardes, f: *panes.File.State) ?*anyopaque { if (f.node_tree == null or f.node_tree_revision != f.revision) { const old = f.node_tree; f.node_tree = syntax.parseTree(f.path, f.content, if (f.node_tree_edits == f.revision) old else null); if (old) |o| syntax.freeTree(o); f.node_tree_revision = f.revision; f.node_tree_edits = f.revision; for (f.node_history.items) |step| p.gpa.free(step.ranges); f.node_history.clearRetainingCapacity(); } return f.node_tree; } /// `]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; var last = range; for (0..count) |_| { const s = syntax.objectNext(f.path, tree, 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; } if (std.meta.eql(last, range)) return; if (t.select) { const head = if (last.head < range.anchor) last.anchor else last.head; return t.setRange(text, 0, .{ .anchor = range.anchor, .head = head }, false); } const out: modal.Selection = if (forward) last else .{ .anchor = last.head, .head = last.anchor }; 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; const expl = t.vsel.active and t.vsel.explicit; const arena = p.scratch.allocator(); 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); // back to what Alt-o grew from, while the selection still holds it const holds = for (prev.ranges) |pr| { const pf = @min(pr.anchor, pr.head); const pt = @max(pr.anchor, pr.head); if (for (rs[0..got.n]) |r| { if (@min(r.anchor, r.head) <= pf and pt <= @max(r.anchor, r.head)) break true; } else false) continue; break false; } else true; if (holds) return t.setRanges(text, prev.ranges, &.{}, prev.primary, expl); for (f.node_history.items) |step| p.gpa.free(step.ranges); f.node_history.clearRetainingCapacity(); }; const out = try arena.alloc(modal.Selection, Text.max_selections); const spans = try arena.alloc(syntax.Span, Text.max_selections); var m: usize = 0; for (rs[0..got.n]) |r| { if (m == out.len) break; const from = @min(r.anchor, r.head); const to = @max(r.anchor, r.head); const back = r.head < r.anchor; const n = syntax.walkNodes(tree, walk, from, to, modal.selectionCursor(text, r), spans[0 .. out.len - m]); if (n == 0) { out[m] = r; m += 1; continue; } for (spans[0..n]) |s| { out[m] = switch (walk) { .next_sibling => .{ .anchor = s.from, .head = s.to }, .prev_sibling => .{ .anchor = s.to, .head = s.from }, // helix move_parent_node_end: a one-character range on the // bound, or stretched to it in select mode .parent_node_end, .parent_node_start => bound: { const head = s.from; if (t.select) { const anchor = r.anchor; break :bound .{ .anchor = anchor, .head = if (head >= anchor) modal.nextGrapheme(text, head) else head }; } const next = modal.nextGrapheme(text, head); break :bound if (back) .{ .anchor = next, .head = head } else .{ .anchor = head, .head = next }; }, else => if (back) .{ .anchor = s.to, .head = s.from } else .{ .anchor = s.from, .head = s.to }, }; m += 1; } } const same = m == got.n and std.mem.eql(u8, std.mem.sliceAsBytes(out[0..m]), std.mem.sliceAsBytes(rs[0..m])); if (walk == .expand_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); } t.setRanges(text, out[0..m], &.{}, @min(got.pri, m - 1), expl); } /// `gw` (helix goto_word): label the words in view, nearest the cursor first, /// 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 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); const end = @min(modal.lineStartOffset(text, top + pane.rows), text.len); const letters = config.jump_label_alphabet.len; try pane.jump.resize(p.gpa, letters * letters); pane.jump.shrinkRetainingCapacity(modal.jumpWords(text, cursor, start, end, pane.jump.items)); pane.jump_first = null; } /// A key while `gw`'s labels are up: a label's first letter, then its /// second, which selects that word; anything else takes the labels away. pub fn jumpKey(p: *Pardes, pane: *Pane, t: *Text, key: Key) void { const letters = config.jump_label_alphabet; const at = if (key.ctrl or key.alt or key.cp > 0x7f) null else std.mem.indexOfScalar(u8, letters, @intCast(key.cp)); const i = at orelse return pane.jump.clearRetainingCapacity(); const first = pane.jump_first orelse { if (i * letters.len > pane.jump.items.len) return pane.jump.clearRetainingCapacity(); pane.jump_first = @intCast(i); return; }; const chosen = first * letters.len + i; 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); 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); const anchor = if (r.anchor < r.head) @min(r.anchor, @min(pr.anchor, pr.head)) else @max(r.anchor, @max(pr.anchor, pr.head)); t.setRange(text, 0, .{ .anchor = anchor, .head = r.head }, true); } const KeyState = struct { mode: Text.Mode, select: bool, normal: modal.Normal.State, find_op: ?modal.Normal.Find, find_ch: u21, restore_cursor: bool, reg_wait: bool, fn of(t: *Text) KeyState { return .{ .mode = t.mode, .select = t.select, .normal = t.normal, .find_op = t.find_op, .find_ch = t.find_ch, .restore_cursor = t.restore_cursor, .reg_wait = t.reg_wait, }; } fn into(s: KeyState, t: *Text) void { t.mode = s.mode; t.select = s.select; t.normal = s.normal; t.find_op = s.find_op; t.find_ch = s.find_ch; t.restore_cursor = s.restore_cursor; t.reg_wait = s.reg_wait; } }; /// what a replayed key does at each cursor const Replay = union(enum) { normal: modal.Normal.Action, insert: Key, }; pub fn replaySels(p: *Pardes, t: *Text, what: Replay) void { const id = 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; // the whole selection in text coordinates, document order. t.sels // is already ordered, so this only slots the primary into place. var list: [Text.max_selections]Text.SelRange = undefined; var n: usize = 0; var pri: usize = 0; const prim: Text.SelRange = .{ .row = t.cur_row, .col = t.cur_col, .arow = if (t.vsel.active) t.vsel.row else t.cur_row, .acol = if (t.vsel.active) t.vsel.col else t.cur_col, .sticky = t.sticky_col, }; const pr = Text.selStart(prim); var placed = false; for (t.sels[0..t.nsel]) |s| { const sr = Text.selStart(s); if (!placed and (pr.row < sr.row or (pr.row == sr.row and pr.col <= sr.col))) { pri = n; list[n] = prim; n += 1; placed = true; } list[n] = s; n += 1; } if (!placed) { pri = n; list[n] = prim; n += 1; } const saved = KeyState.of(t); const explicit = t.vsel.explicit; var after = saved; var after_expl = explicit; // each pass's result: cursor and anchor cells as distances from the // end of the surface text, plus the range's own j/k goal column var res: [Text.max_selections]struct { cur: usize, anc: usize, sticky: i32 } = undefined; p.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; passes += 1; saved.into(t); t.nsel = 0; // the handler underneath sees ONE selection t.cur_row = list[i].row; t.cur_col = list[i].col; t.vsel = .{ .active = list[i].arow != list[i].row or list[i].acol != list[i].col or t.select, .row = list[i].arow, .col = list[i].acol, .explicit = explicit, }; 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; if (i == pri) { after = KeyState.of(t); after_expl = t.vsel.explicit; } const text = edit.flatSurface(p, t) catch { p.multi_stop = true; break; }; const co = modal.offsetAt(text, .{ .row = @intCast(@max(0, t.cur_row)), .col = @intCast(@max(0, t.cur_col)) }); const ao = if (t.vsel.active) modal.offsetAt(text, .{ .row = @intCast(@max(0, t.vsel.row)), .col = @intCast(@max(0, t.vsel.col)) }) else co; res[i] = .{ .cur = text.len - @min(co, text.len), .anc = text.len - @min(ao, text.len), .sticky = t.sticky_col }; } p.multi_first = true; p.multi_index = 0; p.multi_count = 1; if (p.multi_stop) { p.multi_stop = false; if (owner != null) { const pn = p.panes[id] orelse return; if (pn.serial != serial) return; } t.nsel = 0; return; } const text = edit.flatSurface(p, t) catch |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| { rs[k] = Text.cellOffRange(text, text.len - @min(r.anc, text.len), text.len - @min(r.cur, text.len)); st[k] = r.sticky; } t.setRanges(text, rs[0..n], st[0..n], pri, after_expl); after.into(t); t.show(); // the view follows the PRIMARY, not the last pass } fn normalInput(key: Key) modal.Normal.Input { var out: modal.Normal.Input = .{ .cp = key.cp, .ctrl = key.ctrl, .alt = key.alt, }; inline for (std.enums.values(modal.Normal.Role)) |role| { const name = @tagName(role); const binding = @field(config, name); const matched = if (@TypeOf(binding) == comptime_int) isPrefix(key, binding) else if (@TypeOf(binding) == []const config.Chord) hit(key, binding) else @compileError("normal input binding has unsupported type: " ++ name); if (matched) out.roles.insert(role); } return out; } pub fn handleNormal(p: *Pardes, 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)); const action = switch (parsed) { .pending, .ignored, .unbound => return, .action => |value| value, }; t.normal.register = 0; p.view().register = named; defer p.view().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 }); } fn startSelRegex(p: *Pardes, pane: *Pane, t: *Text, mode: modal.Normal.RegexMode) edit.Error!void { const text = try edit.flatSurface(p, t); const got = t.ranges(text, 0, &pane.sel_snap); pane.nsel_snap = @intCast(got.n); pane.sel_snap_pri = @intCast(got.pri); pane.sel_snap_expl = t.vsel.active and t.vsel.explicit; panes.startPrompt(p, pane, t, .{ .search = regexMarker(mode) }); } /// 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"); 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); for (0..count) |_| { var ranges: [Text.max_selections]modal.Selection = undefined; const got = t.ranges(text, 0, &ranges); const old = ranges[got.pri]; const from = @min(old.anchor, old.head); const to = @max(old.anchor, old.head); var wrapped = false; const found = (if (forward) blk: { if (re.find(hay, to, hay.len)) |h| break :blk h; wrapped = true; break :blk re.find(hay, 0, hay.len); } else blk: { if (lastMatch(&re, hay, 0, from)) |h| break :blk h; wrapped = true; break :blk lastMatch(&re, hay, from, hay.len); }) orelse { p.setMessage(v.active, "no more matches"); return; }; if (found.end == 0) return; const next: modal.Selection = if (old.anchor > old.head) .{ .anchor = found.end, .head = found.start } else .{ .anchor = found.start, .head = found.end }; if (t.select and got.n < ranges.len) { ranges[got.n] = next; t.setRanges(text, ranges[0 .. got.n + 1], &.{}, got.n, true); } else { ranges[got.pri] = next; t.setRanges(text, ranges[0..got.n], &.{}, got.pri, true); } if (wrapped) p.setMessage(v.active, "wrapped around document"); } t.show(); } pub fn searchSelection(p: *Pardes, 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(); 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)); if (i > 0) try pattern.append(arena, '|'); if (boundary and modal.searchWordAt(text, from) and !modal.searchWordBefore(text, from)) try pattern.appendSlice(arena, "\\b"); 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; } 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, t); edit.pinPaneCursor(p, t); const text = try edit.flatSurface(p, t); const range = t.primaryRange(text, 0); const cur = modal.selectionCursor(text, range); switch (a.role) { .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); }, // gg and G: a count names the line; bare G is no move (helix) .goto_file_start, .goto_line => { if (!a.explicit and a.role == .goto_line) return; const to = if (a.explicit) @min(@as(usize, a.count) - 1, Text.maxLine(text)) else 0; return t.pointMove(text, range, modal.lineStartOffset(text, to)); }, .goto_last_line => return t.pointMove(text, range, modal.lineStartOffset(text, Text.maxLine(text))), .goto_line_start, .line_start => return t.pointMove(text, range, modal.lineStartOffset(text, modal.lineAtOffset(text, cur))), .goto_line_end, .line_end => { const line = modal.lineAtOffset(text, cur); const ls = modal.lineStartOffset(text, line); return t.pointMove(text, range, @max(ls, modal.prevGrapheme(text, modal.lineEndOffset(text, line)))); }, .goto_first_nonws, .line_first_nonws => { const line = modal.lineAtOffset(text, cur); const ls = modal.lineStartOffset(text, line); const slice = text[ls..modal.lineEndOffset(text, line)]; const nw = modal.firstNonWs(slice); if (nw == slice.len) return; return t.pointMove(text, range, ls + nw); }, .goto_line_down => return t.verticalMove(text, range, true, a.count, edit.paneWrapWidth(p, t)), .goto_line_up => return t.verticalMove(text, range, false, a.count, edit.paneWrapWidth(p, t)), .goto_column => { const line = modal.lineAtOffset(text, cur); const ls = modal.lineStartOffset(text, line); return t.pointMove(text, range, ls + modal.graphemeAtColumn(text[ls..modal.lineEndOffset(text, line)], @as(usize, a.count) - 1)); }, .goto_view_top => return t.gotoWindow(text, range, .top, a.count), .goto_view_bottom => return t.gotoWindow(text, range, .bottom, a.count), .goto_last_modification => { const at = t.last_edit orelse return; return t.pointMove(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, .find_char_back => .backward, .till_char_fwd => .till_forward, else => .till_backward, }; t.find_ch = a.char; return t.findMove(text, range, a.char, t.find_op.?, a.count); }, .replace_prefix => return edit.normalReplaceChar(p, t, a.char), // `mm` .match_prefix => { const lines = try edit.paneCursorLines(p, t); const mc = modal.matchBracket(lines, modal.positionAt(text, cur)) orelse return; return t.pointMove(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); }, 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); }, .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); return t.pointMove(text, range, target); }, .move_down => return t.verticalMove(text, range, true, a.count, 0), .move_up => return t.verticalMove(text, range, false, a.count, 0), inline .next_word_start, .prev_word_start, .next_word_end, .next_long_word_start, .prev_long_word_start, .next_long_word_end => |role| return t.wordMove(text, range, a.count, @field(modal.WordTarget, @tagName(role))), .repeat_find => { const kind = t.find_op orelse return; var repeated = range; var moved = false; for (0..a.count) |_| { const cc = modal.selectionCursor(text, repeated); const target = modal.findTarget(text, cc, t.find_ch, kind, 1) orelse break; repeated = if (t.select) modal.moveSelectionCursor(text, repeated, target, true) else modal.moveSelectionCursor(text, .{ .anchor = cc, .head = cc }, target, true); moved = true; } if (!moved) return; return t.setRange(text, 0, repeated, false); }, // These four move exactly one viewport unit, whatever the count. .half_page_down => return t.halfPageMove(text, range, true), .half_page_up => return t.halfPageMove(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, .append => .append, .insert_line_start => .line_start, .insert_line_end => .line_end, .open_below => .open_below, else => .open_above, }; return edit.enterInsert(p, t, where, a.count); }, .select_mode => { if (t.select) { t.select = false; } else { t.select = true; if (!t.vsel.active) { t.vsel = .{ .active = true, .row = t.cur_row, .col = t.cur_col, .explicit = true }; } else { t.vsel.explicit = true; } } t.cur_pinned = true; }, .select_line => return t.lineSelect(text, range, a.count), .select_line_bounds => return t.lineBoundsSelect(text, range), .shrink_to_line_bounds => return t.shrinkSelToLineBounds(text, range), .collapse_selection => return t.setRange(text, 0, .{ .anchor = cur, .head = cur }, false), .flip_selection => { const explicit = t.vsel.active and t.vsel.explicit; return t.setRange(text, 0, .{ .anchor = range.head, .head = range.anchor }, explicit); }, .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 t.multiSelAction(text, a.role, a.count), // 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), .goto_callstack => return exec.runBuiltin(p, .Callstack, v.active, "", null), .goto_declaration => return p.lspRequest(v.active, .declaration, ""), .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; }, // `:` is the one key a tag and a body do not share: it moves the // keyboard between them. .command_line => switch (t.what) { .tag => pane.focus = .body, .column, .workspace => tagline.exitHeader(p), .body, .input => tagline.enterTag(p, pane), }, .pipe_selection => return panes.startPrompt(p, pane, t, .{ .pipe = .replace }), .pipe_selection_to => return panes.startPrompt(p, pane, t, .{ .pipe = .ignore }), .insert_output => return panes.startPrompt(p, pane, t, .{ .pipe = .insert }), .append_output => return panes.startPrompt(p, pane, t, .{ .pipe = .append }), .keep_pipe => return panes.startPrompt(p, pane, t, .{ .pipe = .keep }), // `/` in a text is its query pane's line 1 (Query.zig); a // terminal's still asks on the notice band. .search => if (pane.file != null and t.what == .body) panes.Query.open(p, v.active, .text, "", true) else return panes.startPrompt(p, pane, &pane.body, .{ .search = config.search_marker }), // In a file's text, n and N step its places while they answer for // the register (Places.answersN); else helix's search of the register. // A kind's pane walks its `/`'s +Search (look.zig runSearch). .search_next, .search_prev => if (t.what == .body and pane.addon != null) return look.lookWalk(p, if (a.role == .search_next) 1 else -1) 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; } }, .goto_word => return startJump(p, pane, t), .macro_record => { const m = &p.macro; if (m.recording == 0) { m.recording = if (v.register != 0) v.register else '@'; m.recorded.clearRetainingCapacity(); return; } // the keys of this command (a count, `"`, the `Q`) are not // the macro's m.recorded.shrinkRetainingCapacity(m.recorded.items.len -| (m.command.items.len + 1)); const keys = try Macro.encode(p.gpa, m.recorded.items); defer p.gpa.free(keys); try p.registers.put(p.gpa, m.recording, keys, 0, 1, true); m.recording = 0; }, .macro_replay => { const name: u21 = if (v.register != 0) v.register else '@'; const notation = p.registers.value(name, 0) orelse return; const keys = try Macro.decode(p.scratch.allocator(), notation); v.register = 0; for (0..a.count) |_| keyboard.replayKeys(p, keys); }, .repeat_insert => { const m = &p.macro; if (m.last_insert.items.len == 0 or m.repeating) return; if (m.inserting) return; // the session is still open const keys = try p.scratch.allocator().dupe(Macro.Stored, m.last_insert.items); m.repeating = true; defer m.repeating = false; // helix repeat_last_insert: the command once, what was typed // count times, and out of insert mode the way it was left const typed = @min(m.typed_from, keys.len); keyboard.replayKeys(p, keys[0..typed]); if (keys.len == typed) return; 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 => {}, } } test "gj/gk step the wrapped rows a body draws while j/k keep the file's lines" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true }); defer p.deinit(); while (p.nextEffect()) |_| {} const long = &@as([400]u8, @splat('a')); const pane = try p.setTestFile(long ++ "\nsecond\n"); p.settings.wrap = true; const width = panes.File.wrapWidth(pane, true); try std.testing.expect(width > 4 and long.len > width * 3); // gj holds the column INSIDE the row and lands on the next break; the line // is one line the whole way down, which is the whole point. pane.body.cur_row = 0; pane.body.cur_col = 3; pane.body.sticky_col = -1; p.update(.{ .key = .{ .cp = 'g' } }); p.update(.{ .key = .{ .cp = 'j' } }); try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); try std.testing.expectEqual(@as(i32, @intCast(width + 3)), pane.body.cur_col); p.update(.{ .key = .{ .cp = 'g' } }); p.update(.{ .key = .{ .cp = 'j' } }); try std.testing.expectEqual(@as(i32, @intCast(width * 2 + 3)), pane.body.cur_col); p.update(.{ .key = .{ .cp = 'g' } }); p.update(.{ .key = .{ .cp = 'k' } }); try std.testing.expectEqual(@as(i32, @intCast(width + 3)), pane.body.cur_col); // A count is counted in rows, not lines. p.update(.{ .key = .{ .cp = '2' } }); p.update(.{ .key = .{ .cp = 'g' } }); p.update(.{ .key = .{ .cp = 'j' } }); try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); try std.testing.expectEqual(@as(i32, @intCast(width * 3 + 3)), pane.body.cur_col); // Plain j/k are untouched: one FILE line each, whatever the body drew. pane.body.cur_col = 3; pane.body.sticky_col = -1; p.update(.{ .key = .{ .cp = 'j' } }); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); p.update(.{ .key = .{ .cp = 'k' } }); try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); // The last row of a line steps into the next line's first row, and the // first row steps back onto the previous line's LAST row. pane.body.cur_row = 0; pane.body.cur_col = @intCast(long.len - 1); pane.body.sticky_col = -1; p.update(.{ .key = .{ .cp = 'g' } }); p.update(.{ .key = .{ .cp = 'j' } }); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); pane.body.cur_col = 0; pane.body.sticky_col = -1; p.update(.{ .key = .{ .cp = 'g' } }); p.update(.{ .key = .{ .cp = 'k' } }); try std.testing.expectEqual(@as(i32, 0), pane.body.cur_row); try std.testing.expect(pane.body.cur_col >= @as(i32, @intCast(long.len - long.len % width))); // Wrap OFF: a line is one visual row, so gj/gk ARE j/k again. p.settings.wrap = false; pane.body.cur_row = 0; pane.body.cur_col = 3; pane.body.sticky_col = -1; p.update(.{ .key = .{ .cp = 'g' } }); p.update(.{ .key = .{ .cp = 'j' } }); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); } test "flat text movement and selection replay need no scratch rows" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 }); defer p.deinit(); const row_text = "one (two) λ\r\n"; const text = try gpa.alloc(u8, 4096 * row_text.len); defer gpa.free(text); for (0..4096) |row| @memcpy(text[row * row_text.len ..][0..row_text.len], row_text); const pane = try p.setTestFile(text); _ = try panes.File.lineIndex(gpa, &pane.file.?); var denied = std.testing.FailingAllocator.init(gpa, .{ .fail_index = 0 }); p.scratch.deinit(); p.scratch = .init(denied.allocator()); pane.body.cur_row = 4094; handleNormal(p, &pane.body, .{ .cp = 'l' }); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); handleNormal(p, &pane.body, .{ .cp = 'j' }); try std.testing.expectEqual(@as(i32, 4095), pane.body.cur_row); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_col); handleNormal(p, &pane.body, .{ .cp = 'h' }); try std.testing.expectEqual(@as(i32, 0), pane.body.cur_col); try executeNormalAction(p, &pane.body, .{ .role = .match_inside, .char = 'w' }); try std.testing.expectEqual(@as(i32, 2), pane.body.cur_col); try std.testing.expectEqual(@as(i32, 0), pane.body.vsel.col); pane.body.vsel.active = false; pane.body.cur_row = 1024; pane.body.cur_col = 0; 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' }); 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); try std.testing.expectEqual(@as(i32, 3073), pane.body.sels[0].row); try std.testing.expectEqual(@as(i32, 1), pane.body.sels[0].col); try std.testing.expect(!denied.has_induced_failure); try std.testing.expectEqual(@as(usize, 0), p.scratch.queryCapacity()); pane.body.nsel = 0; pane.body.cur_col = 4; try std.testing.expectError(error.OutOfMemory, executeNormalAction(p, &pane.body, .{ .role = .match_prefix })); try std.testing.expect(denied.has_induced_failure); try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col); denied.fail_index = std.math.maxInt(usize); try executeNormalAction(p, &pane.body, .{ .role = .match_prefix }); try std.testing.expectEqual(@as(i32, 8), pane.body.cur_col); } test "s and S search a multi-line selection as addr does: ^ and $ per line, . within one" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 }); defer p.deinit(); const text = "alpha x\nbeta alpha\nalphabet\n"; const pane = try p.setTestFile(text); const Case = struct { pat: []const u8, mode: modal.Normal.RegexMode, want: []const [2]usize }; for ([_]Case{ // ^ at each line's start, not only the selection's .{ .pat = "^alpha", .mode = .select, .want = &.{ .{ 0, 5 }, .{ 19, 24 } } }, // $ at each line's end .{ .pat = "alpha$", .mode = .select, .want = &.{.{ 13, 18 }} }, // . stops at the newline: one selection per line, not one for all .{ .pat = "a.*", .mode = .select, .want = &.{ .{ 0, 7 }, .{ 11, 18 }, .{ 19, 27 } } }, // S splits on a line's end .{ .pat = "$", .mode = .split, .want = &.{ .{ 0, 7 }, .{ 7, 18 }, .{ 18, 27 }, .{ 27, 28 } } }, }) |c| { pane.sel_snap[0] = .{ .anchor = 0, .head = text.len }; pane.nsel_snap = 1; applySelRegex(p, pane, &pane.body, c.pat, c.mode); var out: [Text.max_selections]modal.Selection = undefined; const got = pane.body.ranges(text, 0, &out); try std.testing.expectEqual(c.want.len, got.n); for (c.want, out[0..got.n]) |w, r| { try std.testing.expectEqual(w[0], @min(r.anchor, r.head)); try std.testing.expectEqual(w[1], @max(r.anchor, r.head)); } } } test "tree-sitter selection keys do in a JSON file what hx 25.07.1 does" { if (!syntax.supportsPath("a.json")) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); const text = "{\"a\": [1, 2, 3], \"b\": true}\n"; // each checked against the installed hx through a pty: the keys, then // the text it saved const Case = struct { keys: []const u8, want: []const u8 }; for ([_]Case{ .{ .keys = "10l\x1bo" ++ "d", .want = "{\"a\": , \"b\": true}\n" }, .{ .keys = "10l\x1bo\x1bod", .want = "{, \"b\": true}\n" }, .{ .keys = "10l\x1bo\x1bo\x1bod", .want = "\n" }, .{ .keys = "10l\x1bo\x1bIix\x1b", .want = "{\"a\": [x1, x2, x3], \"b\": true}\n" }, .{ .keys = "10l\x1bo\x1bo\x1b>d", .want = "{\"a\": [1, 2, 3] \"b\": true}\n" }, .{ .keys = "10l\x1bpd", .want = "{\"a\": [1 2, 3], \"b\": true}\n" }, .{ .keys = "10l\x1baix\x1b", .want = "{\"a\": [x1, x2, x3], \"b\": true}\n" }, .{ .keys = "10l\x1bo\x1bo\x1bid", .want = "{\"a\": , \"b\": true}\n" }, .{ .keys = "6lx\x1bid", .want = "\n" }, .{ .keys = "10l\x1beiX\x1b", .want = "{\"a\": [1, 2X, 3], \"b\": true}\n" }, .{ .keys = "10l\x1bb\x1bbiX\x1b", .want = "{X\"a\": [1, 2, 3], \"b\": true}\n" }, // insert Tab after text leaves the node (smart tab) .{ .keys = "8li\tX\x1b", .want = "{\"a\": [1, 2, 3]X, \"b\": true}\n" }, }) |c| { const pane = try p.setTestFile(text); p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, "/test.json"); // ESC before a key is Alt on it; a lone ESC is Esc; `>` is Alt-right var i: usize = 0; while (i < c.keys.len) : (i += 1) { const ch = c.keys[i]; if (ch == 0x1b and i + 1 < c.keys.len) { i += 1; const k = c.keys[i]; p.update(.{ .key = if (k == '>') .{ .cp = Key.right, .alt = true } else .{ .cp = k, .alt = true } }); } else if (ch == 0x1b) { p.update(.{ .key = .{ .cp = Key.escape } }); } else if (ch == '\t') { p.update(.{ .key = .{ .cp = Key.tab } }); } else p.update(.{ .key = .{ .cp = ch, .text = c.keys[i..][0..1] } }); while (p.nextEffect()) |_| {} } std.testing.expectEqualStrings(c.want, pane.file.?.content) catch |err| { std.debug.print("keys {s}\n", .{c.keys}); return err; }; } } test "one cursor holds no room for other ranges; a second range makes it and one again gives it back" { const gpa = std.testing.allocator; 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 }); try std.testing.expectEqual(@as(usize, 0), pane.body.sels.len); handleNormal(p, &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 try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); handleNormal(p, &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 try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); try std.testing.expectEqual(@as(usize, 0), pane.body.sels.len); } test "cursors that land on one place are one: a key typed there is typed once, as helix merges them" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 }); 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' }); try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); handleNormal(p, &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" } }); try std.testing.expectEqualStrings("xab\ncd\n", pane.file.?.content); } test "r and Delete take whole graphemes" { const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 }); 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 = '界' }); try std.testing.expectEqualStrings("A界界界界Z\n", pane.file.?.content); for ("u0li") |c| handleNormal(p, &pane.body, .{ .cp = c }); p.update(.{ .key = .{ .cp = Key.delete } }); try std.testing.expectEqualStrings("A" ++ "👩🏽\u{200d}🚀" ++ "🇧🇷" ++ "界" ++ "Z\n", pane.file.?.content); } test "tree-sitter textobject keys do in Python, JSON and Zig what hx 25.07.1 does" { if (!syntax.supportsPath("a.py") or !syntax.supportsPath("a.json") or !syntax.supportsPath("a.zig")) return; const gpa = std.testing.allocator; const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); defer p.deinit(); // each checked against the installed hx through a pty: the keys, then // the text it saved const Case = struct { path: []const u8, text: []const u8, keys: []const u8, want: []const u8 }; for ([_]Case{ .{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "]fd", .want = "def alpha(a, b):\n return a + b\n\n\n\n\n\ndef test_one():\n assert beta(1) == 1\n" }, .{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "]f]fd", .want = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\n\n" }, .{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "2]fd", .want = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\n\n" }, .{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "Gk[fd", .want = "ef alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n" }, .{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "jmifd", .want = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n" }, .{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "jmafd", .want = "\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n" }, .{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "10lmiad", .want = "def alpha(, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n" }, .{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "10lmaad", .want = "def alpha( b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n" }, .{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "]Td", .want = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\n\n" }, .{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "]cd", .want = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n \n return c\n\n\ndef test_one():\n assert beta(1) == 1\n" }, .{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "v]fd", .want = "\n\n\ndef test_one():\n assert beta(1) == 1\n" }, .{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "]td", .want = "ef alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n" }, .{ .path = "/test.py", .text = "def alpha(a, b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n", .keys = "]ad", .want = "def alpha( b):\n return a + b\n\n\ndef beta(c):\n # note\n return c\n\n\ndef test_one():\n assert beta(1) == 1\n" }, .{ .path = "/test.json", .text = "{\"a\": 1, \"b\": [1, 2]}\n", .keys = "]ed", .want = "{, \"b\": [1, 2]}\n" }, .{ .path = "/test.json", .text = "{\"a\": 1, \"b\": [1, 2]}\n", .keys = "]e]ed", .want = "{\"a\": 1, }\n" }, .{ .path = "/test.json", .text = "{\"a\": 1, \"b\": [1, 2]}\n", .keys = "8lmaed", .want = "{\"a\": 1,\"b\": [1, 2]}\n" }, // Zig: the query is helix's, ported to pardes's zig grammar. No case // walks call arguments: the reference helix counts them as // parameters and the installed 25.07.1's query does not. .{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "]fd", .want = "const std = @import(\"std\");\n\n/// adds\n\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" }, .{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "5jmifd", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 \n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" }, .{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "5jmafd", .want = "const std = @import(\"std\");\n\n/// adds\n\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" }, .{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "]td", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\n\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" }, .{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "9jmitd", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" }, .{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "9jmatd", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\n\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" }, .{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "]Td", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\n\n" }, .{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "16jmiTd", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" \n" }, .{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "3j11lmiad", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" }, .{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "3j11lmaad", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add( b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" }, .{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "]cd", .want = "const std = @import(\"std\");\n\n\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" }, .{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "4jmacd", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" }, .{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "16jf2[ad", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, ) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" }, .{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "16j[fd", .want = "const std = @import(\"std\");\n\n/// adds\n\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" }, .{ .path = "/test.zig", .text = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\nconst Color = enum { red, green };\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n", .keys = "]t]td", .want = "const std = @import(\"std\");\n\n/// adds\npub fn add(a: u32, b: u32) u32 {\n // sum\n return a + b;\n}\n\nconst Point = struct {\n x: i32,\n y: i32,\n};\n\n\n\ntest \"add works\" {\n try std.testing.expectEqual(@as(u32, 3), add(1, 2));\n}\n" }, }) |c| { const pane = try p.setTestFile(c.text); p.gpa.free(pane.file.?.path); pane.file.?.path = try p.gpa.dupe(u8, c.path); for (c.keys, 0..) |ch, i| { p.update(.{ .key = .{ .cp = ch, .text = c.keys[i..][0..1] } }); while (p.nextEffect()) |_| {} } std.testing.expectEqualStrings(c.want, pane.file.?.content) catch |err| { std.debug.print("keys {s} on {s}\n", .{ c.keys, c.path }); return err; }; } }