//! A text prompt in a pane's tag (walk UI, pick-ui SPEC.md §7): `s S K A-K` //! select by a pattern, `| A-| ! A-! $` pipe through a command, typed in //! the head's field after the prompt's key cell, the plain word it stands //! for and its count beside it (`s self = Exec Edit x/self/ 4 selections in //! 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 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 //! a tag's text or a header's still asks on the notice band (panes.zig //! startPrompt), as does Save's. const Prompt = @This(); const std = @import("std"); const pardes = @import("root.zig"); const config = @import("config.zig"); const modal = @import("modal.zig"); const panes = @import("panes.zig"); const normal = @import("normal.zig"); const edit = @import("edit.zig"); const regexp = @import("regexp.zig"); const tagline = @import("tagline.zig"); const Pipe = @import("Pipe.zig"); const Field = @import("Field.zig"); const Band = @import("Band.zig"); const TagState = @import("TagState.zig"); const Kind = @import("Kind.zig"); const Pardes = pardes.Pardes; const Pane = panes.Pane; const Text = panes.Text; const Key = pardes.Key; const hit = pardes.hit; pub const Op = enum(u8) { search, search_back, select, split, keep, remove, pipe, pipe_to, insert, append, keep_pipe, command }; op: Op = .select, /// Up and Down's place in its history: 0 the field as typed, n the n-th /// newest line. recall: u8 = 0, /// Ctrl-r: its history unrolled under the tag, filtered by the field. history: bool = false, /// The field is no regex: the body keeps the last result, dimmed, and the /// count says why. bad: bool = false, /// The ranges the last pattern found (0: none, the selections it started /// from back), and the lines those it started from cover. found: u16 = 0, scope: u32 = 0, /// The session's prompt histories: the lines Enter took, newest last. pub const History = struct { search: Ring = .{}, pipe: Ring = .{}, command: Ring = .{}, }; pub const Ring = struct { pub const replica = .{ .len = .{.{ "lines", "n" }} }; /// The lines a history keeps; past it the oldest goes. pub const max = 16; lines: [max]Kind.Buf(Field.max) = undefined, n: u8 = 0, /// `line` the newest, an older copy of it gone. pub fn add(r: *Ring, line: []const u8) void { if (line.len == 0) return; var w: u8 = 0; for (r.lines[0..r.n]) |l| if (!std.mem.eql(u8, l.slice(), line)) { r.lines[w] = l; w += 1; }; r.n = w; if (r.n == max) { std.mem.copyForwards(Kind.Buf(Field.max), r.lines[0 .. max - 1], r.lines[1..]); r.n -= 1; } r.lines[r.n].set(line); r.n += 1; } /// The `back`-th newest line, 1 the newest. pub fn get(r: *const Ring, back: u8) ?[]const u8 { if (back == 0 or back > r.n) return null; return r.lines[r.n - back].slice(); } }; const Info = struct { /// Its key cell. cell: []const u8, hint: []const u8, }; const info = std.EnumArray(Op, Info).init(.{ .search = .{ .cell = "/", .hint = "⏎ land · C-r history · esc" }, .search_back = .{ .cell = "?", .hint = "⏎ land · C-r history · esc" }, .select = .{ .cell = "s", .hint = "⏎ select · C-r history · esc" }, .split = .{ .cell = "S", .hint = "⏎ select · C-r history · esc" }, .keep = .{ .cell = "K", .hint = "⏎ keep · C-r history · esc" }, .remove = .{ .cell = "A-K", .hint = "⏎ keep · C-r history · esc" }, .pipe = .{ .cell = "|", .hint = "⏎ replace · C-r history · esc" }, .pipe_to = .{ .cell = "A-|", .hint = "⏎ run · C-r history · esc" }, .insert = .{ .cell = "!", .hint = "⏎ insert · C-r history · esc" }, .append = .{ .cell = "A-!", .hint = "⏎ append · C-r history · esc" }, .keep_pipe = .{ .cell = "$", .hint = "⏎ keep · C-r history · esc" }, .command = .{ .cell = ":", .hint = "⏎ run · C-r history · esc" }, }); /// The history `op` reads and Enter adds to. fn ring(p: *Pardes, op: Op) *Ring { return switch (op) { .search, .search_back, .select, .split, .keep, .remove => &p.prompt_history.search, .pipe, .pipe_to, .insert, .append, .keep_pipe => &p.prompt_history.pipe, .command => &p.prompt_history.command, }; } pub fn ofMode(m: modal.Normal.RegexMode) Op { return switch (m) { .select => .select, .split => .split, .keep => .keep, .remove => .remove, }; } fn mode(op: Op) ?modal.Normal.RegexMode { return switch (op) { .select => .select, .split => .split, .keep => .keep, .remove => .remove, else => null, }; } pub fn ofBehavior(how: modal.Normal.PipeBehavior) Op { return switch (how) { .replace => .pipe, .ignore => .pipe_to, .insert => .insert, .append => .append, .keep => .keep_pipe, }; } fn behavior(op: Op) ?modal.Normal.PipeBehavior { return switch (op) { .pipe => .replace, .pipe_to => .ignore, .insert => .insert, .append => .append, .keep_pipe => .keep, else => null, }; } /// Prompt `op` in the tag of `pane`, the pane with the keyboard, for its /// body: its field empty, the body's selections as they are (`s S K A-K` /// select inside them, Esc puts them back). pub fn open(p: *Pardes, pane: *Pane, op: Op) void { // Nobody is at the keyboard to answer a command a script wrote to a // ctl file: the write fails instead (core/ninep/ctl.zig). if (p.fs.no_prompt) { p.fs.refused = true; p.fs.failures +%= 1; return; } const t = &pane.body; // A body is piped only when it is a file that saves. if (behavior(op) != null) { const f = pane.file orelse return; if (!panes.Output.fileTraits(f.output).saves) return; } var scope: u32 = 0; if (mode(op) != null) { const text = edit.flatSurface(p.editor(), t) catch |err| return p.reportError(.at(p.view().active), "prompt", err); const got = t.ranges(text, 0, &pane.sel_snap); pane.nsel_snap = @intCast(got.n); pane.sel_snap_pri = @intCast(got.pri); pane.sel_snap_expl = t.vsel.active and t.vsel.explicit; for (pane.sel_snap[0..got.n]) |r| { const lo = @min(r.anchor, r.head, text.len); const hi = @min(@max(r.anchor, r.head), text.len); scope += @intCast(std.mem.count(u8, text[lo..hi -| @intFromBool(hi > lo and text[hi - 1] == '\n')], "\n") + 1); } } pane.focus = .body; tagline.exitHeader(p); t.mode = .normal; t.normal.clear(); TagState.toRest(p); const s = &p.view().tag_state; s.kind = .prompt; s.host = pane.serial; s.field.clear(); s.rows = .{}; s.prompt = .{ .op = op, .scope = scope }; } /// A key in the prompt of the live view's tag: the field's editing keys, /// and the prompt's own. pub fn key(p: *Pardes, k: Key) void { const v = p.view(); const s = &v.tag_state; const id = TagState.hostOf(p) orelse return TagState.toRest(p); const pane = p.panes[id].?; const plain = !k.ctrl and !k.alt; const ctrl = k.ctrl and !k.alt; if (hit(k, config.escape)) return cancel(p, pane); if (plain and k.cp == Key.enter) return commit(p, id, pane); // Backspace on an empty field: the prompt goes, as Esc. if (plain and k.cp == Key.backspace and s.field.len == 0) return cancel(p, pane); // Up and Down bring its history's lines into the field, the newest first. if (plain and (k.cp == Key.up or k.cp == Key.down)) { const r = ring(p, s.prompt.op); const to: u8 = if (k.cp == Key.up) @min(r.n, s.prompt.recall + 1) else s.prompt.recall -| 1; if (to == s.prompt.recall) return; s.prompt.recall = to; s.field.set(r.get(to) orelse ""); return live(p, pane); } if (ctrl and k.cp == 'r') { s.prompt.history = !s.prompt.history; return; } if (!s.field.key(k)) return; s.prompt.recall = 0; live(p, pane); } /// What the field says now, done to the body: the selections a pattern /// finds inside the ones the prompt began with; none, or no pattern, those /// it began with. A pattern that is no regex changes nothing, and the /// prompt says why. fn live(p: *Pardes, pane: *Pane) void { const s = &p.view().tag_state; const m = mode(s.prompt.op) orelse return; const pat = s.field.text(); s.prompt.bad = pat.len > 0 and if (regexp.Regex.compile(pat)) |_| false else |_| true; if (s.prompt.bad) return; s.prompt.found = @intCast(normal.applySelRegex(p, pane, &pane.body, pat, m)); } /// Enter: what the field says, applied, and the line kept in its history /// and its register (`/` a pattern's, `|` a command's). fn commit(p: *Pardes, id: usize, pane: *Pane) void { const s = &p.view().tag_state; const op = s.prompt.op; const line = s.field.text(); // The field is the view's: what is kept of it is copied before rest. var kept: [Field.max]u8 = undefined; @memcpy(kept[0..line.len], line); const typed = kept[0..line.len]; const bad = s.prompt.bad; s.kind = .rest; TagState.toRest(p); if (typed.len == 0) return undo(p, pane, op); ring(p, op).add(typed); if (mode(op) != null) { // No regex: the selections it began with, and why. if (bad) { undo(p, pane, op); return p.setMessage(.at(id), regexMessage(typed)); } // 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 = '/'; return; } if (behavior(op)) |how| { p.registers.put(p.gpa, '|', typed, 0, 1, true) catch |err| return p.reportError(.at(id), "prompt", err); return Pipe.submit(p, id, &pane.body, how, typed); } } /// Esc: the prompt goes and the body is as it was before it. fn cancel(p: *Pardes, pane: *Pane) void { const op = p.view().tag_state.prompt.op; p.view().tag_state.kind = .rest; TagState.toRest(p); undo(p, pane, op); } /// The live effect of prompt `op` on `pane`'s body taken back. fn undo(p: *Pardes, pane: *Pane, op: Op) void { if (mode(op)) |m| _ = normal.applySelRegex(p, pane, &pane.body, "", m); pane.nsel_snap = 0; } /// The prompt left by something else than its keys (TagState.toRest: a /// click, a word run from the band): its effect taken back, as Esc's. pub fn leave(p: *Pardes) void { const s = &p.view().tag_state; const pane = p.panes[TagState.hostOf(p) orelse return] orelse return; s.kind = .rest; undo(p, pane, s.prompt.op); } /// A paste into the field: its first line. pub fn paste(p: *Pardes, bytes: []const u8) void { const s = &p.view().tag_state; const pane = p.panes[TagState.hostOf(p) orelse return] orelse return; const line = bytes[0 .. std.mem.indexOfAny(u8, bytes, "\r\n") orelse bytes.len]; s.field.insert(line[0..modal.graphemeStart(line, @min(line.len, Field.max - s.field.len))]); s.prompt.recall = 0; live(p, pane); } /// Whether `pane`'s body shows a selecting prompt's live result: its /// selections drawn as a preview (body_layer), dimmed while the field is /// no regex. pub fn selecting(p: *const Pardes, pane: *const Pane) ?struct { dim: bool } { const s = &p.view().tag_state; if (s.kind != .prompt or mode(s.prompt.op) == null or s.host != pane.serial) return null; return .{ .dim = s.prompt.bad }; } fn regexMessage(pat: []const u8) []const u8 { return if (regexp.Regex.compile(pat)) |_| "" else |err| regexp.Regex.message(err); } /// The sam command a pattern prompt is (`s S K A-K` are sam's `x y g v`), /// its `/` written `\/`. fn samWord(w: *std.Io.Writer, c: u8, pat: []const u8) !void { try w.print("{c}/", .{c}); for (pat) |b| if (b == '/') try w.writeAll("\\/") else try w.writeByte(b); try w.writeByte('/'); } /// The plain word prompt `op` with field `line` stands for: what Look or /// Exec would do typed in a tag. None for `! A-! $`, which sam cannot say. fn plainWord(w: *std.Io.Writer, op: Op, line: []const u8) !?[]const u8 { switch (op) { .search => try w.print("/{s}/", .{line}), .search_back => try w.print("?{s}?", .{line}), .select, .split, .keep, .remove => { try w.writeAll("Edit "); try samWord(w, switch (op) { .select => 'x', .split => 'y', .keep => 'g', else => 'v', }, line); }, .pipe => try w.print("Edit |{s}", .{line}), .pipe_to => try w.print("Edit >{s}", .{line}), .insert, .append, .keep_pipe => return null, .command => try w.writeAll(line), } return if (op == .search or op == .search_back) "Look" else "Exec"; } /// 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 { const s = &p.view().tag_state; const pr = &s.prompt; var text: std.ArrayList(u8) = .empty; var spans: std.ArrayList(TagState.Span) = .empty; try text.append(arena, ' '); try styled(arena, &text, &spans, info.get(pr.op).cell, .key); try text.append(arena, ' '); const caret: u32 = @intCast(text.items.len + s.field.caret); const line = s.field.text(); try text.appendSlice(arena, line); if (line.len > 0) { var buf: [Field.max + 16]u8 = undefined; var w: std.Io.Writer = .fixed(&buf); if (plainWord(&w, pr.op, line) catch null) |verb| { try styled(arena, &text, &spans, try std.fmt.allocPrint(arena, " = {s}", .{verb}), .dim); try text.print(arena, " {s}", .{w.buffered()}); } if (pr.bad) { try text.appendSlice(arena, " "); try styled(arena, &text, &spans, regexMessage(line), .err); try text.print(arena, " · the {d} from before shown, dimmed", .{@as(usize, pane.body.nsel) + 1}); } else try count(arena, &text, pane, pr); } try text.appendSlice(arena, " "); try styled(arena, &text, &spans, info.get(pr.op).hint, .dim); return .{ .text = text.items, .spans = spans.items, .cells = 1, .caret = caret }; } fn styled(arena: std.mem.Allocator, text: *std.ArrayList(u8), spans: *std.ArrayList(TagState.Span), s: []const u8, style: TagState.Style) !void { const lo: u32 = @intCast(text.items.len); try text.appendSlice(arena, s); try spans.append(arena, .{ .lo = lo, .hi = @intCast(text.items.len), .style = style }); } /// The prompt's count after its field: what it found (`4 selections in 6 /// lines`, `keeps 3 of 9`, `0`). fn count(arena: std.mem.Allocator, text: *std.ArrayList(u8), pane: *const Pane, pr: *const Prompt) !void { switch (pr.op) { .select, .split => if (pr.found == 0) try text.appendSlice(arena, " 0") else try text.print(arena, " {d} selection{s} in {d} line{s}", .{ pr.found, plural(pr.found), pr.scope, plural(pr.scope) }), .keep, .remove => try text.print(arena, " keeps {d} of {d}", .{ pr.found, pane.nsel_snap }), else => {}, } } fn plural(n: usize) []const u8 { return if (n == 1) "" else "s"; } /// The rows the prompt's band takes: its history unrolled (Ctrl-r), the /// lines the field is in, eleven at most. pub fn takes(p: *Pardes) u16 { const s = &p.view().tag_state; if (!s.prompt.history) return 0; var n: u16 = 0; const r = ring(p, s.prompt.op); for (r.lines[0..r.n]) |l| { if (std.mem.indexOf(u8, l.slice(), s.field.text()) != null) n += 1; } return @max(1, @min(Band.Cursor.shown, n)); } /// The prompt's steps in its band: its history, newest first, the lines /// holding the field, the one Up recalled on. pub fn steps(p: *Pardes, arena: std.mem.Allocator, out: *[Band.max_steps]Band.Step) ![]Band.Step { const s = &p.view().tag_state; if (!s.prompt.history) return out[0..0]; const r = ring(p, s.prompt.op); var rows: std.ArrayList(Band.Row) = .empty; const q = s.field.text(); var back: u8 = 1; while (back <= r.n and rows.items.len < Band.Cursor.shown) : (back += 1) { const l = r.get(back).?; if (std.mem.indexOf(u8, l, q) == null) continue; try rows.append(arena, .{ .text = l, .on = back == s.prompt.recall, .index = back }); } if (rows.items.len == 0) try rows.append(arena, .{ .text = if (r.n == 0) "no history yet" else "no line holds it", .dim = true }); out[0] = .{ .rows = rows.items }; return out[0..1]; } fn typeKeys(p: *Pardes, keys: []const u8) void { for (keys) |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); } fn tagOf(p: *Pardes) ![]const u8 { return tagline.tagText(p, p.scratch.allocator(), p.panes[p.view().active].?); } fn has(hay: []const u8, needle: []const u8) bool { return std.mem.indexOf(u8, hay, needle) != null; } test "s asks in the tag's head: its key cell, the field, the plain word and the count, the selections live in the body; no match is 0, a pattern that is no regex keeps the last result dimmed and says why, Esc puts them back" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 200, .rows = 30 }); defer p.deinit(); const pane = try p.setTestFile("self.a = 1;\nself.b = 2;\nother = 3;\n"); const rest = try std.testing.allocator.dupe(u8, try tagOf(p)); defer std.testing.allocator.free(rest); typeKeys(p, "%s"); try std.testing.expectEqual(TagState.Kind.prompt, p.view().tag_state.kind); // No chip on the notice band: the prompt is the tag's. try std.testing.expectEqual(Pane.Prompt.none, pane.prompt); try std.testing.expect(std.mem.endsWith(u8, try tagOf(p), " s ⏎ select · C-r history · esc")); typeKeys(p, "self"); try std.testing.expect(has(try tagOf(p), " s self = Exec Edit x/self/ 2 selections in 3 lines ⏎ select")); try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); try std.testing.expect(selecting(p, pane).?.dim == false); // No match: 0, and the selection it began with. typeKeys(p, "x"); try std.testing.expect(has(try tagOf(p), "= Exec Edit x/selfx/ 0 ")); try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); p.update(.{ .key = .{ .cp = Key.backspace } }); try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); // No regex: the two from before, dimmed, and why. typeKeys(p, "("); try std.testing.expect(has(try tagOf(p), " bad regular expression · the 2 from before shown, dimmed ")); try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); try std.testing.expect(selecting(p, pane).?.dim); // Esc: rest, the tag and the selection as they were. p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind); try std.testing.expectEqualStrings(rest, try tagOf(p)); try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); const r = pane.body.primaryRange(pane.file.?.content, 0); try std.testing.expectEqual(pane.file.?.content.len, @max(r.anchor, r.head)); try std.testing.expect(selecting(p, pane) == null); } test "Enter keeps what s found, the pattern in / and in the history Up brings back; K keeps, counted; a pipe from the body asks in the tag and runs off the loop" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 200, .rows = 30 }); defer p.deinit(); while (p.nextEffect()) |_| {} const pane = try p.setTestFile("self.a = 1;\nself.b = 2;\nother = 3;\n"); typeKeys(p, "%sself.."); p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind); try std.testing.expectEqual(@as(u16, 1), pane.body.nsel); try std.testing.expectEqualStrings("self..", p.registers.value('/', 0).?); try std.testing.expectEqualStrings("self..", p.prompt_history.search.get(1).?); // K over the two: Up brings `self..` back, `b` keeps one of them. typeKeys(p, "K"); p.update(.{ .key = .{ .cp = Key.up } }); try std.testing.expectEqualStrings("self..", p.view().tag_state.field.text()); try std.testing.expect(has(try tagOf(p), " K self.. = Exec Edit g/self../ keeps 2 of 2")); p.update(.{ .key = .{ .cp = Key.down } }); typeKeys(p, "b"); try std.testing.expect(has(try tagOf(p), " K b = Exec Edit g/b/ keeps 1 of 2 ⏎ keep")); // Ctrl-r: the history under the tag, a row a line. p.update(.{ .key = .{ .cp = 'r', .ctrl = true } }); try std.testing.expectEqual(@as(u16, 1), Band.takes(p, p.view().active)); p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expectEqual(@as(u16, 0), pane.body.nsel); try std.testing.expectEqualStrings("b", p.prompt_history.search.get(1).?); try std.testing.expectEqualStrings("self..", p.prompt_history.search.get(2).?); // | from the body: in the tag, the plain word Edit's, Enter pipes. typeKeys(p, "|"); try std.testing.expectEqual(Pane.Prompt.none, pane.prompt); p.update(.{ .key = .{ .cp = 't', .text = "tr a-z A-Z" } }); try std.testing.expect(has(try tagOf(p), " | tr a-z A-Z = Exec Edit |tr a-z A-Z ⏎ replace")); p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expectEqualStrings("tr a-z A-Z", p.registers.value('|', 0).?); var asked: ?u32 = null; while (p.nextEffect()) |effect| if (effect == .pipe) { asked = effect.pipe.id; }; const request = p.pipe.pipeRequest(asked orelse return error.MissingPipeEffect).?; try std.testing.expectEqualStrings("tr a-z A-Z", request.command); try std.testing.expectEqualSlices(u8, "self.b", request.inputs[0]); // Esc in a pipe's prompt runs nothing. typeKeys(p, "|cat"); p.update(.{ .key = .{ .cp = Key.escape } }); while (p.nextEffect()) |effect| try std.testing.expect(effect != .pipe); }