//! `:` (walk UI, pick-ui SPEC.md §8): a line typed in the focused pane's //! tag after a `:` key cell, a text prompt of its own (Prompt.zig's //! `.command`). Its rows are the tag's own words in the tag's order (`Kill` //! after them for a terminal), marked `in the tag` and ruled off, then the //! commands a helix hand types, each the pardes word it runs: `write` //! Save, `quit` Del, `theme X` Theme X, `set` and `toggle` a setting's //! word, `reload` Get, `goto N` Look `:N`, `open F` Look F, `sort`, //! `reflow` and `pipe` a pipe of the selections. The field filters them by //! the query pane's scorer (Names.match), in their order; Tab and S-Tab put //! the next or the last into the field, a command with a space after it, //! and the doc beside the rows is the current one's. Enter runs the line as //! B2 runs a word: a command as its pardes word, anything else Exec'd. `:` //! on the empty field gives the keyboard to the tag's own text, as `:` did //! before there was a field; `:` there gives it back. //! //! A view's own, as its prompt is (TagState.prompt.command): which rows //! the hits (TagState.hits) are of, and where in the field Tab writes. const Command = @This(); const std = @import("std"); const pardes = @import("root.zig"); const config = @import("config.zig"); const tagline = @import("tagline.zig"); const panes = @import("panes.zig"); const exec = @import("exec.zig"); const builtins = @import("builtins.zig"); const Names = @import("Names.zig"); const Field = @import("Field.zig"); const Band = @import("Band.zig"); const TagState = @import("TagState.zig"); const Prompt = @import("Prompt.zig"); const Pipe = @import("Pipe.zig"); const Pardes = pardes.Pardes; const Pane = panes.Pane; const File = panes.File; const Key = pardes.Key; /// What the rows (TagState.hits) are of: the names a line starts with /// (the tag's words, then the commands), or none: a command whose /// argument is no list (`goto`'s line). pub const Rows = enum(u8) { names, none }; rows: Rows = .names, /// The names' first rows are the tag's words: how many there were when /// the field was filtered (the commands' come after them). words: u8 = 0, /// Where the query starts in the field: Tab writes the current row from /// there. from: u16 = 0, /// Tab (or a click) wrote the current row into the field: the rows are /// the line's from before it, which Tab steps on through. completed: bool = false, /// A command typed after `:`, its short name, what it takes, and what it /// does: the pardes word it is. const Typed = struct { name: []const u8, alias: []const u8 = "", arg: []const u8 = "", doc: []const u8 }; const typed = [_]Typed{ .{ .name = "write", .alias = "w", .doc = "Write the pane's text to its file: Save (a path after it, Save there)." }, .{ .name = "quit", .alias = "q", .doc = "Close the pane, asking once over unsaved text: Del." }, .{ .name = "theme", .arg = "theme", .doc = "Change the theme: Theme and its name." }, .{ .name = "set", .arg = "setting", .doc = "Set a setting: its word and the value (`set Wrap off` is `Wrap off`)." }, .{ .name = "sort", .doc = "Sort the selections' lines: each piped through sort, as `|sort` does." }, .{ .name = "reflow", .arg = "width", .doc = "Wrap the selections' lines at a width, 80 if none: each piped through `fmt -w`." }, .{ .name = "goto", .alias = "g", .arg = "line", .doc = "Go to a line: Look `:N`." }, .{ .name = "open", .alias = "o", .arg = "file", .doc = "Open a file: Look at its name." }, .{ .name = "pipe", .arg = "command", .doc = "Pipe the selections through a command, as `|` does." }, .{ .name = "reload", .doc = "Read the file again: Get." }, .{ .name = "toggle", .arg = "setting", .doc = "Flip a setting, or step it to its next value: its word bare." }, }; /// The tag's words `:` lists at most. const max_words = 32; /// A row's text at most, its name and what it says beside it. const row_max = 96; /// A doc's rows, the fewest the names' band has. const doc_rows = 4; /// `:` in pane `pane`'s body: the field empty in its tag, every row. pub fn open(p: *Pardes, pane: *Pane) void { Prompt.open(p, pane, .command); if (p.view().tag_state.kind != .prompt) return; filter(p, pane); } /// A key `:` takes before its prompt's own (Prompt.key): `:` on the empty /// field, Tab and S-Tab, Enter. False for the rest. pub fn key(p: *Pardes, id: usize, pane: *Pane, k: Key) bool { const s = &p.view().tag_state; const plain = !k.ctrl and !k.alt; if (plain and !k.shift and k.cp == ':' and s.field.len == 0) { TagState.toRest(p); tagline.enterTag(p, pane); return true; } if (plain and k.cp == Key.tab) { step(p, pane, if (k.shift) -1 else 1); return true; } if (plain and k.cp == Key.enter) { run(p, id, pane); return true; } return false; } /// The line in the field read: its first word, the command it names, and /// what follows the space after it (null without one). const Line = struct { name: []const u8, command: ?usize, arg: ?[]const u8 }; fn read(line: []const u8) Line { const space = std.mem.indexOfScalar(u8, line, ' '); const name = line[0 .. space orelse line.len]; const command = for (typed, 0..) |t, i| { if (std.mem.eql(u8, name, t.name) or (t.alias.len > 0 and std.mem.eql(u8, name, t.alias))) break i; } else null; return .{ .name = name, .command = command, .arg = if (space) |at| line[at + 1 ..] else null }; } /// The rows for the line in the field: the names its first word matches, /// until a command's space; then its argument's. The matches in the rows' /// own order, the first current. pub fn filter(p: *Pardes, pane: *Pane) void { const s = &p.view().tag_state; const c = &s.prompt.command; const line = s.field.text(); const l = read(line); c.completed = false; c.from = 0; c.words = 0; s.rows = .{}; s.nhits = 0; s.ntotal = 0; c.rows = if (l.command != null and l.arg != null) .none else .names; if (c.rows == .none) return; const q = l.name; var words = tagWords(pane); while (words.next()) |w| { if (c.words == max_words) break; consider(s, q, w, c.words); c.words += 1; } for (typed, 0..) |t, i| consider(s, q, t.name, c.words + i); } /// Row `at` of its source among the hits when query `q` matches its /// `text`. fn consider(s: *TagState, q: []const u8, text: []const u8, at: usize) void { s.ntotal += 1; if (q.len > 0 and !matches(q, text)) return; if (s.nhits == TagState.max_hits) return; s.hits[s.nhits] = @intCast(at); s.nhits += 1; } fn matches(q: []const u8, text: []const u8) bool { var low: [row_max]u8 = undefined; const t = text[0..@min(text.len, low.len)]; return Names.match(q, t, std.ascii.lowerString(&low, t), 0, null, null) != null; } /// The tag's own words, in its order: its text after the prefix but `|`, /// then for a terminal `Kill` (its job's), unless the tag has it. const Words = struct { words: std.mem.TokenIterator(u8, .any), kill: bool, fn next(w: *Words) ?[]const u8 { while (w.words.next()) |word| { if (std.mem.eql(u8, word, "|")) continue; if (std.mem.eql(u8, word, "Kill")) w.kill = false; return word; } if (!w.kill) return null; w.kill = false; return "Kill"; } }; fn tagWords(pane: *Pane) Words { return .{ .words = std.mem.tokenizeAny(u8, tagline.curTail(pane), " \t\n"), .kill = pane.isTerminal() and pane.command == null }; } /// The name row `at` stands for: a tag's word, or a command's name. fn nameOf(pane: *Pane, c: *const Command, at: usize) ?[]const u8 { if (at >= c.words) return if (at - c.words < typed.len) typed[at - c.words].name else null; var words = tagWords(pane); var i: usize = 0; while (words.next()) |w| : (i += 1) if (i == at) return w; return null; } /// Tab (`by` 1) and S-Tab (-1): the next row, or the last, written into /// the field from where the query starts, a command's name with a space /// after it; the rows stay the line's from before. fn step(p: *Pardes, pane: *Pane, by: i32) void { const s = &p.view().tag_state; const c = &s.prompt.command; if (s.nhits == 0) return; const n: i32 = s.nhits; if (c.completed) { s.rows.at = @intCast(@mod(@as(i32, s.rows.at) + by, n)); } else if (by < 0) s.rows.at = @intCast(n - 1); fill(p, pane); } /// The current row written into the field after the query's start. fn fill(p: *Pardes, pane: *Pane) void { const s = &p.view().tag_state; const c = &s.prompt.command; const at = s.hits[s.rows.at]; const name = nameOf(pane, c, at) orelse return; var line: [Field.max]u8 = undefined; var w: std.Io.Writer = .fixed(&line); w.writeAll(s.field.text()[0..@min(c.from, s.field.len)]) catch return; w.writeAll(name) catch return; if (at >= c.words) w.writeByte(' ') catch return; s.field.set(w.buffered()); c.completed = true; s.prompt.recall = 0; } /// A click on row `index` of the rows: it is current, written into the /// field as Tab writes it. pub fn point(p: *Pardes, index: u16) void { const s = &p.view().tag_state; const pane = p.panes[TagState.hostOf(p) orelse return] orelse return; if (index >= s.nhits) return; s.rows.at = index; fill(p, pane); } /// What a line runs: the pardes word a command is, Looked at or Exec'd, /// or a pipe of the selections; anything else, the line Exec'd. `said` /// when it can run nothing, and why. const Run = struct { verb: enum { exec, look, pipe } = .exec, word: []const u8 = "", said: ?[]const u8 = null, }; fn plan(line_in: []const u8, buf: []u8) Run { const line = std.mem.trim(u8, line_in, " "); const l = read(line); const i = l.command orelse return .{ .word = line }; const arg = std.mem.trim(u8, l.arg orelse "", " "); const name = typed[i].name; const word: Run = if (std.mem.eql(u8, name, "write")) .{ .word = if (arg.len == 0) "Save" else std.fmt.bufPrint(buf, "Save {s}", .{arg}) catch return .{ .said = "write: the path is too long" } } else if (std.mem.eql(u8, name, "quit")) .{ .word = "Del" } else if (std.mem.eql(u8, name, "reload")) .{ .word = "Get" } else if (std.mem.eql(u8, name, "theme")) (if (arg.len == 0) Run{ .said = "theme: which? Themes lists them" } else .{ .word = std.fmt.bufPrint(buf, "Theme {s}", .{arg}) catch return .{ .said = "theme: no such theme" } }) else if (std.mem.eql(u8, name, "set") or std.mem.eql(u8, name, "toggle")) setting(name, arg, buf) else if (std.mem.eql(u8, name, "goto")) (if (arg.len == 0 or !allDigits(arg)) Run{ .said = "goto: a line number" } else .{ .verb = .look, .word = std.fmt.bufPrint(buf, ":{s}", .{arg}) catch return .{ .said = "goto: a line number" } }) else if (std.mem.eql(u8, name, "open")) (if (arg.len == 0) Run{ .said = "open: which file?" } else .{ .verb = .look, .word = arg }) else if (std.mem.eql(u8, name, "sort")) .{ .verb = .pipe, .word = "sort" } else if (std.mem.eql(u8, name, "reflow")) (if (arg.len > 0 and !allDigits(arg)) Run{ .said = "reflow: a width in cells" } else .{ .verb = .pipe, .word = std.fmt.bufPrint(buf, "fmt -w {s}", .{if (arg.len == 0) "80" else arg}) catch return .{ .said = "reflow: a width in cells" } }) else if (std.mem.eql(u8, name, "pipe")) (if (arg.len == 0) Run{ .said = "pipe: through what?" } else .{ .verb = .pipe, .word = arg }) else unreachable; return word; } /// `set Word value` and `toggle Word`: the setting's word (any case /// typed), with the value, or bare. fn setting(name: []const u8, arg: []const u8, buf: []u8) Run { const space = std.mem.indexOfScalar(u8, arg, ' '); const which = arg[0 .. space orelse arg.len]; const value = std.mem.trim(u8, if (space) |at| arg[at + 1 ..] else "", " "); const found = for (config.Settings.settings) |st| { if (std.ascii.eqlIgnoreCase(st.word, which)) break st; } else return .{ .said = if (which.len == 0) "set: which setting?" else "set: no such setting" }; if (std.mem.eql(u8, name, "toggle") or value.len == 0) return .{ .word = found.word }; return .{ .word = std.fmt.bufPrint(buf, "{s} {s}", .{ found.word, value }) catch return .{ .said = "set: the value is too long" } }; } fn allDigits(s: []const u8) bool { for (s) |b| if (!std.ascii.isDigit(b)) return false; return true; } /// Enter: the line kept in `:`'s history and register, the tag at rest, /// and what it says run, in pane `id`, as B2 runs a word. fn run(p: *Pardes, id: usize, pane: *Pane) void { const s = &p.view().tag_state; var kept: [Field.max]u8 = undefined; const line = kept[0..s.field.len]; @memcpy(line, s.field.text()); TagState.toRest(p); if (std.mem.trim(u8, line, " ").len == 0) return; p.prompt_history.command.add(line); p.registers.put(p.gpa, ':', line, 0, 1, true) catch |err| return p.reportError(.at(id), "command", err); var buf: [Field.max + 16]u8 = undefined; const r = plan(line, &buf); if (r.said) |why| return p.setMessage(.at(id), why); switch (r.verb) { .exec => exec.runBuiltin(p, config.exec_cmd, id, "", r.word), .look => exec.runBuiltin(p, config.look_cmd, id, "", r.word), .pipe => { const f = pane.file orelse return p.setMessage(.at(id), "only a file's text is piped"); if (!panes.Output.fileTraits(f.output).saves) return p.setMessage(.at(id), "only a file's text is piped"); p.registers.put(p.gpa, '|', r.word, 0, 1, true) catch |err| return p.reportError(.at(id), "command", err); Pipe.submit(p, id, &pane.body, .replace, r.word); }, } } /// The plain word the line in the field is (Prompt.head): `Exec Save`, /// `Look :12`, `Exec Edit |sort`; null when it runs nothing. pub fn plainWord(w: *std.Io.Writer, line: []const u8) ?[]const u8 { var buf: [Field.max + 16]u8 = undefined; const r = plan(line, &buf); if (r.said != null) return null; switch (r.verb) { .exec => w.writeAll(r.word) catch return null, .look => w.writeAll(r.word) catch return null, .pipe => w.print("Edit |{s}", .{r.word}) catch return null, } return if (r.verb == .look) "Look" else "Exec"; } /// The count after the field: how many rows, or what the command takes. pub fn count(p: *Pardes, arena: std.mem.Allocator, text: *std.ArrayList(u8)) !void { const s = &p.view().tag_state; const c = &s.prompt.command; switch (c.rows) { .names => try text.print(arena, " {d} command{s}", .{ s.nhits, if (s.nhits == 1) "" else "s" }), .none => { const l = read(s.field.text()); const t = typed[l.command orelse return]; try text.print(arena, " {s}", .{if (t.arg.len == 0) "⏎ runs it" else try std.fmt.allocPrint(arena, "<{s}>", .{t.arg})}); }, } } /// The rows the band takes: the rows shown, and beside the names' the /// current one's doc. pub fn takes(p: *Pardes) u16 { const s = &p.view().tag_state; const c = &s.prompt.command; if (c.rows == .none) return 0; const shown: u16 = @max(1, @min(Band.Cursor.shown, s.nhits)); return @max(doc_rows, shown); } /// The band's steps: the rows around the current one, each its name, the /// query's bytes in the match tint, what it is said on its right (`in the /// tag`, a command's ``), the tag's last word ruled off; and the /// current row's doc. pub fn steps(p: *Pardes, arena: std.mem.Allocator, out: []Band.Step) !usize { const s = &p.view().tag_state; const c = &s.prompt.command; const pane = p.panes[TagState.hostOf(p) orelse return 0] orelse return 0; if (c.rows == .none or out.len < 2) return 0; if (s.nhits == 0) { const none = try arena.alloc(Band.Row, 1); none[0] = .{ .text = "no word or command matches", .dim = true }; out[0] = .{ .rows = none }; return 1; } const tab = p.settings.tab; const win = s.rows.window(s.nhits); const q = if (c.completed) "" else read(s.field.text()).name; var widest: usize = 0; for (s.hits[win.lo..win.hi]) |at| widest = @max(widest, File.displayWidth(tab, nameOf(pane, c, at) orelse "") + aliasWidth(c, at)); const rows = try arena.alloc(Band.Row, win.hi - win.lo); for (rows, win.lo..) |*row, i| { const at = s.hits[i]; const name = nameOf(pane, c, at) orelse ""; var text: std.ArrayList(u8) = .empty; try text.appendSlice(arena, name); if (at >= c.words and typed[at - c.words].alias.len > 0) try text.print(arena, " {s}", .{typed[at - c.words].alias}); const said: []const u8 = if (at < c.words) "in the tag" else if (typed[at - c.words].arg.len > 0) try std.fmt.allocPrint(arena, "<{s}>", .{typed[at - c.words].arg}) else ""; if (said.len > 0) { for (0..widest + 2 - File.displayWidth(tab, text.items)) |_| try text.append(arena, ' '); try text.appendSlice(arena, said); } var marks: [Names.max_query * 4]u16 = undefined; var nmarks: usize = 0; if (q.len > 0) { var low: [row_max]u8 = undefined; const t = name[0..@min(name.len, low.len)]; _ = Names.match(q, t, std.ascii.lowerString(&low, t), 0, &marks, &nmarks); } // The tag's last word ruled off from the commands under it. const last_word = at + 1 == c.words and i + 1 < s.nhits; row.* = .{ .text = text.items, .on = i == s.rows.at, .marks = try arena.dupe(u16, marks[0..nmarks]), .index = @intCast(i), .under = last_word }; } out[0] = .{ .rows = rows }; out[1] = .{ .rows = try docRows(arena, pane, c, s.hits[s.rows.at]), .doc = true }; return 2; } fn aliasWidth(c: *const Command, at: usize) usize { if (at < c.words) return 0; const alias = typed[at - c.words].alias; return if (alias.len == 0) 0 else alias.len + 1; } /// Row `at`'s doc: its name, then what it does. fn docRows(arena: std.mem.Allocator, pane: *Pane, c: *const Command, at: usize) ![]const Band.Row { const rows = try arena.alloc(Band.Row, 2); if (at >= c.words) { const t = typed[at - c.words]; const head = try std.fmt.allocPrint(arena, ":{s}{s}{s}{s}", .{ t.name, if (t.alias.len > 0) " " else "", t.alias, if (t.arg.len > 0) try std.fmt.allocPrint(arena, " <{s}>", .{t.arg}) else "" }); rows[0] = .{ .text = head, .key = @intCast(1 + t.name.len) }; rows[1] = .{ .text = t.doc }; return rows; } const name = nameOf(pane, c, at) orelse ""; rows[0] = .{ .text = try std.fmt.allocPrint(arena, "{s} in the tag", .{name}), .key = @intCast(name.len) }; rows[1] = .{ .text = if (std.meta.stringToEnum(pardes.Builtin, name)) |b| builtins.registry.doc(b).text else "A word of this pane's tag: ⏎ runs it, as B2 on it does." }; return rows; } fn typeKeys(p: *Pardes, keys: []const u8) void { for (keys) |ch| p.update(.{ .key = .{ .cp = ch, .text = &[_]u8{ch} } }); } 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; } /// Band row `y`'s text under the live view's active pane. fn bandRow(p: *Pardes, arena: std.mem.Allocator, y: u16) ![]const u8 { const id = p.view().active; const band = (try Band.of(p, arena, p.panes[id].?, id)).?; return (try band.line(arena, p.settings.tab, y)).text; } test ": opens a field in the tag after its key cell: the tag's own words first, in its order, marked and ruled off, then the commands with what they take; typing filters both; Tab completes, a command with a space; the doc is the current row's; Enter runs a command as its pardes word" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 40 }); defer p.deinit(); var frame = std.heap.ArenaAllocator.init(std.testing.allocator); defer frame.deinit(); const a = frame.allocator(); const pane = try p.setTestFile("b\na\nc\n"); const rest = try std.testing.allocator.dupe(u8, try tagOf(p)); defer std.testing.allocator.free(rest); typeKeys(p, ":"); const s = &p.view().tag_state; try std.testing.expectEqual(TagState.Kind.prompt, s.kind); try std.testing.expectEqual(Prompt.Op.command, s.prompt.op); try std.testing.expectEqual(panes.Pane.Focus.body, pane.focus); // The head: its key cell, the field, the count, the hints. try std.testing.expect(has(try tagOf(p), " : 16 commands Tab complete · ⏎ run · C-r history · esc")); // The rows: the tag's words in its order, `in the tag`, the last ruled // off; then the commands, each what it takes. try std.testing.expect(has(try bandRow(p, a, 0), "▶ Save ")); try std.testing.expect(has(try bandRow(p, a, 0), "in the tag")); try std.testing.expect(has(try bandRow(p, a, 1), " Term ")); // The doc beside them is the current row's: Save's. try std.testing.expect(has(try bandRow(p, a, 0), "Save in the tag")); const band = (try Band.of(p, a, pane, p.view().active)).?; const first = band.steps[0].rows; try std.testing.expect(first[4].under and !first[3].under); try std.testing.expect(has(first[5].text, "write w")); try std.testing.expect(has(first[7].text, "theme") and has(first[7].text, "")); // Typing filters both, by the scorer, in their order. typeKeys(p, "th"); try std.testing.expect(has(try tagOf(p), " : th = Exec th 1 command ")); try std.testing.expect(has(try bandRow(p, a, 0), "▶ theme ")); // Tab: the command, a space after it; the field's plain word is its // pardes word once it is whole. p.update(.{ .key = .{ .cp = Key.tab } }); try std.testing.expectEqualStrings("theme ", s.field.text()); typeKeys(p, "acme"); try std.testing.expect(has(try tagOf(p), " : theme acme = Exec Theme acme ")); p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expectEqual(TagState.Kind.rest, s.kind); try std.testing.expectEqualStrings("acme", p.theme().name); try std.testing.expectEqualStrings("theme acme", p.prompt_history.command.get(1).?); try std.testing.expectEqualStrings("theme acme", p.registers.value(':', 0).?); try std.testing.expectEqualStrings(rest, try tagOf(p)); // `:sort`: the selections piped through sort, as `|sort` does. while (p.nextEffect()) |_| {} typeKeys(p, "%:sort"); try std.testing.expect(has(try tagOf(p), " : sort = Exec Edit |sort 1 command")); p.update(.{ .key = .{ .cp = Key.enter } }); var asked: ?u32 = null; while (p.nextEffect()) |effect| if (effect == .pipe) { asked = effect.pipe.id; }; try std.testing.expectEqualStrings("sort", p.pipe.pipeRequest(asked orelse return error.MissingPipeEffect).?.command); // `:goto 2`: Look `:2`. typeKeys(p, ":goto 2"); try std.testing.expect(has(try tagOf(p), " : goto 2 = Look :2 ")); p.update(.{ .key = .{ .cp = Key.enter } }); try std.testing.expectEqual(@as(i32, 1), pane.body.cur_row); // S-Tab: the last row; Tab after it, round to the first. A tag word // takes no space. typeKeys(p, ":"); p.update(.{ .key = .{ .cp = Key.tab, .shift = true } }); try std.testing.expectEqualStrings("toggle ", s.field.text()); p.update(.{ .key = .{ .cp = Key.tab } }); try std.testing.expectEqualStrings("Save", s.field.text()); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expectEqual(TagState.Kind.rest, s.kind); } test ": on the empty field gives the keyboard to the tag's own text, and : there gives it back" { const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 160, .rows = 40 }); defer p.deinit(); const pane = try p.setTestFile("one\n"); typeKeys(p, "::"); try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind); try std.testing.expectEqual(panes.Pane.Focus.tag, pane.focus); typeKeys(p, ":"); try std.testing.expectEqual(panes.Pane.Focus.body, pane.focus); // A field with text in it takes `:` as a character. typeKeys(p, ":a:"); try std.testing.expectEqualStrings("a:", p.view().tag_state.field.text()); p.update(.{ .key = .{ .cp = Key.escape } }); try std.testing.expectEqual(TagState.Kind.rest, p.view().tag_state.kind); try std.testing.expectEqual(panes.Pane.Focus.body, pane.focus); }