From abe3817e8dd0af41e6b5786bdbeb631219b58c23 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 20:33:01 -0300 Subject: Prompt: a body's text prompts ask in its tag's head (walk UI, pick-ui SPEC.md §7.1, §7.2, item 1 of line E): `s S K A-K | A-| ! A-! $` from a body are a typing state of the view's tag (TagState.Kind.prompt, its state Prompt.zig, its field A's Field), drawn after the prefix in place of the tag's own text (R1): box `^`, the prompt's key cell, the field, the plain word it stands for (`= Exec Edit x/self/`, `Edit g/re/`, `Edit |tr a-z A-Z`, `Edit >cmd`; none for `! A-! $`), its count (`2 selections in 3 lines`, `keeps 1 of 2`, `0` for no match, the selections it began with back), the hints; the live machinery as it was (normal.applySelRegex, now returning what it found; the pipe off the loop, Pipe.submit split from the notice band's submitPipe); a pattern that is no regex changes nothing, the last result drawn dimmed (body_layer) and the reason at the count's place in the error ink (TagState.Style.err, regexp's message); Up/Down recall the history inline, Ctrl-r unrolls it as a band step filtered by the field (three session histories, Pardes.prompt_history: search and select's, the pipes', the command line's, 16 lines each, in the digest and the dump); Esc and Backspace on an empty field put the body back; Enter keeps the line in its history and the pattern in `/`, the command in `|`; a paste goes into the field; a prompt for a tag's or a header's text, Save's path, a terminal's `/` still ask on the notice band; wire 37; TEST FIRST: Prompt.zig "s asks in the tag's head ..." and "Enter keeps what s found ... a pipe from the body asks in the tag and runs off the loop"; Pipe.zig's and panes.zig's prompt tests and test/behaviour/keys.zig's two read the head; goldens pipe, selregex, msg (the prompt in the tag head, no chip); core-test 1014/1180 (166 skipped), shell-test 1227/1230, pane-test 182/184 (the 1 failure A's: `SPC h ?` is Help in the tag now), behaviour-test 274/277 (the 3 failures A's: window mode's head, a struck leader key), process-test the 6 of A's report plus none of mine, term-test 17/17, kitty-test 45/45 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- core/keys.zig | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) (limited to 'core/keys.zig') diff --git a/core/keys.zig b/core/keys.zig index 6f43e166..6ffca8e1 100644 --- a/core/keys.zig +++ b/core/keys.zig @@ -20,6 +20,7 @@ const Pipe = @import("Pipe.zig"); const Registers = @import("Registers.zig"); const bindings = @import("bindings.zig"); const TagState = @import("TagState.zig"); +const Prompt = @import("Prompt.zig"); const Pardes = pardes.Pardes; const Pane = panes.Pane; const Text = panes.Text; @@ -360,8 +361,9 @@ pub fn handleKey(p: *Pardes, key: Key) void { .save => if (submit) exec.submitSave(p, p.view().active), .search => if (submit) look.submitSearch(p, p.view().active) - else if (normal.selRegexArmed(pane)) |_| if (target) |answered| - normal.applySelRegex(p, pane, answered, "", .select), + else if (normal.selRegexArmed(pane)) |_| if (target) |answered| { + _ = normal.applySelRegex(p, pane, answered, "", .select); + }, .none, .del_side, .repl_choice, .name => unreachable, } pane.closePrompt(); @@ -372,7 +374,9 @@ pub fn handleKey(p: *Pardes, key: Key) void { return; } edit.handleInsert(p.editor(), &pane.input, key); - if (normal.selRegexArmed(pane)) |a| if (panes.promptTarget(p, pane)) |answered| normal.applySelRegex(p, pane, answered, a.pat, a.mode); + if (normal.selRegexArmed(pane)) |a| if (panes.promptTarget(p, pane)) |answered| { + _ = normal.applySelRegex(p, pane, answered, a.pat, a.mode); + }; return; } if (header == null) if (TagState.current(p, p.view())) |cur| if (cur.root != .leader and cur.root != .window) { @@ -549,9 +553,10 @@ fn leaderTake(p: *Pardes, c: u8) void { fn tagStateKey(p: *Pardes, key: Key) void { const v = p.view(); const s = &v.tag_state; + if (s.kind == .prompt) return Prompt.key(p, key); if (TagState.hostOf(p) == null or hit(key, config.escape)) return TagState.toRest(p); switch (s.kind) { - .rest => unreachable, + .rest, .prompt => unreachable, .describe => return TagState.toRest(p), .help => { const plain = !key.ctrl and !key.alt; -- cgit v1.3 From 3da01ac676283c6d20ca6f2c0321b9dfe8cc59cd Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 22:04:55 -0300 Subject: Prompt: sam prompts one after another make one recipe word, and `s S K A-K` show their scope and what K drops (walk UI, pick-ui SPEC.md §7.1's table, §7.5, item 3 of line E): a sam prompt (`s S K A-K | A-|`, sam's `x y g v | >`) right after another of the same pane's, no key between (Prompt.chain, ended by any key at rest but one that opens such a prompt: Prompt.keyAtRest from keys.handleKey, by a search, by `! A-! $`), extends the pane's one recipe word in its trail, the Edit line it is (`Edit x/self../ g/a/ |tr a-z A-Z`, Trail.setWord); a selecting one that found nothing adds no link; Look on the word puts back the selections its sam prompts made (Pane.recipe_sels, recipe_pri), Exec runs it as Edit (edit_cmd.run, sam's dot the primary selection: a recipe of selections alone prints its matches, as acme's Edit does); while `s S K A-K` is typed the lines the selections it began with cover are fenced `┃` in the gutter, and K's and A-K's selections that would go are dimmed and struck through (a visible line's ranges found by a binary search, never all of them a frame); wire 38; THE FAULTS THE 40,000-SEED FUZZ MET over a session holding a recipe, a search word and an open prompt (a dump or an image cut, flipped and grown loaded and used): View.focus_told's pane slot was never held to the panes (Core.zig reportFocus indexed p.panes past 64: a damaged image's), now a `.index` of its own; A's Field's caret was not held to its text (Field.insert copied past the buffer at caret 513), now a `.place`; Places.current past its places (Places.addTicks's tickOf, the prompt's count and the gutter) taken as none; a search word's `/re/` length past its text taken as its text's; a user loading a damaged Dump could have hit the first three; TEST FIRST: Prompt.zig "sam prompts one after another make one recipe word ..."; fuzz "a dump and an image cut" at 40,000 join and 1,779 image seeds (a temporary edit, put back): pass; the soak, 5 clients: diverged 0, unequal 0 at rtt 30/80/207, quiet checks 413/0 426/0 619/0, the corpus 22 scenes the same, exit 0; goldens pipe (the recipe word in the trail), selregex (the fence); core-test 1017/1183 (166 skipped), shell-test 1230/1233, pane-test 182/184, behaviour-test and its replay 274/277 (the failures A's, as on item 1), process-test A's six and none of mine (`exec` failed once under a load of 8 and passes alone), term-test 17/17, kitty-test 45/45 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- abi/wire.zig | 5 +- core/Core.zig | 8 +- core/Field.zig | 8 +- core/Places.zig | 3 +- core/Prompt.zig | 265 +++++++++++++++++++++++++++++++++++++++-- core/Trail.zig | 10 +- core/keys.zig | 1 + core/panes.zig | 5 + test/daemon.py | 2 +- test/snapshots/pipe.golden | 4 +- test/snapshots/selregex.golden | 47 +++++--- 11 files changed, 317 insertions(+), 41 deletions(-) (limited to 'core/keys.zig') diff --git a/abi/wire.zig b/abi/wire.zig index cbe255f4..0cb55a32 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -10,6 +10,9 @@ const pardes = @import("core"); const config = @import("pardes_options"); const build_info = @import("build_info"); +/// 38: a pane's recipe's selections (`Pane.recipe_sels`, `recipe_pri`) +/// and the pane whose recipe a view's next sam prompt extends +/// (`Prompt.chain`) in the dump and the digest; /// 37: a view's text prompt in its tag (walk UI: `TagState.prompt`, which /// prompt, its history's place, what its field found) and the session's /// prompt histories (`prompt_history`) in the dump and the digest; @@ -83,7 +86,7 @@ const build_info = @import("build_info"); /// part B); 14: the hello names a session and /// carries the semantics hash, and a ping is answered (phase 5's /// groundwork); 13: the frames went (phase 3). -pub const version: u16 = 37; +pub const version: u16 = 38; /// The terminal's build and the window's step alike (`semantics`). const family = switch (config.platform) { diff --git a/core/Core.zig b/core/Core.zig index 95f3a3a8..e718149e 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -153,7 +153,13 @@ pub const View = struct { /// Whether the host window has the keyboard (Event.focus), and the pane /// whose program was last told it has it (reportFocus). window_focused: bool = true, - focus_told: ?struct { id: usize, serial: u32 } = null, + focus_told: ?struct { + // A slot of the session's, looked at before it is used, as + // `active` is (a damaged image's indexed past the panes). + pub const replica = .{ .index = .{.{ "id", Pardes, "panes" }} }; + id: usize, + serial: u32, + } = null, hover_col: u16 = 0, hover_row: u16 = 0, pointer_raw_col: u16 = 0, diff --git a/core/Field.zig b/core/Field.zig index 7b8ea399..2f668001 100644 --- a/core/Field.zig +++ b/core/Field.zig @@ -19,7 +19,13 @@ len: u16 = 0, /// A byte offset in the text, at a character's start. caret: u16 = 0, -pub const replica = .{ .len = .{.{ "buf", "len" }} }; +/// The caret held to the text there is (walk.zig `.place`): a damaged +/// image's past it typed out of the buffer. +pub const replica = .{ .len = .{.{ "buf", "len" }}, .place = .{.{ "caret", "lastCaret" }} }; + +pub fn lastCaret(f: *const Field) usize { + return f.len; +} pub fn text(f: *const Field) []const u8 { return f.buf[0..f.len]; diff --git a/core/Places.zig b/core/Places.zig index 4c04555b..7ffcb6cb 100644 --- a/core/Places.zig +++ b/core/Places.zig @@ -733,7 +733,8 @@ pub fn addTicks(set: *Places, p: *Pardes, pane: *Pane, s: *Surface, owner: u8) v if (!set.shows(pane)) return; const f = &pane.file.?; set.buildTicks(p, f); - const cur = if (set.current) |c| set.tickOf(p, f, c) else null; + // (A damaged image's `current` may name no place: none current then.) + const cur = if (set.current) |c| (if (c < set.hits.items.len) set.tickOf(p, f, c) else null) else null; for (set.ticks.items) |b| { if (s.nrail_ticks == s.rail_ticks.len) return; s.rail_ticks[s.nrail_ticks] = .{ .owner = owner, .at = b, .current = cur != null and cur.? == b }; diff --git a/core/Prompt.zig b/core/Prompt.zig index 53f6cd5c..1c0b1d31 100644 --- a/core/Prompt.zig +++ b/core/Prompt.zig @@ -6,6 +6,11 @@ //! 6 lines`), its effect drawn live in the body on every key; Enter applies //! it and keeps the line in its history, Esc puts the body back. //! +//! A sam prompt (`s S K A-K | A-|`, sam's `x y g v | >`) right after +//! another of the same pane's, no key between, extends one recipe word in +//! the pane's trail, the Edit line it is (`Edit x/self/ |tr a-z A-Z`): Look +//! on it puts back the selections it made, Exec runs it as Edit (SPEC §7.5). +//! //! A view's own (TagState.prompt, the coordinator's R4): its field the //! head's (TagState.field); its histories the session's, three of them //! (`/ ? s S K A-K` share one, the pipes another, `:` its own). A prompt for @@ -60,6 +65,9 @@ seeking: bool = false, /// the places' `hits_gen` `counted`. lines: u32 = 0, counted: u32 = std.math.maxInt(u32), +/// The pane, by serial, whose sam prompt Enter took last with no key since: +/// the next one extends its recipe (0: none). +chain: u32 = 0, /// The session's prompt histories: the lines Enter took, newest last. pub const History = struct { @@ -215,7 +223,17 @@ pub fn open(p: *Pardes, pane: *Pane, op: Op) void { s.host = pane.serial; s.field.clear(); s.rows = .{}; - s.prompt = .{ .op = op, .scope = scope }; + s.prompt = .{ .op = op, .scope = scope, .chain = s.prompt.chain }; +} + +/// A key the tag at rest takes (keys.handleKey): any but one that opens a +/// sam prompt ends the recipe Enter left open (a motion, an edit). +pub fn keyAtRest(p: *Pardes, k: Key) void { + const s = &p.view().tag_state; + if (s.prompt.chain == 0) return; + if (hit(k, config.select_regex) or hit(k, config.split_regex) or hit(k, config.keep_regex) or + hit(k, config.remove_regex) or hit(k, config.pipe_selection) or hit(k, config.pipe_selection_to)) return; + s.prompt.chain = 0; } /// A key in the prompt of the live view's tag: the field's editing keys, @@ -331,10 +349,16 @@ fn commit(p: *Pardes, id: usize, pane: *Pane) void { // helix keeps the pattern in `/` p.registers.put(p.gpa, '/', typed, 0, 1, true) catch |err| return p.reportError(.at(id), "prompt", err); p.registers.last_search = '/'; + // Nothing found: nothing changed, no link. + if (s.prompt.found == 0) return; + link(p, pane, op, typed); + keepSelections(p, pane); return; } if (behavior(op)) |how| { p.registers.put(p.gpa, '|', typed, 0, 1, true) catch |err| return p.reportError(.at(id), "prompt", err); + // `! A-! $` apply, and end the recipe: no Edit line says them. + if (op == .pipe or op == .pipe_to) link(p, pane, op, typed) else s.prompt.chain = 0; return Pipe.submit(p, id, &pane.body, how, typed); } } @@ -344,6 +368,8 @@ fn commit(p: *Pardes, id: usize, pane: *Pane) void { /// `/re/ 3/7` in its trail (SPEC §7.3). fn land(p: *Pardes, id: usize, pane: *Pane, op: Op, pat: []const u8, bad: bool) void { const set = &pane.places; + // A search moves the selection: the recipe ends. + p.view().tag_state.prompt.chain = 0; if (bad) { undo(p, pane, op); return p.setMessage(.at(id), regexMessage(pat)); @@ -431,6 +457,77 @@ pub fn dims(p: *const Pardes, pane: *const Pane) bool { return s.kind == .prompt and searches(s.prompt.op) and s.host == pane.serial and s.prompt.bad; } +// ---- the recipe word (SPEC §7.5) ---- + +fn recipeOf(pane: *Pane) ?*Trail.Word { + for (pane.trail.steps[0..pane.trail.n]) |*step| if (step.* == .recipe) return &step.recipe; + return null; +} + +/// Sam prompt `op`'s `line` as a link of `pane`'s recipe: after the one +/// its last sam prompt left open, else a recipe of its own in place of the +/// pane's one. One past the trail's room starts none. +fn link(p: *Pardes, pane: *Pane, op: Op, line: []const u8) void { + const s = &p.view().tag_state; + var buf: [Trail.max_text]u8 = undefined; + var w: std.Io.Writer = .fixed(&buf); + const open_recipe = if (s.prompt.chain == pane.serial) recipeOf(pane) else null; + s.prompt.chain = 0; + (if (open_recipe) |r| w.writeAll(r.text.slice()) else w.writeAll("Edit")) catch return; + w.writeByte(' ') catch return; + const said = switch (op) { + .select => samWord(&w, 'x', line), + .split => samWord(&w, 'y', line), + .keep => samWord(&w, 'g', line), + .remove => samWord(&w, 'v', line), + .pipe => w.print("|{s}", .{line}), + .pipe_to => w.print(">{s}", .{line}), + else => return, + }; + said catch return; + var word_: Trail.Word = .{}; + word_.text.set(w.buffered()); + pane.trail.setWord(.{ .recipe = word_ }); + s.prompt.chain = pane.serial; +} + +/// The selections a recipe's sam prompts made, kept for Look on its word. +fn keepSelections(p: *Pardes, pane: *Pane) void { + const text = edit.flatSurface(p.editor(), &pane.body) catch return; + var ranges: [Text.max_selections]modal.Selection = undefined; + const got = pane.body.ranges(text, 0, &ranges); + const kept = p.gpa.dupe(modal.Selection, ranges[0..got.n]) catch return; + p.gpa.free(pane.recipe_sels); + pane.recipe_sels = kept; + pane.recipe_pri = @intCast(got.pri); +} + +/// Look on pane `id`'s recipe word: the selections it made, again. +pub fn lookRecipe(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + p.view().active = id; + if (pane.recipe_sels.len == 0) return; + const text = edit.flatSurface(p.editor(), &pane.body) catch |err| return p.reportError(.at(id), "recipe", err); + for (pane.recipe_sels) |*r| { + r.anchor = @min(r.anchor, text.len); + r.head = @min(r.head, text.len); + } + pane.body.setRanges(p.settings.tab, text, pane.recipe_sels, &.{}, @min(pane.recipe_pri, pane.recipe_sels.len - 1), true); + pane.body.show(p.settings.tab); +} + +/// Exec on it: the Edit line it is, run on what is selected now +/// (edit_cmd.zig, sam's dot the primary selection). +pub fn execRecipe(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + const r = recipeOf(pane) orelse return; + var line: [Trail.max_text]u8 = undefined; + const text = r.text.slice(); + @memcpy(line[0..text.len], text); + p.view().active = id; + pardes.edit_cmd.run(p, id, line["Edit ".len..text.len]); +} + // ---- the search word (SPEC §7.3) ---- /// Pane `pane`'s search word, `/re/ 3/7`: one a pane, its `index` the @@ -441,8 +538,14 @@ fn wordOf(pane: *Pane) ?*Trail.Word { } fn patternOf(w: *const Trail.Word) []const u8 { - const end: u16 = @truncate(w.index); - return w.text.slice()[1 .. end - 1]; + const end = patternEnd(w); + return if (end < 2) "" else w.text.slice()[1 .. end - 1]; +} + +/// Where a search word's `/re/` ends: held to its text (a damaged image's +/// says anything). +fn patternEnd(w: *const Trail.Word) u16 { + return std.math.clamp(@as(u16, @truncate(w.index)), @min(2, w.text.len), w.text.len); } /// Whether the places the pane's body shows are its search word's. @@ -472,7 +575,7 @@ fn refresh(pane: *Pane, wrapped: ?bool) void { if (!lights(pane, w)) return; const set = &pane.places; const f = &pane.file.?; - const end: u16 = @truncate(w.index); + const end = patternEnd(w); const round = wrapped orelse (w.index >> 16 != 0); const hits = set.hits.items; const sel = pane.body.primaryRange(f.content, 0); @@ -525,6 +628,7 @@ pub fn stepped(p: *Pardes, id: usize, forward: bool, before: ?usize) void { const set = &pane.places; if (!lights(pane, w)) return; const after = set.current orelse return; + if (after >= set.hits.items.len) return; refresh(pane, if (before) |b| (if (forward) after <= b else after >= b) else false); const index = File.lineIndex(p.gpa, &pane.file.?) catch return; var said: [Trail.max_text + 32]u8 = undefined; @@ -550,8 +654,7 @@ pub fn lookWord(p: *Pardes, id: usize) void { set.search(p, pane, .search, 0, pat, false, null, false); set.fill(p, pane, std.math.maxInt(usize), regexp.Regex.budget); p.view().active = id; - const end: u16 = @truncate(w.index); - const rest = w.text.slice()[end..]; + const rest = w.text.slice()[patternEnd(w)..]; const n = std.fmt.parseInt(usize, std.mem.trim(u8, rest[0 .. std.mem.indexOfScalar(u8, rest, '/') orelse rest.len], " "), 10) catch return; if (n > 0 and n <= set.hits.items.len) set.goTo(p.settings.tab, pane, n - 1, false); } @@ -587,17 +690,21 @@ pub fn unlit(pane: *Pane) ?[2]usize { /// The gutter's marks while a prompt is typed (SPEC §7.1): `▸` on the /// current place's line and `▪` on every other line holding a place (`/ -/// ?`). In the blank after a row's line number, on a line's first row. +/// ?`); `┃` on each line the selections a sam prompt began with cover (`s +/// S K A-K`), its scope. In the blank after a row's line number, on a +/// line's first row. pub fn paintGutter(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: u16) void { const ts = &p.view().tag_state; - if (ts.kind != .prompt or ts.host != pane.serial or !searches(ts.prompt.op)) return; + if (ts.kind != .prompt or ts.host != pane.serial) return; const f = &(pane.file orelse return); + if (mode(ts.prompt.op) != null) return fence(p, s, pane, r, body_h); + if (!searches(ts.prompt.op)) return; const set = &pane.places; if (!set.shows(pane)) return; const hits = set.hits.items; if (hits.len == 0) return; const tab = p.settings.tab; - const x = r.x + config.GUTTER + (File.gutterWidth(pane) -| File.laneCells(pane) -| pane.layers.heat -| 1); + const x = gutterX(pane, r); const y = p.bodyTop(pane, r); const ink = p.chromeTheme().box; const nlines = File.nlines(p.gpa, f); @@ -612,7 +719,7 @@ pub fn paintGutter(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: const next = File.lineStart(p.gpa, f, @intCast(line + 1)); const i = Places.firstFrom(hits, ls); if (i == hits.len or hits[i].start >= @max(next, ls + 1)) continue; - const current = if (set.current) |c| hits[c].start >= ls and hits[c].start < @max(next, ls + 1) else false; + const current = if (set.current) |c| c < hits.len and hits[c].start >= ls and hits[c].start < @max(next, ls + 1) else false; var style = s.at(x, y + vr).style; style.fg = .{ .rgb = ink }; s.set(x, y + vr, if (current) "▸" else "▪", style); @@ -654,6 +761,90 @@ fn plainWord(w: *std.Io.Writer, op: Op, line: []const u8) !?[]const u8 { return if (op == .search or op == .search_back) "Look" else "Exec"; } +/// The x of the blank after pane `pane`'s line numbers. +fn gutterX(pane: *const Pane, r: pardes.Rect) u16 { + return r.x + config.GUTTER + (File.gutterWidth(pane) -| File.laneCells(pane) -| pane.layers.heat -| 1); +} + +/// `┃` on the lines the selections a sam prompt began with cover, and +/// the ones `K` or `A-K` would drop dimmed and struck through. +fn fence(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: u16) void { + const f = &pane.file.?; + const tab = p.settings.tab; + const snap = pane.sel_snap[0..pane.nsel_snap]; + if (snap.len == 0) return; + const x = gutterX(pane, r); + const y = p.bodyTop(pane, r); + const ink = p.chromeTheme().box; + const nlines = File.nlines(p.gpa, f); + const op = p.view().tag_state.prompt.op; + var kept: [Text.max_selections]modal.Selection = undefined; + const now = if (op == .keep or op == .remove) pane.body.ranges(f.content, 0, &kept).n else 0; + var last: i32 = -1; + var vr: u16 = 0; + while (vr < body_h) : (vr += 1) { + const line = pane.wrapAt(tab, vr).line; + if (line == last or line < 0) continue; + if (line >= nlines) break; + last = line; + const ls = File.lineStart(p.gpa, f, @intCast(line)); + const le = File.lineStart(p.gpa, f, @intCast(line + 1)); + // The ranges are in the text's order: the first ending past the + // line's start, on while they start before its end. + var i = endingPast(snap, ls); + if (i < snap.len and @min(snap[i].anchor, snap[i].head) < @max(le, ls + 1)) { + var style = s.at(x, y + vr).style; + style.fg = .{ .rgb = ink }; + s.set(x, y + vr, "┃", style); + } + // K and A-K: the selections that would go, on this line. + if (op != .keep and op != .remove) continue; + while (i < snap.len and @min(snap[i].anchor, snap[i].head) < le) : (i += 1) { + const lo = @min(snap[i].anchor, snap[i].head); + const hi = @max(snap[i].anchor, snap[i].head); + const k = endingPast(kept[0..now], lo); + const stays = k < now and @min(kept[k].anchor, kept[k].head) == lo and @max(kept[k].anchor, kept[k].head) == hi; + if (!stays) strike(p, s, pane, r, line, @intCast(@max(lo, ls) - ls), @intCast(@min(hi, le) - ls)); + } + } +} + +/// The first of `ranges` (in the text's order) ending past byte `at`. +fn endingPast(ranges: []const modal.Selection, at: usize) usize { + return std.sort.partitionPoint(modal.Selection, ranges, at, struct { + fn before(byte: usize, r: modal.Selection) bool { + return @max(r.anchor, r.head) <= byte; + } + }.before); +} + +/// Bytes [lo, hi) of `line`, as many of its rows as show them, dimmed and +/// struck through (File.paintWordSelection's walk). +fn strike(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, line: i32, lo_: i32, hi_: i32) void { + const tab = p.settings.tab; + const tw = r.w - config.GUTTER; + const prefix: i32 = File.gutterWidth(pane); + const body_y = p.bodyTop(pane, r); + var vr: i32 = 0; + while (vr + @as(i32, pane.tag_rows) < @as(i32, r.h)) : (vr += 1) { + const here = pane.wrapAt(tab, vr); + if (here.line != line) continue; + var hi = hi_; + const next = pane.wrapAt(tab, vr + 1); + if (next.line == line) hi = @min(hi, next.at); + const lo = @max(lo_, here.at); + if (hi <= lo) continue; + const c0 = prefix + here.pad + File.displayOffset(tab, pane, line, here.at, lo); + const c1 = prefix + here.pad + File.displayEndOffset(tab, pane, line, here.at, hi - 1); + var col = @max(prefix, c0); + while (col <= c1 and col < tw) : (col += 1) { + const style = &s.at(r.x + config.GUTTER + @as(u16, @intCast(col)), body_y + @as(u16, @intCast(vr))).style; + style.dim = true; + style.strikethrough = true; + } + } +} + /// The head of the prompt's tag: ` s self▌ = Exec Edit x/self/ 4 /// selections in 6 lines ⏎ select · C-r history · esc`. pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !TagState.Head { @@ -702,11 +893,12 @@ fn count(arena: std.mem.Allocator, text: *std.ArrayList(u8), pane: *Pane, pr: *c const hits = set.hits.items; if (set.complete() and hits.len == 0) return text.appendSlice(arena, " 0"); try text.appendSlice(arena, " "); - if (set.current) |c| try text.print(arena, "{d}", .{c + 1}) else try text.appendSlice(arena, "–"); + const at = if (set.current) |c| (if (c < hits.len) c else null) else null; + if (at) |c| try text.print(arena, "{d}", .{c + 1}) else try text.appendSlice(arena, "–"); if (!set.complete()) return text.appendSlice(arena, "/⋯"); try text.print(arena, "/{d} · {d} line{s}", .{ hits.len, pr.lines, plural(pr.lines) }); // Round the end from where it began. - const c = set.current orelse return; + const c = at orelse return; const origin = set.origin(pane); if (if (pr.op == .search) hits[c].start < origin else hits[c].start > origin) try text.appendSlice(arena, " · wrapped"); }, @@ -940,3 +1132,52 @@ test "? searches back from the caret; no match is 0; a pattern that is no regex try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind); try std.testing.expect(p.panes[p.view().active].?.query != null); } + +test "sam prompts one after another make one recipe word, the Edit line it is; a motion ends it and the next starts the pane's one again; ! adds nothing; the scope fenced in the gutter, what K drops struck; Look puts its selections back, Exec runs it as Edit" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 200, .rows = 30 }); + defer p.deinit(); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile("self.a = 1;\nself.b = 2;\nother = 3;\n"); + typeKeys(p, "%sother"); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "Edit x/other/ › /test.txt ")); + // Look on it: the selection it made, again. + typeKeys(p, "gg"); + Trail.lookStep(p, 0, 0); + const back = pane.body.primaryRange(pane.file.?.content, 0); + try std.testing.expectEqual(@as(usize, 24), @min(back.anchor, back.head)); + try std.testing.expectEqual(@as(usize, 29), @max(back.anchor, back.head)); + // A motion ends it: the next s is a recipe of its own, the pane's one. + typeKeys(p, "j%sself.."); + for ([_]u16{ 0, 1, 2 }) |row| try std.testing.expectEqualStrings("┃", try gutterAt(p, frame.allocator(), row)); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "Edit x/self../ › /test.txt ")); + try std.testing.expectEqual(@as(u8, 1), pane.trail.n); + // K right after: `self.b` would go, struck through. + typeKeys(p, "Ka"); + p.sync(); + const s = try p.render(frame.allocator()); + const r = p.view().rects[0]; + const cell = s.at(r.x + config.GUTTER + File.gutterWidth(pane), p.bodyTop(pane, r) + 1); + try std.testing.expect(cell.style.strikethrough and cell.style.dim); + try std.testing.expect(!s.at(r.x + config.GUTTER + File.gutterWidth(pane), p.bodyTop(pane, r)).style.strikethrough); + p.update(.{ .key = .{ .cp = Key.enter } }); + typeKeys(p, "|"); + p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "Edit x/self../ g/a/ |tr a-z A-Z › /test.txt ")); + // `!` applies and adds nothing: an Edit line cannot say it. + typeKeys(p, "!"); + p.update(.{ .key = .{ .cp = 'e', .text = "echo" } }); + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p), "Edit x/self../ g/a/ |tr a-z A-Z › /test.txt ")); + while (p.nextEffect()) |_| {} + if (p.pipe.wait) |*w| w.deinit(); + p.pipe.wait = null; + // Exec on it: Edit runs it, its command off the loop. + typeKeys(p, "%"); + Trail.execStep(p, 0, 0); + try std.testing.expect(p.pipe.edit_run != null); +} diff --git a/core/Trail.zig b/core/Trail.zig index 0ea893e2..cb5dedf8 100644 --- a/core/Trail.zig +++ b/core/Trail.zig @@ -338,8 +338,8 @@ pub fn stepAt(t: *const Trail, part: Part, off: usize) ?u8 { } /// Look on step `i` of pane `id`'s trail (§6.3): a place is gone back or -/// forward to, the owner focused, a search lit again (Prompt.zig); a list -/// or a recipe is the pickers' and the prompts' to take (not yet: said). +/// forward to, the owner focused, a search lit again, a recipe's +/// selections put back (Prompt.zig); a list is the pickers' (not yet: said). pub fn lookStep(p: *Pardes, id: usize, i: u8) void { const pane = p.panes[id] orelse return; switch (pane.trail.steps[i]) { @@ -348,7 +348,8 @@ pub fn lookStep(p: *Pardes, id: usize, i: u8) void { p.view().active = owner; } else p.reportFailure(id, "walk: its owner is closed"), .search => pardes.Prompt.lookWord(p, id), - .list, .recipe => p.setMessage(.at(id), "walk: a list or a recipe is not walked yet"), + .recipe => pardes.Prompt.lookRecipe(p, id), + .list => p.setMessage(.at(id), "walk: a list is not walked yet"), } } @@ -359,7 +360,8 @@ pub fn execStep(p: *Pardes, id: usize, i: u8) void { switch (pane.trail.steps[i]) { .place, .owner => lookStep(p, id, i), .search => pardes.Prompt.execWord(p, id), - .list, .recipe => p.setMessage(.at(id), "walk: a list or a recipe is not run again yet"), + .recipe => pardes.Prompt.execRecipe(p, id), + .list => p.setMessage(.at(id), "walk: a list is not run again yet"), } } diff --git a/core/keys.zig b/core/keys.zig index 6ffca8e1..a0aa9692 100644 --- a/core/keys.zig +++ b/core/keys.zig @@ -214,6 +214,7 @@ pub fn handleKey(p: *Pardes, key: Key) void { } // A tag in a typing state takes every key (TagState: Help, describe-key). if (p.view().tag_state.kind != .rest) return tagStateKey(p, key); + Prompt.keyAtRest(p, key); if (p.view().window_pick != null) return layout.windowKey(p, key); const pane = p.panes[p.view().active] orelse return; layout.noteTyped(p); diff --git a/core/panes.zig b/core/panes.zig index 0590a80d..e15ad180 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -273,6 +273,10 @@ pub const Pane = struct { /// Its walk: the places it stepped through, its owner when it is a /// reader, whether it is held (Trail.zig, pick-ui SPEC §6). trail: Trail = .{}, + /// The selections its recipe word's sam prompts made (gpa), for Look + /// on the word to put back (Prompt.zig, SPEC §7.5). + recipe_sels: []modal.Selection = &.{}, + recipe_pri: u16 = 0, /// `gw`'s words, labelled in order while it waits for a label to be /// typed (gpa-owned); `jump_first` is the label's first letter once typed. jump: std.ArrayList(modal.Selection) = .empty, @@ -1296,6 +1300,7 @@ pub fn teardownPane(p: *Pardes, pane: *Pane) void { pane.input.deinit(p.gpa); pane.jump.deinit(p.gpa); pane.places.deinit(p.gpa); + p.gpa.free(pane.recipe_sels); @import("jj.zig").forget(p, pane.serial); if (pane.query) |q| { q.deinit(p.gpa); diff --git a/test/daemon.py b/test/daemon.py index 4bc2658f..bb159424 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -340,7 +340,7 @@ class Replica: """A replica's connection (abi/wire.zig): length-prefixed messages, a tag byte and a little-endian u32 length. It is a near client: its first word after the hello says so.""" - WIRE = 37 + WIRE = 38 def __init__(self, path, timeout=10): self.path, self.timeout = path, timeout diff --git a/test/snapshots/pipe.golden b/test/snapshots/pipe.golden index 641418f9..04921c77 100644 --- a/test/snapshots/pipe.golden +++ b/test/snapshots/pipe.golden @@ -5,8 +5,8 @@ | 1 alpha beta | 2 gamma delta == snap filtered grid=180x13 cursor=17,3 -|2: */tmp/pardes-snap/pipe/cwd/pipe.txt Save Term Collapse Follow Del +|2: *Edit |tr a-z A-Z › /tmp/pardes-snap/pipe/cwd/pipe.txt Save Term Collapse Follow Del |3: 1 ALPHA BETA == snap undone grid=180x13 cursor=17,3 -|2: /tmp/pardes-snap/pipe/cwd/pipe.txt Save Term Collapse Follow Del +|2: Edit |tr a-z A-Z › /tmp/pardes-snap/pipe/cwd/pipe.txt Save Term Collapse Follow Del |3: 1 alpha beta diff --git a/test/snapshots/selregex.golden b/test/snapshots/selregex.golden index cc460f03..7a760e2b 100644 --- a/test/snapshots/selregex.golden +++ b/test/snapshots/selregex.golden @@ -2,9 +2,9 @@ | Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config History Debug Exit | New Term Find Grep Joincol Delcol |^ /tmp/pardes-snap/selregex/cwd/m.zig s ⏎ select · C-r history · esc -| 1 const one = 1; -| 2 const two = 2; -| 3 const three = 3; +| 1┃const one = 1; +| 2┃const two = 2; +| 3┃const three = 3; | ~ == snap preview grid=160x25 cursor=45,2 |2: ^ /tmp/pardes-snap/selregex/cwd/m.zig s const = Exec Edit x/const/ 3 selections in 3 lines ⏎ select · C-r history · esc @@ -12,9 +12,9 @@ |0: 0-1 d,#1d2824, 2-159 #b2c3b8,#1d2824, |1: 0-1 d,#887455, 2-159 #becfc4,#314738, |2: 0-1 #000000,#add38a, 2-31 #becfc4,#314738, 32-37 #dfbce5,#314738, 38-38 #add38a,#314738,b 39-39 #add38a,#314738, 40-44 #becfc4,#314738, 45-52 #becfc4,#314738,f 53-95 #becfc4,#314738, 96-123 #becfc4,#314738,f 124-159 #becfc4,#314738, -|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #f5f7ee,#3c614a, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, -|4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, -|5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-159 #e5eee5,#0d1410, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-5 #616f64,#0d1410,b 6-6 #add38a,#0d1410,b 7-10 #f5f7ee,#3c614a, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-4 d,#0d1410, 5-5 #59675c,#0d1410, 6-6 #add38a,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-4 d,#0d1410, 5-5 #59675c,#0d1410, 6-6 #add38a,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-159 #e5eee5,#0d1410, |6: 0-0 d,#608269, 1-4 d,#0d1410, 5-159 #59675c,#0d1410, |7: 0-0 d,#608269, 1-159 d,#0d1410, |8: 0-0 d,#608269, 1-159 d,#0d1410, @@ -35,31 +35,42 @@ |23: 0-0 d,#608269, 1-159 d,#0d1410, |24: 0-0 d,#608269, 1-159 d,#0d1410, == snap three-selected grid=160x25 cursor=11,3 -|2: /tmp/pardes-snap/selregex/cwd/m.zig Save Term Collapse Follow TreeContext Def Refs Del +|2: Edit x/const/ › /tmp/pardes-snap/selregex/cwd/m.zig Save Term Collapse Follow TreeContext Def Refs Del +|3: 1 const one = 1; +|4: 2 const two = 2; +|5: 3 const three = 3; == style three-selected grid=160x25 -|2: 0-1 d,#add38a, 2-31 #becfc4,#314738, 32-37 #dfbce5,#314738, 38-159 #becfc4,#314738, +|2: 0-1 d,#add38a, 2-47 #becfc4,#314738, 48-53 #dfbce5,#314738, 54-159 #becfc4,#314738, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-11 #f5f7ee,#3c614a, 12-12 #f5f7ee,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, -== snap narrowed grid=160x25 cursor=41,2 -|2: ^ /tmp/pardes-snap/selregex/cwd/m.zig s t = Exec Edit x/t/ 3 selections in 3 lines ⏎ select · C-r history · esc +|4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-159 #e5eee5,#0d1410, +== snap narrowed grid=160x25 cursor=57,2 +|2: ^ Edit x/const/ › /tmp/pardes-snap/selregex/cwd/m.zig s t = Exec Edit x/t/ 3 selections in 3 lines ⏎ select · C-r history · esc +|3: 1┃const one = 1; +|4: 2┃const two = 2; +|5: 3┃const three = 3; == style narrowed grid=160x25 -|2: 0-1 #000000,#add38a, 2-31 #becfc4,#314738, 32-37 #dfbce5,#314738, 38-38 #add38a,#314738,b 39-39 #add38a,#314738, 40-40 #becfc4,#314738, 41-48 #becfc4,#314738,f 49-87 #becfc4,#314738, 88-115 #becfc4,#314738,f 116-159 #becfc4,#314738, -|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-10 #e5eee5,#0d1410, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, -|4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, -|5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #e5eee5,#0d1410, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-159 #e5eee5,#0d1410, +|2: 0-1 #000000,#add38a, 2-47 #becfc4,#314738, 48-53 #dfbce5,#314738, 54-54 #add38a,#314738,b 55-55 #add38a,#314738, 56-56 #becfc4,#314738, 57-64 #becfc4,#314738,f 65-103 #becfc4,#314738, 104-131 #becfc4,#314738,f 132-159 #becfc4,#314738, +|3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-5 #616f64,#0d1410,b 6-6 #add38a,#0d1410,b 7-10 #e5eee5,#0d1410, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, +|4: 0-0 d,#608269, 1-4 d,#0d1410, 5-5 #59675c,#0d1410, 6-6 #add38a,#0d1410, 7-10 #e5eee5,#0d1410, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, +|5: 0-0 d,#608269, 1-4 d,#0d1410, 5-5 #59675c,#0d1410, 6-6 #add38a,#0d1410, 7-10 #e5eee5,#0d1410, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-159 #e5eee5,#0d1410, == snap esc-restores grid=160x25 cursor=11,3 -|2: /tmp/pardes-snap/selregex/cwd/m.zig Save Term Collapse Follow TreeContext Def Refs Del +|2: Edit x/const/ › /tmp/pardes-snap/selregex/cwd/m.zig Save Term Collapse Follow TreeContext Def Refs Del +|3: 1 const one = 1; +|4: 2 const two = 2; +|5: 3 const three = 3; == style esc-restores grid=160x25 -|2: 0-1 d,#add38a, 2-31 #becfc4,#314738, 32-37 #dfbce5,#314738, 38-159 #becfc4,#314738, +|2: 0-1 d,#add38a, 2-47 #becfc4,#314738, 48-53 #dfbce5,#314738, 54-159 #becfc4,#314738, |3: 0-0 d,#608269, 1-1 d,#0d1410, 2-4 d,#0d1410,b 5-6 #616f64,#0d1410,b 7-11 #f5f7ee,#3c614a, 12-12 #f5f7ee,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, |4: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-18 #e5eee5,#0d1410, 19-19 #f8c082,#0d1410, 20-159 #e5eee5,#0d1410, |5: 0-0 d,#608269, 1-4 d,#0d1410, 5-6 #59675c,#0d1410, 7-10 #f5f7ee,#243a2d, 11-11 #3c614a,#f5f7ee, 12-12 #3c614a,#0d1410, 13-20 #e5eee5,#0d1410, 21-21 #f8c082,#0d1410, 22-159 #e5eee5,#0d1410, == snap commented grid=160x25 cursor=14,3 -|2: */tmp/pardes-snap/selregex/cwd/m.zig Save Term Collapse Follow TreeContext Def Refs Del +|2: *Edit x/const/ › /tmp/pardes-snap/selregex/cwd/m.zig Save Term Collapse Follow TreeContext Def Refs Del |3: 1 // const one = 1; |4: 2 // const two = 2; |5: 3 // const three = 3; == snap uncommented grid=160x25 cursor=11,3 -|2: /tmp/pardes-snap/selregex/cwd/m.zig Save Term Collapse Follow TreeContext Def Refs Del +|2: Edit x/const/ › /tmp/pardes-snap/selregex/cwd/m.zig Save Term Collapse Follow TreeContext Def Refs Del |3: 1 const one = 1; |4: 2 const two = 2; |5: 3 const three = 3; -- cgit v1.3 From b44a129a8854483dbe45ce2bcfa09f33ccbd6e8c Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 22:16:38 -0300 Subject: registers: `"` shows the registers rolled in the tag, each its key and the first line of its value (`" ▸ " self.dirty = true; a const best = rank(q, nam… / — … % core/x.zig . o # 1 _ —`), `↓` unrolls them a row each (key, what it is, first line) beside the cursor's value in full, and choosing one (its key, or Enter) goes down to its verbs rolled (`" a ▸ p after P before R replace y into`), Backspace back up, Esc to rest (pick-ui SPEC §9, walk UI line F item 1): the level is built from the registers (and the four computed from the pane with the keyboard) when it is read, as the addon words join SPC's (bindings.registerLevel, registerValue: the first value only, a first line cut at 24 columns and never scanned past 96 bytes, the value step reading only the lines the band shows); a register named (`t.normal.register`, the parser's) is the root `"` with that key as its path (TagState.current), its verbs a node of normal mode's paste, yank and replace roles (bindings.register_verbs, a group slot of its own: TagState.used one longer, the dump with it); keys.prefixKey reads the level at the current path, Esc there goes to rest (normal mode's Esc would have named the register ESC, then left the pane), Backspace from the verbs goes back to `"`; TEST: bindings.zig "\" shows the registers rolled ..." (the level, the band's rows and value, Enter, Backspace, `a p` pasting, Esc); core-test 1024/1191 (167 skipped), 0 failed, load 5 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- core/Band.zig | 66 ++++++++++++++++++++- core/TagState.zig | 11 +++- core/bindings.zig | 172 +++++++++++++++++++++++++++++++++++++++++++++++++++++- core/keys.zig | 28 +++++++-- 4 files changed, 266 insertions(+), 11 deletions(-) (limited to 'core/keys.zig') diff --git a/core/Band.zig b/core/Band.zig index 3c800bf0..13c4b9c0 100644 --- a/core/Band.zig +++ b/core/Band.zig @@ -105,6 +105,8 @@ pub fn takes(p: *Pardes, id: usize) u16 { const cur = TagState.current(p, v) orelse return 0; var children: [bindings.max_children]bindings.Child = undefined; const n: u16 = @intCast(bindings.level(p, cur.root, cur.path, &children).len); + // The registers, one column of eleven at most (registerSteps). + if (cur.root == .register and cur.path.len == 0) return @max(doc_rows, @min(Cursor.shown, n)); return @max(doc_rows, levelRows(n)); } @@ -151,6 +153,11 @@ pub fn of(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, id: usize) !?Band { }, } const cur = TagState.current(p, v).?; + if (cur.root == .register) { + try band.registerSteps(p, arena, pane, cur.path); + try band.place(p, arena, pane, id); + return band; + } // The level, its cursor on the child it names, else the leaf its group // ran last, else the first; and that child's doc beside it. const node = bindings.nodeAt(cur.root, cur.path); @@ -196,6 +203,63 @@ fn helpSteps(band: *Band, p: *Pardes, arena: std.mem.Allocator, s: *const TagSta band.add(try docStep(p, arena, at.root, at.path[0 .. at.path.len - 1], at.child)); } +/// `"` unrolled (SPEC §9): the registers, a row each (its key, what it +/// is, its first line) around the cursor, or under `"a` its verbs; beside +/// them the value of the one on the cursor (or named) in full, as many of +/// its lines as the band has rows, only those read. +fn registerSteps(band: *Band, p: *Pardes, arena: std.mem.Allocator, pane: *const Pane, path: []const u8) !void { + const s = &p.view().tag_state; + var children: [bindings.max_children]bindings.Child = undefined; + const level = bindings.level(p, .register, path, &children); + const node = bindings.nodeAt(.register, path); + const used = if (node) |n| s.used[n.group] else 0; + var at: usize = 0; + for (level, 0..) |c, i| if (c.key == (if (s.hi != 0) s.hi else used)) { + at = i; + }; + if (path.len > 0) band.add(try levelStep(arena, pane, level, at, used)) else { + const w = (Cursor{ .at = @intCast(at) }).window(@intCast(level.len)); + const rows = try arena.alloc(Row, w.hi - w.lo); + for (rows, w.lo..) |*row, i| { + const c = level[i]; + const name = for (bindings.register_names) |r| { + if (r.key == c.key) break r.name; + } else "named"; + row.* = .{ + .text = try std.fmt.allocPrint(arena, "{s} {s: <17} {s}{s}", .{ bindings.keyName(c.key), name, c.label, if (c.more) "…" else "" }), + .on = i == at, + .key = 1, + .under = c.key == used, + .index = @intCast(i), + }; + } + band.add(.{ .rows = rows }); + } + const key = if (path.len > 0) path[0] else level[at].key; + const name = for (bindings.register_names) |r| { + if (r.key == key) break r.name; + } else "named"; + var rows: std.ArrayList(Row) = .empty; + try rows.append(arena, .{ .text = try std.fmt.allocPrint(arena, "\"{s} · {s}", .{ bindings.keyName(key), name }), .key = 2 }); + const value = bindings.registerValue(p, key); + if (value.len == 0) try rows.append(arena, .{ .text = "(empty)", .dim = true }); + // A line is cut at what the band could show of it: a long one is + // never scanned past that. + const most = @as(usize, band.columns) * band.height; + var rest = value; + while (rest.len > 0 and rows.items.len + 1 < band.height) { + const look = rest[0..@min(rest.len, most)]; + const end = std.mem.indexOfScalar(u8, look, '\n') orelse { + try rows.append(arena, .{ .text = rest[0..if (look.len < rest.len) modal.graphemeStart(rest, look.len) else look.len] }); + break; + }; + try rows.append(arena, .{ .text = look[0..end] }); + rest = rest[end + 1 ..]; + } + if (path.len == 0) try rows.append(arena, .{ .text = "next p after P before R replace y into", .dim = true }); + band.add(.{ .rows = rows.items, .doc = true }); +} + /// A list's cursor and the rows of it a band shows: eleven at most, around /// the cursor (SPEC §3.6, the prototype's `H.window`). Each view's (a /// tag state's field): Help's rows, a picker's, a prompt's history. @@ -245,7 +309,7 @@ pub fn levelStep(arena: std.mem.Allocator, pane: *const Pane, level: []const bin for (level, rows, 0..) |c, *row, i| { const key = bindings.keyName(c.key); row.* = .{ - .text = try std.fmt.allocPrint(arena, "{s} {s}{s}", .{ key, c.label, if (c.group) "…" else "" }), + .text = try std.fmt.allocPrint(arena, "{s} {s}{s}", .{ key, c.label, if (c.group or c.more) "…" else "" }), .on = i == at, .key = @intCast(key.len), .dim = bindings.dimmed(pane, c), diff --git a/core/TagState.zig b/core/TagState.zig index 5a30f182..95df8937 100644 --- a/core/TagState.zig +++ b/core/TagState.zig @@ -152,7 +152,11 @@ pub fn current(p: *const Pardes, v: *const View) ?Current { if (v != p.view() or v.header != null) return null; const pane = p.panes[v.active] orelse return null; const t = if (pane.focus == .tag) &pane.tag else &pane.body; - const prefix = t.normal.prefix orelse return null; + const prefix = t.normal.prefix orelse { + // `"a`: the register named, its verbs next (SPEC §9). + const r = t.normal.register; + return if (r > ' ' and r <= '~') .{ .root = .register, .path = bindings.keyName(@intCast(r)) } else null; + }; const root: Root = switch (prefix) { .goto_prefix => .goto, .view_prefix => if (t.normal.sticky) .view_sticky else .view, @@ -188,7 +192,8 @@ pub fn hostOf(p: *const Pardes) ?usize { fn textPrefix(p: *const Pardes, v: *const View) bool { const pane = p.panes[v.active] orelse return false; - return pane.body.normal.prefix != null or pane.tag.normal.prefix != null; + return pane.body.normal.prefix != null or pane.tag.normal.prefix != null or + pane.body.normal.register != 0 or pane.tag.normal.register != 0; } /// After a key (keys.handleKey): a root newly current starts its delay; one @@ -515,7 +520,7 @@ pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !?Head { try b.styled(bindings.keyName(c.key), .key); try b.put(" "); try b.put(c.label); - if (c.group) try b.put("…"); + if (c.group or c.more) try b.put("…"); const hi: u32 = @intCast(b.text.items.len); if (bindings.dimmed(pane, c)) try b.spans.append(arena, .{ .lo = lo, .hi = hi, .style = .dim }); if (c.key == used) try b.spans.append(arena, .{ .lo = lo, .hi = hi, .style = .under }); diff --git a/core/bindings.zig b/core/bindings.zig index b2d84a7c..f7be1a43 100644 --- a/core/bindings.zig +++ b/core/bindings.zig @@ -15,6 +15,8 @@ const Pardes = pardes.Pardes; const Pane = pardes.Pane; const Key = pardes.Key; const Role = modal.Normal.Role; +const edit = @import("edit.zig"); +const File = @import("File.zig"); /// The keys a sequence starts with. `register` (`"`) is drawn the same way /// but its rows are the registers' contents, not a tree. @@ -87,8 +89,9 @@ pub const groups = groups: { }; break :groups paths; }; -/// SPC's groups, then one for each other root. -pub const ngroups = groups.len + std.enums.values(Root).len - 1; +/// SPC's groups, then one for each other root, then the verbs a register +/// takes (`"a ▸`). +pub const ngroups = groups.len + std.enums.values(Root).len; fn rootGroup(comptime r: Root) u8 { return @intCast(groups.len + @intFromEnum(r) - 1); @@ -233,6 +236,15 @@ const view_sticky_tree: Node = .{ .key = config.view_prefix_sticky, .label = "vi const prev_tree: Node = .{ .key = config.prev_prefix, .label = "previous", .children = roleLevel(.goto_paragraph, .goto_xml_element, &.{}), .group = rootGroup(.prev) }; const next_tree: Node = .{ .key = config.next_prefix, .label = "next", .children = roleLevel(.goto_paragraph, .goto_xml_element, &.{}), .group = rootGroup(.next) }; const register_tree: Node = .{ .key = config.register_prefix, .label = "registers", .group = rootGroup(.register) }; +/// What the register `"` named does next (SPEC §9: `"a ▸ p after P before +/// y into R replace`): normal mode's paste, yank and replace, which read +/// the register the parser holds. +const register_verbs: Node = .{ .key = 0, .label = "register", .group = ngroups - 1, .children = sorted(&.{ + .{ .key = roleKey(.paste_after).?, .label = "after", .leaf = .{ .role = .paste_after } }, + .{ .key = roleKey(.paste_before).?, .label = "before", .leaf = .{ .role = .paste_before } }, + .{ .key = roleKey(.yank).?, .label = "into", .leaf = .{ .role = .yank } }, + .{ .key = roleKey(.replace_with_yank).?, .label = "replace", .leaf = .{ .role = .replace_with_yank } }, +}) }; /// pardes's window mode (layout.windowKey): its moves, Collapse and Del; /// a letter picks the pane its box shows. const window_tree: Node = .{ .key = 'w', .label = "window", .group = rootGroup(.window), .children = window: { @@ -248,7 +260,13 @@ const window_tree: Node = .{ .key = 'w', .label = "window", .group = rootGroup(. /// The node `path` reaches under `root`, or null. pub fn nodeAt(root: Root, path: []const u8) ?*const Node { var n = info.get(root).node; - for (path) |k| n = for (n.children) |*c| { + var keys = path; + // A register's name is any key: under each, its verbs. + if (root == .register and path.len > 0) { + n = ®ister_verbs; + keys = path[1..]; + } + for (keys) |k| n = for (n.children) |*c| { if (c.key == k) break c; } else return null; return n; @@ -263,6 +281,8 @@ pub const Child = struct { word: ?*const pardes.Kind.Word = null, group: bool = false, lsp: bool = false, + /// Its label is cut (a register's first line): `…` after it. + more: bool = false, }; /// The most children a level shows: SPC's top has 17, and an addon's /// words (Kind.Registry's 64) may each start a key of their own. @@ -273,6 +293,7 @@ pub const max_children = 96; /// addons' leader words joined in (SPC alone). Bounded by the level and the /// registry's 64 words. pub fn level(p: *const Pardes, root: Root, path: []const u8, out: *[max_children]Child) []Child { + if (root == .register and path.len == 0) return registerLevel(p, out); var n: usize = 0; if (nodeAt(root, path)) |node| for (node.children) |*c| { if (c.leaf) |leaf| if (leaf == .builtin and !builtins.registry.here(p, leaf.builtin)) continue; @@ -300,6 +321,87 @@ pub fn level(p: *const Pardes, root: Root, path: []const u8, out: *[max_children return shown; } +/// The registers `"` shows (SPEC §9), in its order, and what each is: the +/// default first, the ones a name was given (`"ay`) after it, by name, +/// then these, the last four computed from the pane with the keyboard. +pub const register_names = [_]struct { key: u8, name: []const u8 }{ + .{ .key = '"', .name = "yank" }, + .{ .key = '/', .name = "last search" }, + .{ .key = ':', .name = "last command" }, + .{ .key = '|', .name = "last pipe" }, + .{ .key = '+', .name = "system clipboard" }, + .{ .key = '@', .name = "last macro" }, + .{ .key = '%', .name = "this file's name" }, + .{ .key = '.', .name = "the selections" }, + .{ .key = '#', .name = "selection numbers" }, + .{ .key = '_', .name = "black hole" }, +}; + +/// The display columns of a register's first line which-key shows; the +/// rest is `…`. +pub const register_cut = 24; + +/// `"`'s level: a child a register, its label the first line of its value +/// (`—` when empty), cut. Read when the level is (a key, a frame), never +/// kept: the first `register_cut` columns of each, the named ones bounded +/// by the level's room. +fn registerLevel(p: *const Pardes, out: *[max_children]Child) []Child { + var n: usize = 1; + for (p.registers.list.items) |*reg| { + if (reg.name <= ' ' or reg.name > '~' or n == out.len - (register_names.len - 1)) continue; + const k: u8 = @intCast(reg.name); + for (register_names) |r| { + if (r.key == k) break; + } else { + var j = n; + while (j > 1 and out[j - 1].key > k) : (j -= 1) out[j] = out[j - 1]; + out[j] = .{ .key = k, .label = "" }; + n += 1; + } + } + out[0] = .{ .key = '"', .label = "" }; + for (register_names[1..]) |r| { + out[n] = .{ .key = r.key, .label = "" }; + n += 1; + } + for (out[0..n]) |*c| { + const value = registerValue(p, c.key); + const bound = if (value.len > 4 * register_cut) modal.graphemeStart(value, 4 * register_cut) else value.len; + const line = value[0 .. std.mem.indexOfScalar(u8, value[0..bound], '\n') orelse bound]; + const cut = File.byteAtDisplay(p.settings.tab, line, register_cut); + c.label = if (value.len == 0) "—" else line[0..cut]; + c.more = cut < value.len; + } + return out[0..n]; +} + +/// Register `key`'s value as a paste of the pane with the keyboard reads +/// its first range's (edit.registerValue): a stored one's first value; `%` +/// the file's name, `.` the primary selection's text, `#` its number, `_` +/// nothing. Borrowed from the register or the pane, for the frame. +pub fn registerValue(p: *const Pardes, key: u8) []const u8 { + const pane = p.panes[p.view().active] orelse return ""; + switch (key) { + '_' => return "", + '#' => return "1", + '%' => return if (pane.file) |*f| f.path else "", + '.' => { + const f = if (pane.file) |*f| f else return ""; + const t = &pane.body; + const b = edit.cellBounds(.{ .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 }); + const first = File.sourceLine(pane, b.lo_row); + const last = File.sourceLine(pane, b.hi_row); + if (f.content.len == 0) return ""; + const lo = @min(f.content.len, first.ptr - f.content.ptr + @as(usize, @intCast(@max(0, b.lo_col)))); + const hi = @min(f.content.len, last.ptr - f.content.ptr + @as(usize, @intCast(@max(0, b.hi_col)))); + return f.content[lo..modal.nextGrapheme(f.content, @max(lo, hi))]; + }, + else => for (p.registers.list.items) |*reg| { + if (reg.name == key) return if (reg.values.len == 0) "" else reg.values[0]; + } else return "", + } +} + /// A key as a cell shows it: `SPC` for the space. pub fn keyName(key: u8) []const u8 { return if (key == ' ') "SPC" else @as(*const [1]u8, &printable[key - 0x20]); @@ -450,3 +552,67 @@ test "Help's rows: every leaf of every root, spelled as its chord, its word and try std.testing.expectEqual(@as(usize, 4), found); for (flat) |f| try std.testing.expectEqual(f.row.len, f.lower.len); } + +test "\" shows the registers rolled, each its first line; Down unrolls them beside the cursor's value; a register's key goes down to its verbs, Backspace back up, p pastes it" { + const tagline = @import("tagline.zig"); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 40 }); + defer p.deinit(); + const pane = try p.setTestFile("one\ntwo\n"); + try p.registers.put(p.gpa, 'a', "const best = rank(q, name) orelse continue;\nreturn best;", 0, 1, true); + try p.registers.put(p.gpa, '"', "self.dirty = true;", 0, 1, true); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const a = frame.allocator(); + p.clock.now_ns = 5 * std.time.ns_per_s; + p.clock.stepped_ns = p.clock.now_ns; + p.sync(); + // Its key cell at once, the level 300 ms on. + p.update(.{ .key = .{ .cp = '"' } }); + try std.testing.expect(std.mem.endsWith(u8, try tagline.tagText(p, a, pane), " \" …")); + p.advance(p.clock.now_ns); + try std.testing.expectEqual(p.clock.now_ns + 300 * std.time.ns_per_ms, p.view().tag_state.due_ns); + p.clock.now_ns = p.view().tag_state.due_ns; + const rolled = try tagline.tagText(p, a, pane); + try std.testing.expect(std.mem.indexOf(u8, rolled, " \" ▸ \" self.dirty = true; a const best = rank(q, nam… / —") != null); + try std.testing.expect(std.mem.indexOf(u8, rolled, "% /test.txt . o # 1 _ —") != null); + // Down unrolls: a row each, the cursor on the default, its value + // beside them. + p.update(.{ .key = .{ .cp = Key.down } }); + try std.testing.expect(p.view().tag_state.unrolled); + try std.testing.expect(pane.band_rows >= 4); + _ = try p.render(a); + const layer = &p.surface.tag_layers[pardes.BAND_LAYER_BASE + p.view().active]; + var band: std.ArrayList(u8) = .empty; + for (0..layer.rows) |row| for (layer.cells[row * layer.cols ..][0..layer.cols]) |cell| try band.appendSlice(a, cell.grapheme()); + try std.testing.expect(std.mem.indexOf(u8, band.items, "▶ \" yank self.dirty = true;") != null); + try std.testing.expect(std.mem.indexOf(u8, band.items, "\"\" · yank") != null); + // The next row's value in full, every line of it. + p.update(.{ .key = .{ .cp = Key.down } }); + _ = frame.reset(.retain_capacity); + _ = try p.render(a); + band = .empty; + for (0..layer.rows) |row| for (layer.cells[row * layer.cols ..][0..layer.cols]) |cell| try band.appendSlice(a, cell.grapheme()); + try std.testing.expect(std.mem.indexOf(u8, band.items, "const best = rank(q, name) orelse continue;") != null); + try std.testing.expect(std.mem.indexOf(u8, band.items, "return best;") != null); + // Enter chooses it: its verbs, rolled. + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expect(std.mem.indexOf(u8, try tagline.tagText(p, a, pane), " \" a ▸ p after P before R replace y into") != null); + try std.testing.expect(!p.view().tag_state.unrolled); + // Backspace: the registers again; a register's own key goes down too. + p.update(.{ .key = .{ .cp = Key.backspace } }); + try std.testing.expect(std.mem.indexOf(u8, try tagline.tagText(p, a, pane), " \" ▸ \" self.dirty") != null); + p.update(.{ .key = .{ .cp = 'a' } }); + try std.testing.expect(std.mem.indexOf(u8, try tagline.tagText(p, a, pane), " \" a ▸ p after") != null); + // p pastes it after the selection, and the tag is at rest. + p.update(.{ .key = .{ .cp = 'p' } }); + try std.testing.expect(std.mem.indexOf(u8, pane.file.?.content, "const best = rank(q, name) orelse continue;") != null); + try std.testing.expect(p.view().tag_state.root == null); + try std.testing.expect(@import("TagState.zig").hostOf(p) == null); + // Esc from the registers: rest, the keyboard where it was. + const id = p.view().active; + p.update(.{ .key = .{ .cp = '"' } }); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expect(p.view().tag_state.root == null); + try std.testing.expectEqual(id, p.view().active); + try std.testing.expectEqual(@as(u21, 0), pane.body.normal.register); +} diff --git a/core/keys.zig b/core/keys.zig index 04a3cc35..78f45820 100644 --- a/core/keys.zig +++ b/core/keys.zig @@ -376,7 +376,7 @@ pub fn handleKey(p: *Pardes, key: Key) void { return; } if (header == null) if (TagState.current(p, p.view())) |cur| if (cur.root != .leader and cur.root != .window) { - if (prefixKey(p, t, cur.root, key)) return; + if (prefixKey(p, t, cur, key)) return; }; if (t == &pane.body and pane.jump.items.len > 0) return normal.jumpKey(p, pane, t, key); // A query pane's line 1 answers Enter, Esc and the stepping keys @@ -679,15 +679,27 @@ fn levelKey(p: *Pardes, root: bindings.Root, path: []const u8, key: Key) LevelSt /// A key while a helix prefix waits in text `t` (g m z Z [ ]): which-key's /// own, else the prefix's, the leaf it runs remembered. True when taken here. -fn prefixKey(p: *Pardes, t: *Text, root: bindings.Root, key: Key) bool { +fn prefixKey(p: *Pardes, t: *Text, cur: TagState.Current, key: Key) bool { + const root = cur.root; if (root != .register and key.cp == config.leader_help and !key.ctrl and !key.alt) { TagState.openHelp(p, root, ""); return true; } - switch (levelKey(p, root, "", key)) { + // `"` and a register's verbs: Esc goes to rest (normal mode's would + // name the register, or leave the pane). + if (root == .register and hit(key, config.escape)) { + t.normal.clear(); + return true; + } + switch (levelKey(p, root, cur.path, key)) { .taken => return true, .up => { t.normal = .{}; + // A register's verbs go back up to the registers (SPEC §9). + if (root == .register and cur.path.len > 0) { + t.normal.prefix = .register_prefix; + p.view().tag_state.hi = 0; + } return true; }, .take => |c| { @@ -697,7 +709,15 @@ fn prefixKey(p: *Pardes, t: *Text, root: bindings.Root, key: Key) bool { .pass => { if (!key.ctrl and !key.alt and key.cp >= 0x20 and key.cp < 0x7f) { const k: u8 = @intCast(key.cp); - if (bindings.nodeAt(root, &.{k}) != null) TagState.ran(p.view(), root, "", k); + var buf: [2]u8 = .{ 0, k }; + if (cur.path.len > 0) buf[0] = cur.path[0]; + const here = if (cur.path.len > 0) buf[0..2] else buf[1..2]; + if (bindings.nodeAt(root, here) != null) TagState.ran(p.view(), root, cur.path, k); + // A register named: its verbs, rolled, the cursor afresh. + if (root == .register) { + p.view().tag_state.hi = 0; + p.view().tag_state.unrolled = false; + } } return false; }, -- cgit v1.3 From 791d47a64db09f842d23b3d0b03c40951f30aae6 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 22:32:25 -0300 Subject: walk: Enter on a word of the walk with the keyboard in the tag Looks it as a click does (Tab Execs it, as B2), and out of rest the walk folds to its newest word, its older ones `·` (pick-ui SPEC §6.3, §3.4.3, walk UI line F item 5, the gaps line B left): keys.zig handleKey's Enter-in-a-tag asks tagline.trailAt at the cursor's byte before taking the word as a builtin's operand, the keyboard back in the body as a click leaves it; Trail.folded says how many back steps a tag writes whole (shown_steps at rest, one while TagState.hostOf is its pane), which Trail.write, bytes and stepAt now take (wordOf's fold the caller's), so the name's offset (tagline.nameAt), the forward span, a click on a step, the drafted name and the name's tint all read the trail as it is drawn (nameAt, forwardSpan, onName and draw.tagTintRange take the session); TEST: Trail.zig "Enter on a word of the walk, the keyboard in the tag, goes back to its step ..." (SPC folds `‹@pN › · › rank.zig:20 ›`, Esc unfolds, Enter on rank.zig:10 goes back there); core-test 1026/1193 (167 skipped), 0 failed, load 8 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- core/Trail.zig | 61 ++++++++++++++++++++++++++++++++++++++++++++++---------- core/draw.zig | 10 +++++----- core/keys.zig | 7 +++++++ core/mouse.zig | 2 +- core/tagline.zig | 46 ++++++++++++++++++++++++------------------ 5 files changed, 91 insertions(+), 35 deletions(-) (limited to 'core/keys.zig') diff --git a/core/Trail.zig b/core/Trail.zig index b5dff554..571779b4 100644 --- a/core/Trail.zig +++ b/core/Trail.zig @@ -18,6 +18,7 @@ const look = @import("look.zig"); const Pardes = pardes.Pardes; const Pane = panes.Pane; const Spot = look.Spot; +const TagState = @import("TagState.zig"); const Trail = @This(); @@ -275,9 +276,9 @@ pub const Part = enum { back, forward }; /// Step `i`'s word: `‹@p3`, `rank.zig:14`, a list's, search's or recipe's /// own text; `·` when it is folded. -fn wordOf(t: *const Trail, i: usize, buf: *[max_text + 16]u8) []const u8 { +fn wordOf(t: *const Trail, i: usize, whole: usize, buf: *[max_text + 16]u8) []const u8 { const s = t.steps[i]; - if (s != .owner and i < t.cur and t.cur - i > shown_steps) return "·"; + if (s != .owner and i < t.cur and t.cur - i > whole) return "·"; // The step's own bytes, not a copy's (a copy is gone at the return). return switch (t.steps[i]) { .owner => |serial| std.fmt.bufPrint(buf, "‹" ++ config.pane_addr ++ "{d}", .{serial}) catch unreachable, // a u32 fits @@ -297,34 +298,43 @@ fn range(t: *const Trail, part: Part) [2]usize { } /// The back steps' words, each with the separator after it (before the -/// path), or the forward steps', each with one before it (after the path). -pub fn write(t: *const Trail, part: Part, w: *std.Io.Writer) std.Io.Writer.Error!void { +/// path), or the forward steps', each with one before it (after the path): +/// the newest `whole` back steps whole, older ones `·` (`folded`). +pub fn write(t: *const Trail, part: Part, whole: usize, w: *std.Io.Writer) std.Io.Writer.Error!void { var buf: [max_text + 16]u8 = undefined; const r = range(t, part); for (r[0]..r[1]) |i| switch (part) { - .back => try w.print("{s}" ++ sep, .{wordOf(t, i, &buf)}), - .forward => try w.print(sep ++ "{s}", .{wordOf(t, i, &buf)}), + .back => try w.print("{s}" ++ sep, .{wordOf(t, i, whole, &buf)}), + .forward => try w.print(sep ++ "{s}", .{wordOf(t, i, whole, &buf)}), }; } /// The bytes `write` writes for `part`. -pub fn bytes(t: *const Trail, part: Part) usize { +pub fn bytes(t: *const Trail, part: Part, whole: usize) usize { var buf: [max_text + 16]u8 = undefined; var n: usize = 0; const r = range(t, part); - for (r[0]..r[1]) |i| n += wordOf(t, i, &buf).len + sep.len; + for (r[0]..r[1]) |i| n += wordOf(t, i, whole, &buf).len + sep.len; return n; } +/// The back steps pane `pane`'s tag writes whole: `shown_steps` at rest, +/// the newest alone while its tag is out of rest (SPEC §3.4.3), so a +/// state's head and the band's spines keep their room. +pub fn folded(p: *const Pardes, pane: *const Pane) usize { + const host = TagState.hostOf(p) orelse return shown_steps; + return if (p.panes[host] == pane) 1 else shown_steps; +} + /// The step whose word in `part` is at byte `off` of what `write` wrote /// for it, null on a separator or past them. -pub fn stepAt(t: *const Trail, part: Part, off: usize) ?u8 { +pub fn stepAt(t: *const Trail, part: Part, whole: usize, off: usize) ?u8 { var buf: [max_text + 16]u8 = undefined; var x: usize = 0; const r = range(t, part); for (r[0]..r[1]) |i| { if (part == .forward) x += sep.len; - const n = wordOf(t, i, &buf).len; + const n = wordOf(t, i, whole, &buf).len; if (off >= x and off < x + n) return @intCast(i); x += n; if (part == .back) x += sep.len; @@ -722,3 +732,34 @@ test "Jumps new-pane jumps as before the walk: a new pane for a file no pane sho }; try std.testing.expectEqual(open + 2, now); } + +test "Enter on a word of the walk, the keyboard in the tag, goes back to its step as a click does; out of rest the walk folds to its newest word" { + var f: Fixture = .{ .p = undefined, .tmp = undefined }; + try f.init(60); + defer f.deinit(); + const p = f.p; + const owner = p.panes[f.held].?.serial; + for ([_]usize{ 10, 20, 30 }) |line| f.look(f.held, "rank.zig", line); + const r = p.view().active; + const pane = p.panes[r].?; + var buf: [4096 + 128]u8 = undefined; + var at: [64]u8 = undefined; + const rest = try std.fmt.bufPrint(&buf, "‹@p{d} › rank.zig:10 › rank.zig:20 › {s}/rank.zig Keep", .{ owner, f.dir }); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, pane), rest)); + // SPC: out of rest, the older steps are `·`, the owner and the newest + // whole; back at rest, as they were. + p.update(.{ .key = .{ .cp = ' ' } }); + var folded_buf: [4096 + 128]u8 = undefined; + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, pane), try std.fmt.bufPrint(&folded_buf, "‹@p{d} › · › rank.zig:20 › {s}/rank.zig", .{ owner, f.dir }))); + p.update(.{ .key = .{ .cp = pardes.Key.escape } }); + try std.testing.expect(std.mem.startsWith(u8, try tagOf(p, pane), rest)); + // The keyboard in the tag, its cursor on `rank.zig:10`: Enter goes back + // to that step, the keyboard in the body again. + pane.focus = .tag; + pane.tag.cur_row = 0; + pane.tag.cur_col = @intCast(std.mem.indexOf(u8, rest, "rank.zig:10").? + 2); + p.update(.{ .key = .{ .cp = pardes.Key.enter } }); + p.sync(); + try std.testing.expectEqualStrings("rank.zig:10", f.at(&at)); + try std.testing.expect(pane.focus == .body); +} diff --git a/core/draw.zig b/core/draw.zig index 5282b1c9..cf62adf8 100644 --- a/core/draw.zig +++ b/core/draw.zig @@ -631,7 +631,7 @@ fn joinCells(s: *Surface, x: u16, y: u16, cells: []const Cell, from: usize, w: u if (!cells[from].default and cells[from].len == 0) blank(&row[x], ink); } -fn tagTintRange(pane: *const Pane, tag: []const u8, prefix_len: usize) ?struct { lo: usize, hi: usize } { +fn tagTintRange(p: *const Pardes, pane: *const Pane, tag: []const u8, prefix_len: usize) ?struct { lo: usize, hi: usize } { if (pane.isTerminal()) { // `tag` is the first row; a prefix longer than it ran to a second. var words = std.mem.tokenizeAny(u8, tag[@min(prefix_len, tag.len)..], " \t\r\n"); @@ -642,7 +642,7 @@ fn tagTintRange(pane: *const Pane, tag: []const u8, prefix_len: usize) ?struct { } return null; } - var start: usize = tagline.nameAt(pane); + var start: usize = tagline.nameAt(p, pane); const name = if (pane.file) |file| if (pane.prompt == .name) pane.input.own orelse file.path else file.path else if (pane.addon) |k| blk: { @@ -955,7 +955,7 @@ fn paintPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, else if (pane.prompt == .name) caret: { // A drafted name is the prefix: its caret is on row 0 of the tag, // the rows it wrapped onto included. - const at = modal.positionAt(shown.text, shown.fromReal(tagline.nameAt(pane) + @as(usize, @intCast(@max(0, pane.input.cur_col))))); + const at = modal.positionAt(shown.text, shown.fromReal(tagline.nameAt(p, pane) + @as(usize, @intCast(@max(0, pane.input.cur_col))))); if (at.row < top or at.row >= top + rows) break :caret null; break :caret .{ .row = at.row - top, .at = @min(lines[at.row - top].len, at.col) }; } else if (pane.focus == .tag and pane.prompt == .none and head == null) caret: { @@ -975,10 +975,10 @@ fn paintPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, // The name's tint, in the tag's first line, over whichever rows it // wrapped onto. const first_line = whole[0 .. std.mem.indexOfScalar(u8, whole, '\n') orelse whole.len]; - if (tagTintRange(pane, first_line, prefix_len)) |name| if (name.lo < name.hi) + if (tagTintRange(p, pane, first_line, prefix_len)) |name| if (name.lo < name.hi) inkTag(p, s, shown, lines[0..rows], top, tx, tag_y, tw, name.lo, @min(name.hi, first_line.len), if (active) chrome.tag_active_name_fg else chrome.tag_name_fg); // A walk's forward steps, after the name, dimmed (Trail.zig). - const ahead = tagline.forwardSpan(pane); + const ahead = tagline.forwardSpan(p, pane); if (ahead[0] < ahead[1]) inkTag(p, s, shown, lines[0..rows], top, tx, tag_y, tw, ahead[0], @min(ahead[1], first_line.len), chrome.lineno); // The head's keys in the key ink, its dimmed, underlined and struck // words (TagState.Span), over whichever rows they wrapped onto. diff --git a/core/keys.zig b/core/keys.zig index 78f45820..651d6417 100644 --- a/core/keys.zig +++ b/core/keys.zig @@ -401,6 +401,13 @@ pub fn handleKey(p: *Pardes, key: Key) void { break :word .{ b.lo, b.hi }; }; const txt = shown[span[0]..span[1]]; + // On a word of the pane's walk, the step's Look or Exec, as a + // click there (SPEC §6.3). + if (header == null and t.what == .tag) if (tagline.trailAt(p, pane, modal.selectionCursor(shown, range))) |step| { + pane.focus = .body; + if (cmd == config.look_cmd) pardes.Trail.lookStep(p, p.view().active, step) else pardes.Trail.execStep(p, p.view().active, step); + return; + }; // A column tag's command acts on that column, empty or not. p.exec_column = if (header != null) p.headerColumn() else null; defer p.exec_column = null; diff --git a/core/mouse.zig b/core/mouse.zig index 400d020b..48546c12 100644 --- a/core/mouse.zig +++ b/core/mouse.zig @@ -1265,7 +1265,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { // (pick-ui SPEC §6.3): the one place B1 does more than // select. if (!dragged and tagline.trailClick(p, s.id, row, col, false)) return; - if (if (dragged) null else tagline.onName(p.settings.tab, pane, row, col)) |at| { + if (if (dragged) null else tagline.onName(p, pane, row, col)) |at| { tagline.draftName(p, pane, at); } else if (tagline.tagOffsetAt(p, pane, row, col)) |cursor| { pane.tag.cur_row = @intCast(cursor.row); diff --git a/core/tagline.zig b/core/tagline.zig index 78d5a256..e95d68de 100644 --- a/core/tagline.zig +++ b/core/tagline.zig @@ -163,11 +163,12 @@ pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]co // Its walk's back steps before the name, its forward steps after // it (Trail.zig), in the room `bytes` measures them. const keep_word = if (keep) " Keep" else ""; - const room = try arena.alloc(u8, pane.trail.bytes(.back) + name.len + pane.trail.bytes(.forward) + keep_word.len); + const whole = pardes.Trail.folded(p, pane); + const room = try arena.alloc(u8, pane.trail.bytes(.back, whole) + name.len + pane.trail.bytes(.forward, whole) + keep_word.len); var w: std.Io.Writer = .fixed(room); - pane.trail.write(.back, &w) catch return error.OutOfMemory; + pane.trail.write(.back, whole, &w) catch return error.OutOfMemory; w.writeAll(name) catch return error.OutOfMemory; - pane.trail.write(.forward, &w) catch return error.OutOfMemory; + pane.trail.write(.forward, whole, &w) catch return error.OutOfMemory; w.writeAll(keep_word) catch return error.OutOfMemory; return w.buffered(); } @@ -183,17 +184,29 @@ pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]co } /// Where a file's name starts in its tag: after its walk's back steps. -pub fn nameAt(pane: *const Pane) usize { - return if (pane.file != null and pane.trail.n > 0) pane.trail.bytes(.back) else 0; +pub fn nameAt(p: *const Pardes, pane: *const Pane) usize { + return if (pane.file != null and pane.trail.n > 0) pane.trail.bytes(.back, pardes.Trail.folded(p, pane)) else 0; } /// The bytes of a file's tag its walk's forward steps take, after its name. -pub fn forwardSpan(pane: *const Pane) [2]usize { +pub fn forwardSpan(p: *const Pardes, pane: *const Pane) [2]usize { const f = pane.file orelse return .{ 0, 0 }; if (pane.trail.n == 0) return .{ 0, 0 }; + const whole = pardes.Trail.folded(p, pane); const name = if (pane.prompt == .name) pane.input.own orelse f.path else f.path; - const lo = pane.trail.bytes(.back) + name.len; - return .{ lo, lo + pane.trail.bytes(.forward) }; + const lo = pane.trail.bytes(.back, whole) + name.len; + return .{ lo, lo + pane.trail.bytes(.forward, whole) }; +} + +/// The step of pane `pane`'s walk whose word is at byte `at` of its tag's +/// text, if one is there. +pub fn trailAt(p: *const Pardes, pane: *const Pane, at: usize) ?u8 { + if (pane.trail.n == 0 or pane.file == null) return null; + const whole = pardes.Trail.folded(p, pane); + const ahead = forwardSpan(p, pane); + if (at < nameAt(p, pane)) return pane.trail.stepAt(.back, whole, at); + if (at >= ahead[0] and at < ahead[1]) return pane.trail.stepAt(.forward, whole, at - ahead[0]); + return null; } /// A click at shown row `row`, display column `col` of pane `id`'s tag on @@ -201,15 +214,9 @@ pub fn forwardSpan(pane: *const Pane) [2]usize { /// (Trail.zig, pick-ui SPEC §6.3). True when it was on one. pub fn trailClick(p: *Pardes, id: usize, row: usize, col: usize, run: bool) bool { const pane = p.panes[id] orelse return false; - if (pane.trail.n == 0 or pane.file == null) return false; const at = tagOffsetAt(p, pane, row, col) orelse return false; if (at.row != 0) return false; - const lead = nameAt(pane); - const ahead = forwardSpan(pane); - const step = if (at.col < lead) - pane.trail.stepAt(.back, at.col) - else if (at.col >= ahead[0] and at.col < ahead[1]) pane.trail.stepAt(.forward, at.col - ahead[0]) else null; - const i = step orelse return false; + const i = trailAt(p, pane, at.col) orelse return false; if (run) pardes.Trail.execStep(p, id, i) else pardes.Trail.lookStep(p, id, i); return true; } @@ -402,14 +409,15 @@ pub fn tagOffsetAt(p: *Pardes, pane: *Pane, row: usize, col: usize) ?modal.Curso /// The display column in the name a click drafts at display column `col` /// of the tag's shown row `row`: on a saving file's path, after its walk's /// words; null off it. -pub fn onName(tab: u16, pane: *Pane, row: usize, col: usize) ?usize { +pub fn onName(p: *const Pardes, pane: *Pane, row: usize, col: usize) ?usize { + const tab = p.settings.tab; if (row + pane.tag_top != 0) return null; const f = pane.file orelse return null; if (!panes.Output.fileTraits(f.output).saves) return null; const name = if (pane.prompt == .name) pane.input.own orelse f.path else f.path; var room: [pardes.Trail.max_steps * (pardes.Trail.max_text + 32)]u8 = undefined; var w: std.Io.Writer = .fixed(&room); - pane.trail.write(.back, &w) catch return null; + pane.trail.write(.back, pardes.Trail.folded(p, pane), &w) catch return null; const lead = panes.File.displayWidth(tab, w.buffered()); if (col < lead or col >= lead + panes.File.displayWidth(tab, name)) return null; return col - lead; @@ -424,8 +432,8 @@ pub fn typedIntoName(p: *Pardes, pane: *Pane, key: pardes.Key) bool { if (!panes.Output.fileTraits(f.output).saves or pane.tag.cur_row != 0) return false; // The name starts after its walk's words. const col: usize = @intCast(@max(0, pane.tag.cur_col)); - if (col < nameAt(pane)) return false; - const at = col - nameAt(pane); + if (col < nameAt(p, pane)) return false; + const at = col - nameAt(p, pane); const back = key.cp == pardes.Key.backspace or pardes.hit(key, config.insert_backspace_alias); const forward = key.cp == pardes.Key.delete or pardes.hit(key, config.insert_delete_alias); const typed = key.text.len > 0 and !key.ctrl and !key.alt; -- cgit v1.3 From 5d091b37b4641c274900d4d02b7f1d61b5a9301f Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 24 Nov 2026 22:51:55 -0300 Subject: lsp: a hover (SPC l k) and a rename (SPC l r) asked from the keyboard show in the edited pane's own body: the hover as ghost lines under the line it was asked at, no +Hover pane, Esc taking them away; Rename typed in that pane's tag (` Rename best → bester▌`, the old name struck), each whole-word place of the old name in the rows shown drawn struck with the new name after it as it is typed, Enter asking the server for it (its edits applied as before), Esc asking nothing (pick-ui SPEC §3.5, §14.1, R3, walk UI line F item 3, its hover and rename; code actions NOT done: the protocol client sends an action's title alone, no edit to preview or apply): Ask.hover (its pane, line, revision and first 1,024 bytes, in the dump; an edit of the text stops it showing), body_layer.hoverGhosts and renameGhosts (drawn after the rows as the message ghosts are, the rows below pushed down or a row's cells pushed right, never written, the rows shown alone), TagState.Kind.rename (its head; no band), Ask.openRename and renameKey, the name under the caret Ask.renamedWord (the preview is pardes's own whole-word match in view, the edit the server's on Enter); under `Jumps new-pane` or from a 9P script, +Hover and the rename prompt as before; TESTS: Ask.zig "a hover asked from the keyboard is ghost lines ..." and "SPC l r types the new name in the pane's own tag ..."; core-test 1029/1196 (167 skipped), 0 failed, load 8 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- core/Band.zig | 2 + core/TagState.zig | 17 +++++- core/body_layer.zig | 90 +++++++++++++++++++++++++++++++ core/builtins.zig | 3 ++ core/keys.zig | 7 +++ core/lsp/Ask.zig | 149 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 6 files changed, 267 insertions(+), 1 deletion(-) (limited to 'core/keys.zig') diff --git a/core/Band.zig b/core/Band.zig index 13c4b9c0..63407626 100644 --- a/core/Band.zig +++ b/core/Band.zig @@ -100,6 +100,7 @@ pub fn takes(p: *Pardes, id: usize) u16 { return @max(doc_rows, levelRows(@intCast(bindings.level(p, s.scope_root.?, s.scope[0 .. s.scope_n - 1], &children).len))); }, .pick => return @import("Pick.zig").bandRows(p), + .rename => return 0, } if (!s.unrolled) return 0; const cur = TagState.current(p, v) orelse return 0; @@ -151,6 +152,7 @@ pub fn of(p: *Pardes, arena: std.mem.Allocator, pane: *Pane, id: usize) !?Band { try band.place(p, arena, pane, id); return band; }, + .rename => return null, } const cur = TagState.current(p, v).?; if (cur.root == .register) { diff --git a/core/TagState.zig b/core/TagState.zig index 95df8937..1d6abace 100644 --- a/core/TagState.zig +++ b/core/TagState.zig @@ -24,12 +24,13 @@ const Root = bindings.Root; const Field = @import("Field.zig"); const Band = @import("Band.zig"); const Names = @import("Names.zig"); +const Ask = @import("lsp/Ask.zig"); /// The tag's states besides a root's level (which `kind` rest with a root /// current is): `help`, a field over every leaf (SPEC §4.5); `describe`, /// a sequence replayed in the tree (item 5); `pick`, a picker (Pick.zig, /// SPEC §5). -pub const Kind = enum(u8) { rest, help, describe, pick }; +pub const Kind = enum(u8) { rest, help, describe, pick, rename }; pub const replica = .{ .len = .{ .{ "scope", "scope_n" }, .{ "hits", "nhits" } } }; @@ -483,6 +484,20 @@ pub fn head(p: *Pardes, arena: std.mem.Allocator, pane: *Pane) !?Head { return b.done(); }, .pick => return @import("Pick.zig").head(p, arena, pane), + // `Rename`, the name under the caret struck, the new one typed: + // ` Rename best → top▌ ⏎ rename · esc` (SPEC §3.5). + .rename => { + try b.put(" Rename "); + try b.styled(Ask.renamedWord(pane) orelse "", .strike); + try b.put(" → "); + var h = b.done(); + h.caret = @intCast(b.text.items.len + s.field.caret); + try b.put(s.field.text()); + try b.put(" ⏎ rename · esc"); + h.text = b.text.items; + h.spans = b.spans.items; + return h; + }, } const cur = current(p, v) orelse return null; try b.put(" "); diff --git a/core/body_layer.zig b/core/body_layer.zig index 13fc7a85..13c24f97 100644 --- a/core/body_layer.zig +++ b/core/body_layer.zig @@ -472,6 +472,8 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane } if (pane.file != null) paintTargets(p, s, arena, pane, r, tx, tw, body_y, body_h); + if (p.lsp_ask.hover != null) hoverGhosts(p, s, pane, tx, tw, body_y, body_h); + if (p.view().tag_state.kind == .rename) renameGhosts(p, s, pane, tx, tw, body_y, body_h); // `gw`'s labels, two letters over the start of each word if (pane.jump.items.len > 0) labels: { @@ -632,6 +634,94 @@ fn paintTargets(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, } } +/// A hover's answer as ghost lines under the line it was asked at (SPEC +/// §3.5, R3): the rows below move down by its lines (those past the body's +/// foot not shown meanwhile), the buffer untouched. Bounded by the rows +/// shown and the hover's `Ask.hover_max` bytes. +fn hoverGhosts(p: *Pardes, s: *Surface, pane: *Pane, tx: u16, tw: u16, body_y: u16, body_h: u16) void { + const h = &p.lsp_ask.hover.?; + if (h.serial != pane.serial) return; + const f = if (pane.file) |*file| file else return; + if (f.revision != h.revision) return; + const tab = p.settings.tab; + // The last row the line is shown on. + var under: ?u16 = null; + var row: u16 = pane.context_rows; + while (row < body_h) : (row += 1) { + if (pane.wrapAt(tab, row).line == h.row) under = row else if (under != null) break; + } + const at = under orelse return; + const text = std.mem.trimEnd(u8, h.text.slice(), "\n"); + const k: u16 = @intCast(@min(std.mem.count(u8, text, "\n") + 1, body_h - at - 1)); + if (k == 0) return; + var dst: u16 = body_h - 1; + while (dst >= at + 1 + k) : (dst -= 1) { + const to = @as(usize, body_y + dst) * s.cols + tx; + const from = @as(usize, body_y + dst - k) * s.cols + tx; + @memcpy(s.cells[to..][0..tw], s.cells[from..][0..tw]); + } + const th = p.theme(); + const style: CellStyle = .{ .fg = .{ .rgb = th.tag_fg }, .bg = .{ .rgb = th.tag_bg } }; + const gutter: u16 = File.gutterWidth(pane); + var lines = std.mem.splitScalar(u8, text, '\n'); + for (0..k) |i| { + const y = body_y + at + 1 + @as(u16, @intCast(i)); + s.fill(tx, y, tw, 1, .{ .bg = .{ .rgb = th.tag_bg } }); + if (gutter + 2 < tw) _ = s.print(tx + gutter + 2, y, tw - gutter - 2, lines.next() orelse "", style); + } +} + +/// A Rename typed in this body's tag, shown in its rows (SPEC §3.5, R3): +/// each whole-word place of the name under the caret in the rows shown +/// struck, the name typed after it, the rest of its row pushed right. +/// Never written; bounded by the rows shown. +fn renameGhosts(p: *Pardes, s: *Surface, pane: *Pane, tx: u16, tw: u16, body_y: u16, body_h: u16) void { + const host = TagState.hostOf(p) orelse return; + if (p.panes[host] != pane or pane.file == null) return; + const old = @import("lsp/Ask.zig").renamedWord(pane) orelse return; + const new = p.view().tag_state.field.text(); + const tab = p.settings.tab; + const chrome = p.chromeTheme(); + const th = p.theme(); + const added: CellStyle = .{ .fg = .{ .rgb = chrome.diagnostic_hint }, .bg = if (th.bg) |c| .{ .rgb = c } else .default, .bold = true }; + const wide: u16 = @intCast(@min(File.displayWidth(tab, new), tw)); + const gutter: i32 = File.gutterWidth(pane); + var row: u16 = pane.context_rows; + while (row < body_h) : (row += 1) { + const w = pane.wrapAt(tab, row); + if (w.line < 0) continue; + const line = File.sourceLine(pane, w.line); + const from: usize = @min(line.len, @as(usize, @intCast(@max(0, w.at)))); + const next = pane.wrapAt(tab, row + 1); + const to: usize = if (next.line == w.line) @min(line.len, @as(usize, @intCast(@max(0, next.at)))) else line.len; + // Right to left, so a push leaves the places before it where they are. + var end = to; + while (std.mem.lastIndexOf(u8, line[from..end], old)) |k| { + const at = from + k; + end = at; + const before = at > 0 and (std.ascii.isAlphanumeric(line[at - 1]) or line[at - 1] == '_'); + const after = at + old.len < line.len and (std.ascii.isAlphanumeric(line[at + old.len]) or line[at + old.len] == '_'); + if (before or after) continue; + const c0 = gutter + w.pad + File.displayOffset(tab, pane, w.line, w.at, @intCast(at)); + const c1 = gutter + w.pad + File.displayOffset(tab, pane, w.line, w.at, @intCast(at + old.len)); + if (c0 < gutter or c1 > tw) continue; + const y = body_y + row; + var c: u16 = @intCast(c0); + while (c < c1) : (c += 1) { + const cell = s.at(tx + c, y); + cell.style.strikethrough = true; + cell.style.fg = .{ .rgb = chrome.diagnostic_error }; + } + const x: u16 = @intCast(c1); + if (x + wide < tw) { + const cells = s.cells[@as(usize, y) * s.cols + tx ..][0..tw]; + std.mem.copyBackwards(Cell, cells[x + wide ..], cells[x .. tw - wide]); + } + _ = s.print(tx + x, y, tw - x, new, added); + } + } +} + /// The line a motion role would go to from the caret of `pane`, looked for /// in lines `lo` to `hi` (the rows shown) alone; null for none there, or a /// role that is no line's. diff --git a/core/builtins.zig b/core/builtins.zig index eac52555..ffb82c4b 100644 --- a/core/builtins.zig +++ b/core/builtins.zig @@ -2275,6 +2275,9 @@ pub const Rename = struct { pub fn run(c: Ctx) void { const a = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); if (a.len > 0) return c.p.lspRequest(c.id, .rename, a); + // From the keyboard, where the walk is on: typed in the pane's own + // tag, its edits drawn in its body as they are typed (SPEC §3.5). + if (pardes.Pick.asked(c.p) and c.pane.file != null) return @import("lsp/Ask.zig").openRename(c.p, c.id); panes.startPrompt(c.p, c.pane, &c.pane.body, .{ .search = config.rename_marker }); } }; diff --git a/core/keys.zig b/core/keys.zig index 651d6417..6dea7278 100644 --- a/core/keys.zig +++ b/core/keys.zig @@ -213,6 +213,12 @@ pub fn handleKey(p: *Pardes, key: Key) void { } // A tag in a typing state takes every key (TagState: Help, describe-key). if (p.view().tag_state.kind != .rest) return tagStateKey(p, key); + // Esc takes a hover's ghost lines away (SPEC §3.5) before anything else + // it does. + if (p.lsp_ask.hover != null and hit(key, config.escape)) { + p.lsp_ask.hover = null; + return; + } if (p.view().window_pick != null) return layout.windowKey(p, key); const pane = p.panes[p.view().active] orelse return; layout.noteTyped(p); @@ -583,6 +589,7 @@ fn tagStateKey(p: *Pardes, key: Key) void { TagState.describeKey(p, key); }, .pick => return @import("Pick.zig").key(p, key), + .rename => return @import("lsp/Ask.zig").renameKey(p, key), .help => { const plain = !key.ctrl and !key.alt; if (plain and key.cp == Key.enter) { diff --git a/core/lsp/Ask.zig b/core/lsp/Ask.zig index 976821d5..f8cb8cfc 100644 --- a/core/lsp/Ask.zig +++ b/core/lsp/Ask.zig @@ -18,6 +18,7 @@ const memory = @import("../memory.zig"); const Pardes = pardes.Pardes; const Pane = panes.Pane; const Effect = pardes.Effect; +const TagState = @import("../TagState.zig"); const Ask = @This(); @@ -38,6 +39,12 @@ wait: ?struct { row: i32 = 0, col: i32 = 0, } = null, +/// A hover asked from the keyboard (where the walk is on), drawn as ghost +/// lines under the line it was asked at in its own body (pick-ui SPEC §3.5, +/// the coordinator's R3: never written): until Esc, an edit of that text, +/// or the next hover. Its first `hover_max` bytes. +hover: ?struct { serial: u32, row: i32, revision: u32, text: Effect.Buf(hover_max) } = null, +pub const hover_max = 1024; const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8) void { @@ -247,6 +254,48 @@ fn applyLspEdits(p: *Pardes, pane: *Pane, revision: u32, edits: []const LspEdit) return true; } +/// Rename typed in pane `id`'s own tag (SPEC §3.5): the field the name +/// under its caret, which the body shows renamed as it is typed +/// (body_layer.renameGhosts) until Enter asks the server, or Esc. +pub fn openRename(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + const old = renamedWord(pane) orelse return p.reportFailure(id, "Rename: nothing here to rename"); + TagState.toRest(p); + const s = &p.view().tag_state; + s.kind = .rename; + s.host = pane.serial; + s.field.set(old); + s.previewing.set(id); +} + +/// A key in Rename's field: Enter asks the server to rename to it (a name +/// the same as the old is no question), Esc (the tag's) puts it away. +pub fn renameKey(p: *Pardes, key: pardes.Key) void { + const s = &p.view().tag_state; + if (!key.ctrl and !key.alt and key.cp == pardes.Key.enter) { + const id = TagState.hostOf(p) orelse return TagState.toRest(p); + var name: Effect.Buf(128) = .{}; + const typed = std.mem.trim(u8, s.field.text(), " "); + const same = std.mem.eql(u8, typed, renamedWord(p.panes[id].?) orelse ""); + if (typed.len <= 128) name = .from(typed); + TagState.toRest(p); + if (same) return; + if (typed.len > 128) return p.reportFailure(id, "Rename: a name is at most 128 bytes"); + return lspRequest(p, id, .rename, name.slice()); + } + _ = s.field.key(key); +} + +/// The name under pane `pane`'s caret, which a Rename renames. +pub fn renamedWord(pane: *const Pane) ?[]const u8 { + const line = panes.File.sourceLine(pane, pane.body.cur_row); + var lo: usize = @min(@as(usize, @intCast(@max(0, pane.body.cur_col))), line.len); + var hi = lo; + while (lo > 0 and (std.ascii.isAlphanumeric(line[lo - 1]) or line[lo - 1] == '_')) lo -= 1; + while (hi < line.len and (std.ascii.isAlphanumeric(line[hi]) or line[hi] == '_')) hi += 1; + return if (hi > lo) line[lo..hi] else null; +} + /// The builtin word that asks `kind`, for what it says. fn lspWord(kind: lsp.Kind) []const u8 { return switch (kind) { @@ -333,6 +382,14 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { return; } + // A hover asked from the keyboard: ghost lines in its own body, no + // +Hover pane (SPEC §3.5). + if (w.kind == .hover and pardes.Pick.asked(p)) { + var cut = @min(rows.len, hover_max); + while (cut < rows.len and cut > 0 and rows[cut] & 0xC0 == 0x80) cut -= 1; + p.lsp_ask.hover = .{ .serial = pane.serial, .row = w.row, .revision = w.revision, .text = .from(rows[0..cut]) }; + return; + } const from: panes.Output.Origin = .{ .query = w.kind }; const nrows = std.mem.count(u8, rows, "\n"); if ((panes.Output.traits(from).jumps or w.kind == .diagnostics) and nrows == 1) { @@ -626,3 +683,95 @@ test "LSP failure clears only its matching wait without completion indentation" try std.testing.expectEqualStrings("x ", pane.file.?.content); try std.testing.expectEqual(@as(i32, 4), pane.body.cur_col); } + +test "a hover asked from the keyboard is ghost lines under the line it was asked at, drawn and never written, no +Hover pane; Esc takes them away" { + if (!lsp.supports.contains(.hover)) return error.SkipZigTest; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 20 }); + defer p.deinit(); + const pane = try p.setTestFile("one\ntwo\nthree\nfour\n"); + const id = p.view().active; + p.settings.jumps = .walk; + while (p.nextEffect()) |_| {} + pane.focus = .body; + pane.body.cur_row = 1; + var npanes: usize = 0; + for (p.panes) |slot| npanes += @intFromBool(slot != null); + p.lspRequest(id, .hover, ""); + while (p.nextEffect()) |_| {} + lspResponse(p, p.lsp_ask.seq, "pub fn add(a: i32) i32\nadds them\n"); + var now: usize = 0; + for (p.panes) |slot| now += @intFromBool(slot != null); + try std.testing.expectEqual(npanes, now); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + p.sync(); + var s = try p.render(frame.allocator()); + const body = s.region(.body, id).?.rect; + var buf: [256]u8 = undefined; + try std.testing.expect(std.mem.indexOf(u8, rowText(s, body.x, body.y + 1, &buf), "two") != null); + try std.testing.expect(std.mem.indexOf(u8, rowText(s, body.x, body.y + 2, &buf), "pub fn add(a: i32) i32") != null); + try std.testing.expect(std.mem.indexOf(u8, rowText(s, body.x, body.y + 3, &buf), "adds them") != null); + try std.testing.expect(std.mem.indexOf(u8, rowText(s, body.x, body.y + 4, &buf), "three") != null); + try std.testing.expectEqualStrings("one\ntwo\nthree\nfour\n", pane.file.?.content); + p.update(.{ .key = .{ .cp = pardes.Key.escape } }); + try std.testing.expect(p.lsp_ask.hover == null); + try std.testing.expectEqual(id, p.view().active); + _ = frame.reset(.retain_capacity); + s = try p.render(frame.allocator()); + try std.testing.expect(std.mem.indexOf(u8, rowText(s, body.x, body.y + 2, &buf), "three") != null); +} + +/// Grid row `y` of `s` from column `x`, as text. +fn rowText(s: *const pardes.Surface, x: u16, y: u16, buf: []u8) []const u8 { + var n: usize = 0; + for (x..s.cols) |col| { + const g = s.cells[@as(usize, y) * s.cols + col].grapheme(); + if (n + g.len > buf.len) break; + @memcpy(buf[n..][0..g.len], g); + n += g.len; + } + return buf[0..n]; +} + +test "SPC l r types the new name in the pane's own tag, the body showing each place in view renamed as it is typed, never written; Enter asks the server for it, Esc puts it away" { + if (!lsp.supports.contains(.rename)) return error.SkipZigTest; + const Key = pardes.Key; + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 80, .rows = 20 }); + defer p.deinit(); + const pane = try p.setTestFile("const best = 1;\nconst b = best + best;\nconst bestow = 2;\n"); + const id = p.view().active; + p.settings.jumps = .walk; + pane.focus = .body; + pane.body.cur_row = 0; + pane.body.cur_col = 7; + for (" lr") |c| p.update(.{ .key = .{ .cp = c } }); + const s = &p.view().tag_state; + try std.testing.expectEqual(TagState.Kind.rename, s.kind); + try std.testing.expectEqualStrings("best", s.field.text()); + for ("er") |c| p.update(.{ .key = .{ .cp = c } }); + var frame = std.heap.ArenaAllocator.init(std.testing.allocator); + defer frame.deinit(); + const a = frame.allocator(); + try std.testing.expect(std.mem.indexOf(u8, try pardes.tagline.tagText(p, a, pane), " Rename best → bester") != null); + p.sync(); + const sf = try p.render(a); + const body = sf.region(.body, id).?.rect; + var buf: [256]u8 = undefined; + // Each `best` in view struck and followed by the new name; `bestow` is + // another word. + try std.testing.expect(std.mem.indexOf(u8, rowText(sf, body.x, body.y, &buf), "const bestbester = 1;") != null); + try std.testing.expect(std.mem.indexOf(u8, rowText(sf, body.x, body.y + 1, &buf), "const b = bestbester + bestbester;") != null); + try std.testing.expect(std.mem.indexOf(u8, rowText(sf, body.x, body.y + 2, &buf), "const bestow = 2;") != null); + try std.testing.expectEqualStrings("const best = 1;\nconst b = best + best;\nconst bestow = 2;\n", pane.file.?.content); + // Enter: the server asked to rename it, the tag at rest. + while (p.nextEffect()) |_| {} + p.update(.{ .key = .{ .cp = Key.enter } }); + try std.testing.expectEqual(TagState.Kind.rest, s.kind); + try std.testing.expectEqualStrings("bester", p.lsp_ask.wait.?.arg.slice()); + // Esc from the field asks nothing. + p.lsp_ask.wait = null; + for (" lr") |c| p.update(.{ .key = .{ .cp = c } }); + p.update(.{ .key = .{ .cp = Key.escape } }); + try std.testing.expectEqual(TagState.Kind.rest, s.kind); + try std.testing.expect(p.lsp_ask.wait == null); +} -- cgit v1.3