From 13d5613b77c62c425c3a124a34c0c2528cc6251f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 8 Oct 2026 12:00:28 -0300 Subject: Follow Helix search registers for n/N; keep Look navigation as named builtins --- src/CHANGELOG.md | 6 ++ src/Registers.zig | 1 + src/builtins.zig | 32 ++++++++--- src/config.zig | 4 ++ src/look.zig | 14 ++++- src/modal.zig | 23 +++++++- src/normal.zig | 168 ++++++++++++++++++++++++++++++++++++++++++++++++++++-- src/pdf_view.zig | 2 +- src/tutor.txt | 7 ++- 9 files changed, 234 insertions(+), 23 deletions(-) (limited to 'src') diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index ce2cedc8..e15faca7 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## Unreleased + +- n/N follow Helix search registers, counts, wrapping and select mode. + `*` sets a search from the selection; `Alt-*` omits word boundaries. + The location ring remains as LookNext/LookPrev (Space j n/p). + ## 0.23 - A file a language server speaks for (by its extension) has `Def` and diff --git a/src/Registers.zig b/src/Registers.zig index d2a42434..3f2486cd 100644 --- a/src/Registers.zig +++ b/src/Registers.zig @@ -9,6 +9,7 @@ const std = @import("std"); const Registers = @This(); list: std.ArrayList(Reg) = .empty, +last_search: u21 = '/', pub const Reg = struct { name: u21, diff --git a/src/builtins.zig b/src/builtins.zig index c1424b2f..ef769b48 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -744,15 +744,15 @@ pub const Restore = struct { // so a Restore that could never happen spends no warning. if (comptime pardes.hosted) { const bytes = @import("fs.zig").readRestore(c.p.gpa, path, c.p.settings.dump_dir.get()) catch |err| { - var buf: [limits.host_path_cap + 64]u8 = undefined; - var words: [128]u8 = undefined; - const why = switch (err) { - error.FileNotFound => "no such file", - error.PermissionDenied => "permission denied", - error.IsDirectory => "a directory, not a dump", - else => pardes.Messages.errorWords(err, &words), - }; - return c.p.reportFailure(c.id, std.fmt.bufPrint(&buf, "Restore: {s}: {s}", .{ path, why }) catch "Restore: cannot read the dump"); + var buf: [limits.host_path_cap + 64]u8 = undefined; + var words: [128]u8 = undefined; + const why = switch (err) { + error.FileNotFound => "no such file", + error.PermissionDenied => "permission denied", + error.IsDirectory => "a directory, not a dump", + else => pardes.Messages.errorWords(err, &words), + }; + return c.p.reportFailure(c.id, std.fmt.bufPrint(&buf, "Restore: {s}: {s}", .{ path, why }) catch "Restore: cannot read the dump"); }; defer c.p.gpa.free(bytes); // Nor does a file that is not a dump, before any warning. @@ -1837,6 +1837,20 @@ pub const Forward = struct { } }; +/// Select the next Look location across panes; Enter opens it. +pub const LookNext = struct { + pub fn run(c: Ctx) void { + look.lookWalk(c.p, 1); + } +}; + +/// Select the previous Look location across panes; Enter opens it. +pub const LookPrev = struct { + pub fn run(c: Ctx) void { + look.lookWalk(c.p, -1); + } +}; + /// Go back to the last place jumped from in another pane. pub const Last = struct { pub fn run(c: Ctx) void { diff --git a/src/config.zig b/src/config.zig index c2f51b36..fb34b746 100644 --- a/src/config.zig +++ b/src/config.zig @@ -47,6 +47,8 @@ pub const leader_path = paths: { .Callees = "lC", .Supertypes = "lt", .Subtypes = "lT", + .LookNext = "jn", + .LookPrev = "jp", .Del = "d", .DelAbove = null, .DelBelow = null, @@ -331,6 +333,8 @@ pub const command_line: []const Chord = &.{.{ .cp = ':' }}; pub const search: []const Chord = &.{.{ .cp = '/' }}; pub const search_next: []const Chord = &.{.{ .cp = 'n' }}; pub const search_prev: []const Chord = &.{.{ .cp = 'N' }}; +pub const search_selection: []const Chord = &.{.{ .cp = '*', .alt = true }}; +pub const search_selection_word: []const Chord = &.{.{ .cp = '*' }}; pub const pipe_selection: []const Chord = &.{.{ .cp = '|' }}; pub const pipe_selection_to: []const Chord = &.{.{ .cp = '|', .alt = true }}; pub const insert_output: []const Chord = &.{.{ .cp = '!' }}; diff --git a/src/look.zig b/src/look.zig index 6ba6a8d0..5795979f 100644 --- a/src/look.zig +++ b/src/look.zig @@ -542,7 +542,10 @@ pub fn submitSearch(p: *Pardes, id: usize) void { const pane = p.panes[id] orelse return; if (normal.selRegexArmed(pane)) |a| { // helix keeps the pattern in `/` - if (a.pat.len > 0) p.registers.put(p.gpa, '/', a.pat, 0, 1, true); + if (a.pat.len > 0) { + p.registers.put(p.gpa, '/', a.pat, 0, 1, true); + p.registers.last_search = '/'; + } return if (p.promptTarget(pane)) |t| normal.applySelRegex(p, pane, t, a.pat, a.mode); } const armed = pane.promptText() orelse return; @@ -556,7 +559,13 @@ pub fn submitSearch(p: *Pardes, id: usize) void { else .text; _ = runSearch(p, id, armed[slash + 1 ..], kind, .top, true) catch |err| return p.reportError(id, "search", err); - if (kind == .text) lookFirstHit(p, id); + if (kind == .text) { + var pattern: std.ArrayList(u8) = .empty; + normal.appendSearchLiteral(&pattern, p.scratch.allocator(), armed[slash + 1 ..]) catch return; + p.registers.put(p.gpa, '/', pattern.items, 0, 1, true); + p.registers.last_search = '/'; + lookFirstHit(p, id); + } } fn lookFirstHit(p: *Pardes, id: usize) void { @@ -2752,7 +2761,6 @@ test "Look on a diff under each git prefix opens the repository's file, and a re } } - test "Look on a diff line is the look of the address it names, selected by hand: a cached patch, the checkout elsewhere" { if (!platform_has_fs) return; const io = std.testing.io; diff --git a/src/modal.zig b/src/modal.zig index 316a66fa..548524ae 100644 --- a/src/modal.zig +++ b/src/modal.zig @@ -157,6 +157,8 @@ pub const Normal = struct { search, search_next, search_prev, + search_selection, + search_selection_word, }; pub const Input = struct { @@ -355,7 +357,8 @@ pub const Normal = struct { command_line, pipe_selection: PipeBehavior, search, - search_step: Direction, + search_step: struct { direction: Direction, count: u32 }, + search_selection: bool, goto_word, macro_record, macro_replay: u32, @@ -373,6 +376,7 @@ pub const Normal = struct { .pipe_selection, .search, .search_step, + .search_selection, .macro_record, .macro_replay, .node, @@ -676,8 +680,10 @@ pub const Normal = struct { if (key.has(.macro_replay)) return resultAction(.{ .macro_replay = count }); if (key.has(.repeat_insert)) return resultAction(.{ .repeat_insert = count }); if (key.has(.search)) return resultAction(.search); - if (key.has(.search_next)) return resultAction(.{ .search_step = .forward }); - if (key.has(.search_prev)) return resultAction(.{ .search_step = .backward }); + if (key.has(.search_selection)) return resultAction(.{ .search_selection = false }); + if (key.has(.search_selection_word)) return resultAction(.{ .search_selection = true }); + if (key.has(.search_next)) return resultAction(.{ .search_step = .{ .direction = .forward, .count = count } }); + if (key.has(.search_prev)) return resultAction(.{ .search_step = .{ .direction = .backward, .count = count } }); return .unbound; } @@ -1420,6 +1426,17 @@ fn wordClassAt(text: []const u8, off: usize) WordClass { }; } +pub fn searchWordAt(text: []const u8, off: usize) bool { + return off < text.len and wordClassAt(text, off) == .word; +} + +pub fn searchWordBefore(text: []const u8, off: usize) bool { + if (off == 0) return false; + var previous = off - 1; + while (previous > 0 and text[previous] & 0xc0 == 0x80) previous -= 1; + return searchWordAt(text, previous); +} + fn isWordWhitespace(c: WordClass) bool { // Rust char::is_whitespace (includes line endings) return c == .ws or c == .eol; } diff --git a/src/normal.zig b/src/normal.zig index aec6b983..fad1836b 100644 --- a/src/normal.zig +++ b/src/normal.zig @@ -168,6 +168,168 @@ pub fn applySelRegex(p: *Pardes, pane: *Pane, t: *Text, pat: []const u8, mode: m t.setRanges(text, out[0..m], &.{}, 0, true); // helix keeps primary 0 (its own TODO) } +/// 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, direction: modal.Normal.Direction, count: u32) void { + const name = if (p.register != 0) p.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(p.active, "invalid search pattern"); + return; + }; + var hay = text; + if (for (pat) |c| { + if (std.ascii.isUpper(c)) break false; + } else true) { + const lower = p.scratch.allocator().dupe(u8, text) catch return; + for (lower) |*c| c.* = std.ascii.toLower(c.*); + hay = lower; + } + 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 (direction == .forward) blk: { + if (tryFind(&re, hay, to, hay.len)) |h| break :blk h; + wrapped = true; + break :blk tryFind(&re, 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(p.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(p.active, "wrapped around document"); + } + t.show(); +} + +fn tryFind(re: *SearchRegex, hay: []const u8, from: usize, to: usize) ?regexp.Regex.Match { + return re.find(hay, @min(from, hay.len), to); +} + +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 = tryFind(re, 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; +} + +pub fn searchSelection(p: *Pardes, t: *Text, text: []const u8, boundary: bool) 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) pattern.append(arena, '|') catch return; + if (boundary and modal.searchWordAt(text, from) and !modal.searchWordBefore(text, from)) pattern.appendSlice(arena, "\\b") catch return; + appendSearchLiteral(&pattern, arena, text[from..to]) catch return; + if (boundary and to < text.len and modal.searchWordBefore(text, to) and !modal.searchWordAt(text, to)) pattern.appendSlice(arena, "\\b") catch return; + } + const name = if (p.register != 0) p.register else '/'; + p.registers.put(p.gpa, name, pattern.items, 0, 1, true); + p.registers.last_search = name; +} + +// mvzr's word boundary is ASCII-only. Strip outer boundaries and check +// them against Unicode characters for search-selection patterns. +const SearchRegex = struct { + const Branch = struct { re: regexp.Regex, start_word: bool, end_word: bool }; + branches: []Branch, + + fn compile(arena: std.mem.Allocator, pattern: []const u8) !SearchRegex { + 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; + 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 = branches.items }; + } + + 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 }; + } + + 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 { @@ -766,10 +928,8 @@ fn executeNormalAction(p: *Pardes, t: *Text, semantic: modal.Normal.Action) void }, .pipe_selection => |how| return p.startPrompt(pane, t, .{ .pipe = how }), .search => return p.startPrompt(pane, &pane.body, .{ .search = config.search_marker }), - .search_step => |direction| return look.lookWalk( - p, - if (direction == .forward) @as(i32, 1) else -1, - ), + .search_step => |step| return searchStep(p, t, text, step.direction, step.count), + .search_selection => |boundary| return searchSelection(p, t, text, boundary), .node => |walk| return nodeSelect(p, pane, t, walk), .goto_word => return startJump(p, pane, t), .object_jump => |jump| return objectJump(p, pane, t, text, range, jump.object, jump.direction == .forward, jump.count), diff --git a/src/pdf_view.zig b/src/pdf_view.zig index d5769ad3..567117bb 100644 --- a/src/pdf_view.zig +++ b/src/pdf_view.zig @@ -1843,7 +1843,7 @@ pub fn applyNormal( .leader => result.host = .leader, .command_line => result.host = .command_line, .search => result.host = .search, - .search_step => |direction| result.host = if (direction == .forward) + .search_step => |step| result.host = if (step.direction == .forward) .search_forward else .search_backward, diff --git a/src/tutor.txt b/src/tutor.txt index 7492b058..8f5cf241 100644 --- a/src/tutor.txt +++ b/src/tutor.txt @@ -97,7 +97,7 @@ 1. `Look` :20 here: the cursor goes to line 20 of this pane. 2. `Look` :/UNSAVED/ to go to the next match of UNSAVED. 3. Press /, type keys, press Enter: a +Search lists the lines with - keys and the cursor goes to the first. n and N step through. + keys and the cursor goes to the first. n and N select search matches. -> Guide: Look @@ -256,7 +256,8 @@ typed | filter every selection through the shell / case-insensitive SUBSTRING search, one hit a line; the regex lives on s and S - n / N the next/previous text `Look` would open, as above + n / N next/previous search match (Helix); v adds matches + SPC j n/p `LookNext`/`LookPrev`: select locations; Enter opens Ctrl-c comment or uncomment the lines VIEWPORT @@ -341,7 +342,7 @@ typed SPC is the leader (SPC ? is `Help`) vs HELIX selection is LINE-first (x), v for characters; / is a - substring search; n/N walk what `Look` would open. + substring search; n/N repeat it in the current text. vs VIM no verb+noun: the motion already selected, so wd is what dw was; Esc goes back a pane; bare G does nothing. vs BOTH a terminal is just a pane, and the session can outlive -- cgit v1.3