From 83b9d45b8665a80bdb70934aa23bbde5cc03d202 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 02:07:32 -0300 Subject: plumber: a look sends what it looks at (docs/next-plumber.md, phase 2): after the pane's own readings and once a name already open in a pane is focused (never sent), lookAt sends the trimmed name, type text, src pardes (term from a raw terminal, a kind's name from its pane), wdir the pane's directory, with what resolveLookTarget found of it (Plumb.Seen: isfile and isdir take it, so no second stat and Look's own readings of a URL or `//` stay no file); a message the rules give back to `edit` as sent is Look's own (Sent.look) and runs lookAt's switch on that target, one nothing takes or a started word declines is Look's own too, whose `.url` arm is now the word's search; the edit port's open of another message runs with look_text, which now means "unplumbed", so the edit port's lookAt never sends again (the recursion trap); the three diff hooks become the default rules of the record's §5.2 (a bare .diff/.patch to `Diff $file`, a commit hash in the editor to `Diff $0`, after the two edit sets), and `Diff` takes a file or a revision, a rule's Diff declining in silence (Pardes.plumb_declined) where it cannot (no hunk, not readable, no .git above): hunks.lookedAt and lookedAtCommit go, their bodies in hunks.word, the `needs` check of the bare form in the word, PaneKind.diff gone; the old one-line `Plumb` word, Core.plumb, look.Port, plumbRuleError, plumbTarget and resolve's rules block go: bare, `Plumb` opens /plumbing as Config opens init (both through builtins.openConfigFile; `include basic` in a new one), an argument is refused in words, Save applies it (host_io.writeFile beside reapplyInitFile, Plumb.saved), and boot reads it (Plumb.boot in applyStartupConfig); a started program now runs detached as Plan 9's plumber's (the coordinator's decision for the user's question 4): Effect.start, every host's host_io.startDetached (double fork, setsid, /dev/null for 0-2, every other fd closed, argv exec'd in wdir with no shell, the child's errno back through a close-on-exec pipe, said as `plumb start: : `), so exec_dir goes; resolveLookTarget's and Plumb.Send.search's directory walk is one look.Dirs; test: look.zig's Plumb test rewritten onto the rules (a rule's word, an open pane unsent, the hover's resolve, a URL with no web rule searched for) and a hash inside and outside a git work tree; addons.zig's Plumb test onto plumb/rules (a port no kind reads, its kind gone: Look's own); Plumb.zig: the word, the save and boot; replicas.zig gains a URL (speculated whole, confirmed, no rollback) and a hash, each the authority's and a replica's own; every look golden unchanged; the reference quotes src/plumbing whole and says the order, the changelog says so MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/CHANGELOG.md | 16 +++ src/Core.zig | 20 ++-- src/Effect.zig | 16 +++ src/Plumb.zig | 264 ++++++++++++++++++++++++++++++++---------------- src/builtins.zig | 93 +++++++---------- src/exec.zig | 3 +- src/gui/gui.zig | 1 + src/host_io.zig | 126 +++++++++++++++++++++++ src/hunks.zig | 112 ++++++++++++--------- src/look.zig | 287 +++++++++++++++++++++++++++-------------------------- src/macos.zig | 1 + src/ninep/tree.zig | 9 +- src/pardes.zig | 1 + src/plumbing | 23 ++++- src/tui/tui.zig | 1 + 15 files changed, 633 insertions(+), 340 deletions(-) (limited to 'src') diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index f367774e..3e6c3d7f 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -2,6 +2,22 @@ ## Unreleased +- A look asks the plumber first, as acme's does: once the pane's own + readings are done and a name already open in a pane is focused, what + is looked at is sent (`type text`, `src pardes`, `wdir` the pane's + directory), and only what no rule set takes is Look's own. The default + rules keep every look as it was: the browser for a URL, a bare `.diff` + or `.patch` stacked in a +Diff, `git show` of a commit hash in a git + work tree are now rules of `src/plumbing`, no longer written into + Look. `Diff` takes a file or a revision (`Diff fix.patch`, `Diff + 3f2a9c1`), and a rule's Diff that cannot declines, so the look goes + on. `Plumb` opens your plumbing file (`/plumbing`, `include + basic` until you save one), read at start and applied when saved; the + one-line `Plumb suffix .svg to image` rules are gone, refused in words + (write a rule set: `data matches '.*\.svg'`, `arg isfile $data`, + `plumb to image`). A program a rule starts runs detached, as Plan 9's + plumber starts one, with no pane; a failure to start it is said. + - A search with a class whose range ends at `\xff` (`[\x80-\xff]`, in an address, `s`, a plumbing rule) no longer takes the editor down: mvzr counted the range past a byte's end. diff --git a/src/Core.zig b/src/Core.zig index 9a6e80d4..9e404f2b 100644 --- a/src/Core.zig +++ b/src/Core.zig @@ -209,9 +209,6 @@ db: Db = .{}, /// (`stdio.h`, ``) is tried in, in order. The session's, seeded /// with C's (/usr/include, /usr/local/include), kept in a dump. incl: std.ArrayList([]u8) = .empty, -/// Plumb's rules, the user's, tried in order before the built-in ones -/// (look.resolve), the first to match taking the look. Kept in a dump. -plumb: std.ArrayList([]u8) = .empty, /// The plumber's rules (Plumb.zig): plumb/rules and plumb/send's, the /// defaults (`include basic`) until something writes others. Kept in a dump. plumber: Plumb = .{}, @@ -231,9 +228,11 @@ next_serial: u32 = 0, /// The column whose tag the running command came from, while it runs: /// the column acme's commands take from their Text's col. exec_column: ?usize = null, -/// The directory a `plumb start`'s command runs in, while it runs -/// (Plumb.run): the message's wdir, which no pane need have. -exec_dir: ?[]const u8 = null, +/// While a word a plumbing rule started runs (Plumb.run): whether it +/// declined the message, saying nothing (Diff on a file with no hunk, a +/// revision outside a git work tree), so that the send is refused and a +/// look looks itself. Null while no rule's word runs. +plumb_declined: ?bool = null, /// Panes made this step that found no room in their column /// (layout.placeNew): closed at the step's end, once whatever made them /// is done with them. @@ -274,8 +273,10 @@ unattended: bool = false, haptic: HapticSlot = if (platform == .macos) .none else {}, /// The look just run found nothing (look.zig missed). look_missed: bool = false, -/// The look being run opens a .diff or .patch as text, not its +Diff: -/// Diff going back from a +Diff, Edit's B (it edits the file). +/// The look being run opens what it names, unplumbed (Plumb.zig): a +/// .diff as text, not stacked in a +Diff (Diff going back from a +Diff, +/// Edit's B, which edits the file), and the `edit` port's open of a +/// message the plumber already matched. look_text: bool = false, look_hover_wait: ?look.LookHoverWait = null, /// The place a look-hover last found nothing to open: the pointer @@ -764,8 +765,6 @@ pub fn deinit(p: *Pardes) void { p.recent.deinit(p.recentGpa()); for (p.incl.items) |dir| p.gpa.free(dir); p.incl.deinit(p.gpa); - for (p.plumb.items) |rule| p.gpa.free(rule); - p.plumb.deinit(p.gpa); p.plumber.deinit(p.gpa); for (p.twin_groups.items) |group| p.gpa.free(group.path); p.twin_groups.deinit(p.gpa); @@ -1711,7 +1710,6 @@ fn processDir(buf: *[limits.host_path_cap]u8) ?[]const u8 { /// The directory a word run from pane `id`'s text or tag runs in, or, /// from a header, the session's. pub fn execDir(p: *Pardes, id: usize) []const u8 { - if (p.exec_dir) |dir| return dir; if (p.exec_header) return p.sessionDir(); return paneDir(p.panes[id] orelse return p.sessionDir()); } diff --git a/src/Effect.zig b/src/Effect.zig index 2af28dd7..39322796 100644 --- a/src/Effect.zig +++ b/src/Effect.zig @@ -46,6 +46,10 @@ pub const Effect = union(enum) { /// and ends the shell, rather than leave it running with nobody to read. close_pty: struct { pane: u8 }, open_link: Buf(256), + /// A program a plumbing rule starts (Plumb.run): its directory, then + /// its argv, each ended by a NUL. A failure to start it is said at + /// pane `pane`. + start: struct { pane: u8, line: Buf(effect_path_cap) }, /// write this pane's file content to its path; the shell reads both off /// the core (content is unbounded, effects are fixed-size values) save_file: struct { pane: u8 }, @@ -132,6 +136,18 @@ pub fn perform(p: *Pardes, e: Effect) void { f(p.host.ctx, u.slice()) else p.fallback.setLink(u.slice()), + // Plan 9's plumber's, detached (host_io.startDetached); in-process + // (a test), kept to look at. + .start => |st| { + var why_buf: [64]u8 = undefined; + const why = if (v.start) |f| f(p.host.ctx, st.line.slice(), &why_buf) else p.fallback.start(st.line.slice()); + const w = why orelse return; + var words = std.mem.splitScalar(u8, st.line.slice(), 0); + _ = words.next(); // its directory + const prog = words.next() orelse ""; + var said: pardes.Kind.Buf(160) = .{}; + p.reportFailure(st.pane, said.print("plumb start: {s}: {s}", .{ prog[0..@min(64, prog.len)], w })); + }, .save_file => |sf| { const pane = p.panes[sf.pane] orelse return; const f = if (pane.file) |*file| file else return; diff --git a/src/Plumb.zig b/src/Plumb.zig index 57a19b14..f54ac1e2 100644 --- a/src/Plumb.zig +++ b/src/Plumb.zig @@ -10,7 +10,6 @@ const std = @import("std"); const pardes = @import("pardes.zig"); const fs = @import("fs.zig"); const look = @import("look.zig"); -const exec = @import("exec.zig"); const layout = @import("layout.zig"); const Kind = @import("Kind.zig"); const Regex = @import("regexp.zig").Regex; @@ -507,17 +506,48 @@ pub fn inForce(p: *Pardes) []const u8 { return out.written(); } +/// What the `Plumb` word says to a rule written after it. +pub const e_word = "Plumb takes no rule now: rules are plumb(6) rule sets, in /plumbing (Plumb opens it) or written to plumb/rules"; + +/// The plumbing file, the user's rules beside init (plumber(4)'s +/// $home/lib/plumbing), in `buf`; null with no configuration directory. +pub fn filePath(p: *Pardes, buf: *[4096]u8) ?[]const u8 { + const dir = p.configDir() orelse return null; + return std.fmt.bufPrint(buf, "{s}/plumbing", .{std.mem.trimEnd(u8, dir, "/")}) catch null; +} + +/// At boot, the plumbing file's rules in force, if it is there (the +/// plumber reading $home/lib/plumbing); a refusal is said, as an init +/// line that fails is, and the defaults stay. +pub fn boot(p: *Pardes) void { + var buf: [4096]u8 = undefined; + const path = filePath(p, &buf) orelse return; + const text = fs.read(p, path) catch return; + defer p.gpa.free(text); + if (apply(p, false, "plumbing", text)) |why| p.reportFailure(p.view().active, why); +} + +/// A file saved from pane `pane`: when it is the plumbing file, its rules +/// in force now, or the save says why not and the rules stay as they were +/// (plumb.ms's `cp lib/plumbing /mnt/plumb/rules`, done for you). +pub fn saved(p: *Pardes, pane: usize, path: []const u8, text: []const u8) void { + var buf: [4096]u8 = undefined; + const mine = filePath(p, &buf) orelse return; + if (!std.mem.eql(u8, mine, path)) return; + if (apply(p, false, "plumbing", text)) |why| p.reportFailure(pane, why); +} + /// No rules at all: a `>` to plumb/rules, before what it writes. pub fn clear(p: *Pardes) void { p.plumber.text.clearRetainingCapacity(); p.plumber.written = true; } -/// `more` read after the rules in force (`keep`) or in their place, and -/// what that makes kept as the rules: plumb/rules' write and its close's -/// rest. Null when taken, else why not, in the step's scratch, the rules -/// as they were. -pub fn apply(p: *Pardes, keep: bool, more: []const u8) ?[]const u8 { +/// `more` (read from `name`) read after the rules in force (`keep`) or in +/// their place, and what that makes kept as the rules: plumb/rules' write +/// and its close's rest, the plumbing file saved or read at boot. Null +/// when taken, else why not, in the step's scratch, the rules as they were. +pub fn apply(p: *Pardes, keep: bool, name: []const u8, more: []const u8) ?[]const u8 { const arena = p.scratch.allocator(); var ps: Parser = .{ .arena = arena, .p = p, .check = true }; const said = said: { @@ -525,7 +555,7 @@ pub fn apply(p: *Pardes, keep: bool, more: []const u8) ?[]const u8 { ps.feed("plumb/rules", source(p)) catch break :said ps.why; ps.finish() catch break :said ps.why; } - ps.feed("plumb/rules", more) catch break :said ps.why; + ps.feed(name, more) catch break :said ps.why; ps.finish() catch break :said ps.why; var out: std.Io.Writer.Allocating = .init(arena); ps.rules.print(&out.writer) catch break :said "out of memory"; @@ -550,6 +580,9 @@ const Send = struct { from: ?usize, arena: std.mem.Allocator, rules: Rules, + /// The data as a look sent it (`Seen`): a message to `edit` that still + /// holds it is Look's to open. + looked: ?[]const u8 = null, memo_name: ?[]const u8 = null, memo_wdir: []const u8 = "", memo: ?fs.Resolved = null, @@ -571,23 +604,10 @@ const Send = struct { fn search(s: *Send, wdir: []const u8, name: []const u8) ?fs.Resolved { if (name.len == 0) return null; - if (fs.resolve(s.p, name, wdir, &s.memo_buf)) |found| return found; - if (name[0] == '/' or fs.dotRelative(name)) return null; - if (s.from) |id| { - const v = s.p.view(); - var seen: [pardes.MAX_PANES][]const u8 = undefined; - var nseen: usize = 0; - var n: usize = 1; - cand: while (n <= v.jumps.n) : (n += 1) { - const k = v.jumps.list[v.jumps.n - n].pane; - if (k == id) continue; - const dir = Pardes.paneDir(s.p.panes[k] orelse continue); - if (std.mem.eql(u8, dir, wdir)) continue; - for (seen[0..nseen]) |d| if (std.mem.eql(u8, d, dir)) continue :cand; - seen[nseen] = dir; - nseen += 1; - if (fs.resolve(s.p, name, dir, &s.memo_buf)) |found| return found; - } + var dirs: look.Dirs = .init(s.p, s.from, wdir); + while (dirs.next()) |dir| { + if (fs.resolve(s.p, name, dir, &s.memo_buf)) |found| return found; + if (name[0] == '/' or fs.dotRelative(name)) return null; } for (s.p.incl.items) |dir| if (fs.resolve(s.p, name, dir, &s.memo_buf)) |found| return found; return null; @@ -711,14 +731,42 @@ const Port = enum { web, }; +/// What a look found of the name it sends (look.zig's resolveLookTarget: +/// in its pane's directory, the jump list's, Incl's), which `isfile` and +/// `isdir` take as found rather than ask the disk again: the same answer, +/// and Look's own readings of a name kept (a URL, `//`: no file). +pub const Seen = struct { name: []const u8, found: ?fs.Resolved }; + +/// Where a send went. +pub const Sent = union(enum) { + /// Taken: started, or given to the port that reads it. + done, + /// To `edit` as the look sent it (`Seen`): Look opens what it found, + /// as acme's own look opens a file. + look, + /// Taken by nothing, in Plan 9's words; or what a rule started + /// declined it (`declined`). + refused: []const u8, +}; + +/// What a send a rule's started word declined says (Pardes.plumb_declined): +/// fsys.c's words for a message nothing takes. +pub const e_declined = "no matching plumb rule"; + /// A message matched against the rules and sent where they say (fsys.c's /// write of `send`, then dispose), from pane `from` (a look's) or from /// plumb/send (null: the pane with the keyboard runs what it starts). -/// Null when it went somewhere, else why not, in Plan 9's words, in the -/// step's scratch. -pub fn send(p: *Pardes, from: ?usize, msg: Msg) ?[]const u8 { +/// `seen` is a look's, what it found of the name it sends. A refusal is in +/// the step's scratch. +pub fn send(p: *Pardes, from: ?usize, msg: Msg, seen: ?Seen) Sent { const arena = p.scratch.allocator(); - var s: Send = .{ .p = p, .from = from, .arena = arena, .rules = rulesOf(p, arena) catch return "plumb/rules: the rules in force do not read" }; + var s: Send = .{ .p = p, .from = from, .arena = arena, .rules = rulesOf(p, arena) catch return .{ .refused = "plumb/rules: the rules in force do not read" } }; + if (seen) |look_seen| { + s.looked = msg.data; + s.memo_name = look_seen.name; + s.memo_wdir = msg.wdir; + s.memo = look_seen.found; + } var m = msg; var e: Exec = .{ .m = &m }; const set: ?Set = for (s.rules.items.items) |item| { @@ -727,36 +775,33 @@ pub fn send(p: *Pardes, from: ?usize, msg: Msg) ?[]const u8 { else => continue, }; e = .{ .m = &m }; - if (s.matchSet(candidate, &e) catch return "out of memory") break candidate; + if (s.matchSet(candidate, &e) catch return .{ .refused = "out of memory" }) break candidate; } else null; const id = from orelse p.view().active; // dispose. - if (m.dst.len == 0) return startup(&s, id, set orelse return e_no_port, &e); - if (std.meta.stringToEnum(Port, m.dst)) |port| { - deliver(&s, id, port, &m); - return null; - } + if (m.dst.len == 0) return startup(&s, id, set orelse return .{ .refused = e_no_port }, &e); + if (std.meta.stringToEnum(Port, m.dst)) |port| return deliver(&s, id, port, &m); if (p.kinds.byName(m.dst)) |k| { openInKind(&s, id, k, &m); - return null; + return .done; } // A port nobody reads: what the rule set starts, if it is one a rule // names; one no rule names is no port, and the message goes nowhere, // as fsys.c's dispose finds no Dirtab for it. - if (!s.rules.named(m.dst)) return null; - return startup(&s, id, set orelse return e_no_start, &e); + if (!s.rules.named(m.dst)) return .done; + return startup(&s, id, set orelse return .{ .refused = e_no_start }, &e); } /// match.c's startup: the rule set's `start` or `client`, its words /// expanded, run. -fn startup(s: *Send, id: usize, set: Set, e: *const Exec) ?[]const u8 { +fn startup(s: *Send, id: usize, set: Set, e: *const Exec) Sent { const act = for (set.acts) |a| { if (a.verb == .start) break a; if (a.verb == .client) { - if (e.m.dst.len == 0) return e_client; + if (e.m.dst.len == 0) return .{ .refused = e_client }; break a; } - } else return e_no_start; + } else return .{ .refused = e_no_start }; // buildargv: one expansion a word. var argv: std.ArrayList([]const u8) = .empty; var rest = act.arg; @@ -764,63 +809,79 @@ fn startup(s: *Send, id: usize, set: Set, e: *const Exec) ?[]const u8 { rest = std.mem.trimStart(u8, rest, " \t"); if (rest.len == 0) break; var buf: [4096]u8 = undefined; - const word, const took = expand(&s.rules, e, rest, &buf) catch return "string-too-long"; - argv.append(s.arena, s.arena.dupe(u8, word) catch return "out of memory") catch return "out of memory"; + const word, const took = expand(&s.rules, e, rest, &buf) catch return .{ .refused = "string-too-long" }; + argv.append(s.arena, s.arena.dupe(u8, word) catch return .{ .refused = "out of memory" }) catch return .{ .refused = "out of memory" }; rest = rest[took..]; } - if (argv.items.len == 0) return e_empty; - run(s.p, id, e.m.wdir, argv.items); - return null; + if (argv.items.len == 0) return .{ .refused = e_empty }; + return if (run(s.p, id, e.m.wdir, argv.items)) |why| .{ .refused = why } else .done; } /// What a `plumb start` (and, until ports are read, a `plumb client`) runs: /// the one place that decides it (question 4 of docs/next-plumber.md). -/// Its words as pardes's exec runs a line from the message's pane: a -/// builtin or a kind's word in place, any other line a command pane in -/// `wdir`, each word one argument to $SHELL -c however it is spelled. -/// Plan 9's runs detached, with no window. -fn run(p: *Pardes, id: usize, wdir: []const u8, argv: []const []const u8) void { +/// A builtin or a kind's word runs in place, from the message's pane, as +/// a line of it would; one that cannot do what the message asks declines +/// (Pardes.plumb_declined), saying nothing, and the send is refused, so a +/// look looks itself. Any other is a program, started as Plan 9's plumber +/// starts one (match.c's startup): detached, no pane, its argv exec'd in +/// `wdir` with no shell (a rule that wants one says `sh -c`), by the host +/// (Effect.start), which says a failure to start in the log. Null when it +/// ran, else why not. +fn run(p: *Pardes, id: usize, wdir: []const u8, argv: []const []const u8) ?[]const u8 { const arena = p.scratch.allocator(); - const line = std.mem.join(arena, " ", argv) catch return p.reportError(id, "plumb", error.OutOfMemory); - if (p.executeBuiltinLine(id, line)) return; - var quoted: std.Io.Writer.Allocating = .init(arena); - for (argv, 0..) |a, i| { - if (i > 0) quoted.writer.writeByte(' ') catch return; - quoted.writer.writeByte('\'') catch return; - for (a) |c| { - if (c == '\'') { - quoted.writer.writeAll("'\\''") catch return; - } else quoted.writer.writeByte(c) catch return; - } - quoted.writer.writeByte('\'') catch return; - } - p.exec_dir = if (wdir.len > 0) wdir else null; - defer p.exec_dir = null; - _ = exec.runCommand(p, id, quoted.written()); + const line = std.mem.join(arena, " ", argv) catch return "out of memory"; + const outer = p.plumb_declined; + p.plumb_declined = false; + defer p.plumb_declined = outer; + // Started, not clicked: no name said for it under Verbose. + const announce = p.announce; + p.announce = false; + defer p.announce = announce; + if (p.executeBuiltinLine(id, line)) return if (p.plumb_declined.?) e_declined else null; + // Its directory, then its words, each ended by a NUL. + var start: pardes.Effect.Buf(pardes.effect_path_cap) = .{}; + for ([_][]const []const u8{ &.{wdir}, argv }) |words| for (words) |w| { + if (std.mem.indexOfScalar(u8, w, 0) != null) return "plumb start: a NUL in a word"; + if (start.len + w.len + 1 > start.data.len) return std.fmt.comptimePrint("plumb start: over {d} bytes", .{pardes.effect_path_cap}); + @memcpy(start.data[start.len..][0..w.len], w); + start.data[start.len + w.len] = 0; + start.len += @intCast(w.len + 1); + }; + p.emit(.{ .start = .{ .pane = @intCast(id), .line = start } }); + return null; } /// What pardes does with a message to a port it reads. Like a message /// queued to a reader in Plan 9, the send is done: what goes wrong after /// is said as a look's failure is. -fn deliver(s: *Send, id: usize, port: Port, m: *const Msg) void { +fn deliver(s: *Send, id: usize, port: Port, m: *const Msg) Sent { const p = s.p; switch (port) { .web => { - if (m.data.len > 256) return p.reportFailure(id, "plumb: web: a URL is at most 256 bytes"); - p.emit(.{ .open_link = .from(m.data) }); + if (m.data.len > 256) p.reportFailure(id, "plumb: web: a URL is at most 256 bytes") else p.emit(.{ .open_link = .from(m.data) }); }, .edit => { - // acme's plumblook: the data a name in wdir, at its addr. var buf: [4096]u8 = undefined; const addr = attrValue(m.attr, "addr", &buf) orelse ""; + // A look's own name, as it sent it: its own look opens it. + if (s.looked) |data| if (addr.len == 0 and std.mem.eql(u8, data, m.data)) return .look; + // acme's plumblook: the data a name in wdir, at its addr, + // opened as Look opens one and not sent again. const relative = m.data.len > 0 and m.data[0] != '/' and m.data[0] != '~' and m.wdir.len > 0; const text = std.fmt.allocPrint(s.arena, "{s}{s}{s}{s}{s}", .{ if (relative) m.wdir else "", if (relative) "/" else "", m.data, if (addr.len > 0) ":" else "", addr, - }) catch return p.reportError(id, "plumb", error.OutOfMemory); + }) catch { + p.reportError(id, "plumb", error.OutOfMemory); + return .done; + }; + const was = p.look_text; + p.look_text = true; + defer p.look_text = was; look.lookAt(p, id, text); }, } + return .done; } /// A message to a loaded kind's port: its data, a file, opened in that kind @@ -992,7 +1053,7 @@ test "plumb: rc's quoting, variables and the message's in an expansion, the firs const Tried = struct { m: Msg, set: ?usize }; fn tryRules(p: *Pardes, text: []const u8, msg: Msg) !Tried { - try testing.expect(apply(p, false, text) == null); + try testing.expect(apply(p, false, "plumb/rules", text) == null); const arena = p.scratch.allocator(); var s: Send = .{ .p = p, .from = null, .arena = arena, .rules = try rulesOf(p, arena) }; var m = msg; @@ -1100,20 +1161,20 @@ test "plumb: dispose: no rule and no dst, a start, the web port, a port no rule const p = try Pardes.init(testing.allocator, .{ .cols = 80, .rows = 24 }); defer p.deinit(); _ = try p.setTestFile("x\n"); - try testing.expect(apply(p, false, "include basic\n\ntype\tis\tmsg\nplumb\tstart\tMsg $data\n\ntype\tis\tnone\nplumb\tto\tnobody\n\ntype\tis\tclient\nplumb\tclient\tMsg x\n\n") == null); - try testing.expectEqualStrings(e_no_port, send(p, null, .{ .type = "text", .data = "no such thing" }).?); + try testing.expect(apply(p, false, "plumb/rules", "include basic\n\ntype\tis\tmsg\nplumb\tstart\tMsg $data\n\ntype\tis\tnone\nplumb\tto\tnobody\n\ntype\tis\tclient\nplumb\tclient\tMsg x\n\n") == null); + try testing.expectEqualStrings(e_no_port, send(p, null, .{ .type = "text", .data = "no such thing" }, null).refused); // A start of a builtin runs it in place. - try testing.expect(send(p, null, .{ .type = "msg", .data = "hello" }) == null); + try testing.expect(send(p, null, .{ .type = "msg", .data = "hello" }, null) == .done); const pane = p.panes[p.view().active].?; try testing.expectEqualStrings("hello", pane.msg[0..pane.msg_len]); - try testing.expectEqualStrings(e_client, send(p, null, .{ .type = "client" }).?); - try testing.expectEqualStrings(e_no_start, send(p, null, .{ .type = "none" }).?); - try testing.expectEqualStrings(e_no_start, send(p, null, .{ .dst = "nobody", .type = "x" }).?); + try testing.expectEqualStrings(e_client, send(p, null, .{ .type = "client" }, null).refused); + try testing.expectEqualStrings(e_no_start, send(p, null, .{ .type = "none" }, null).refused); + try testing.expectEqualStrings(e_no_start, send(p, null, .{ .dst = "nobody", .type = "x" }, null).refused); // A port no rule names goes nowhere, said nothing (fsys.c's dispose). - try testing.expect(send(p, null, .{ .dst = "elsewhere", .data = "x" }) == null); + try testing.expect(send(p, null, .{ .dst = "elsewhere", .data = "x" }, null) == .done); // A URL to the web port: the host's opener. while (p.nextEffect()) |_| {} - try testing.expect(send(p, null, .{ .type = "text", .data = "https://ziglang.org" }) == null); + try testing.expect(send(p, null, .{ .type = "text", .data = "https://ziglang.org" }, null) == .done); var opened = false; while (p.nextEffect()) |e| switch (e) { .open_link => |u| { @@ -1131,10 +1192,10 @@ test "plumb: rules written replace or add, a refusal keeps them as they were, an // Every session starts with the defaults. try testing.expect(std.mem.indexOf(u8, inForce(p), "plumb\tto\tweb") != null); try testing.expect(!p.plumber.written); - try testing.expect(apply(p, false, "type is a\nplumb to edit\n") == null); - try testing.expect(apply(p, true, "type is b\nplumb to edit\n") == null); + try testing.expect(apply(p, false, "plumb/rules", "type is a\nplumb to edit\n") == null); + try testing.expect(apply(p, true, "plumb/rules", "type is b\nplumb to edit\n") == null); try testing.expectEqualStrings("type\tis\ta\nplumb\tto\tedit\n\ntype\tis\tb\nplumb\tto\tedit\n\n", p.plumber.text.items); - try testing.expectEqualStrings("plumb/rules:1: unknown verb isnt", apply(p, true, "type isnt c\n").?); + try testing.expectEqualStrings("plumb/rules:1: unknown verb isnt", apply(p, true, "plumb/rules", "type isnt c\n").?); try testing.expectEqualStrings("type\tis\ta\nplumb\tto\tedit\n\ntype\tis\tb\nplumb\tto\tedit\n\n", p.plumber.text.items); try pardes.dump.dumpState(p); const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); @@ -1239,3 +1300,40 @@ test "plumb: plan9port's basic parses, its ¡- // The rune range as written is refused, in regexp.zig's words. try testing.expectEqualStrings("t:1: bad regular expression: a range of runes wider than 256 in [...] is not supported", try reread(arena.allocator(), "data matches '[a-zA-Z¡-￿0-9_\\-./]+'\nplumb to edit\n")); } + +test "plumb: the Plumb word opens the plumbing file, include basic until one is saved; saved, or read at boot, its rules are in force, a bad one said with its line" { + if (!fs.platform_has_fs) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var dir_buf: [4096]u8 = undefined; + const root = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; + const p = try Pardes.init(testing.allocator, .{ .cols = 100, .rows = 30, .config_dir = root }); + defer p.deinit(); + _ = try p.setTestFile("x\n"); + var path_buf: [4096]u8 = undefined; + const path = filePath(p, &path_buf).?; + try testing.expect(std.mem.endsWith(u8, path, "/plumbing")); + // Not there yet: a pane of its name holding `include basic`. + try testing.expect(p.executeBuiltinLine(0, "Plumb")); + const made = p.panes[p.view().active].?; + try testing.expectEqualStrings(path, made.file.?.path); + try testing.expectEqualStrings("include basic\n", made.file.?.content); + // A rule after the word is refused, in words. + try testing.expect(p.executeBuiltinLine(0, "Plumb suffix .svg to image")); + const first = p.panes[0].?; + try testing.expectEqualStrings(e_word, first.msg[0..first.msg_len]); + // Saved: its rules, or why not, the rules as they were. + saved(p, 0, path, "type is text\ndata matches 'x.*'\nplumb to web\n"); + try testing.expectEqualStrings("type\tis\ttext\ndata\tmatches\t'x.*'\nplumb\tto\tweb\n\n", inForce(p)); + saved(p, 0, path, "type is text\ndata isnt x\nplumb to web\n"); + try testing.expectEqualStrings("plumbing:2: unknown verb isnt", first.msg[0..first.msg_len]); + try testing.expectEqualStrings("type\tis\ttext\ndata\tmatches\t'x.*'\nplumb\tto\tweb\n\n", inForce(p)); + // Another file saved is no plumbing. + saved(p, 0, "/elsewhere/plumbing", "type is text\nplumb to edit\n"); + try testing.expect(std.mem.indexOf(u8, inForce(p), "'x.*'") != null); + // At boot: the file's rules. + try tmp.dir.writeFile(testing.io, .{ .sub_path = "plumbing", .data = "type is text\ndata matches 'y.*'\nplumb to web\n" }); + const q = try Pardes.init(testing.allocator, .{ .cols = 100, .rows = 30, .config_dir = root }); + defer q.deinit(); + try testing.expectEqualStrings("type\tis\ttext\ndata\tmatches\t'y.*'\nplumb\tto\tweb\n\n", inForce(q)); +} diff --git a/src/builtins.zig b/src/builtins.zig index bb91d0b0..2b9d9f53 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -5,6 +5,7 @@ const tagline = @import("tagline.zig"); const dump = @import("dump.zig"); const exec = @import("exec.zig"); const look = @import("look.zig"); +const PlumbRules = @import("Plumb.zig"); const edit = @import("edit.zig"); const colors = @import("colors.zig"); const Pardes = pardes.Pardes; @@ -65,8 +66,6 @@ pub const PaneKind = enum { picture, /// A terminal, or a +Pager: a program's colours. program_colors, - /// A text pane showing a diff: a .diff, a .patch, a +Pager holding one. - diff, pub fn has(kind: PaneKind, pane: *const panes.Pane) bool { return switch (kind) { @@ -74,7 +73,6 @@ pub const PaneKind = enum { .image => pane.addon != null, .picture => pane.addon != null or pane.isTerminal(), .program_colors => pane.isTerminal() or (pane.file != null and pane.file.?.pager), - .diff => @import("hunks.zig").shows(pane), }; } @@ -84,7 +82,6 @@ pub const PaneKind = enum { .image => "an image", .picture => "an image or a terminal", .program_colors => "a terminal or a +Pager", - .diff => "a diff or a +Diff", }; } }; @@ -937,43 +934,18 @@ pub const Incl = struct { } }; -/// The plumber's rules, for the session, one a line as plumb(6) orders a -/// rule: `Plumb suffix .svg to image` makes a look at an existing `.svg` -/// file an image pane. The user's rules are tried in the order given, -/// before the built-in ones, and the first that matches takes the look. -/// Bare, it lists them; `Plumb -` empties the list. +/// Open the plumbing file, the plumber's rules (plumb(6)'s rule sets) in +/// the configuration directory beside `init`: saved, they are the rules in +/// force. Not there yet, it holds `include basic`, the default rules. pub const Plumb = struct { pub const scope: Scope = .session; pub const takes_arg = true; pub fn run(c: Ctx) void { - const p = c.p; - const typed = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); - if (std.mem.eql(u8, typed, "-")) { - for (p.plumb.items) |rule| p.gpa.free(rule); - p.plumb.clearRetainingCapacity(); - return p.setMessage(c.id, "Plumb: none"); - } - if (typed.len > 0) { - var said: [320]u8 = undefined; - if (look.plumbRuleError(&p.kinds, typed)) |why| - return p.reportFailure(c.id, std.fmt.bufPrint(&said, "Plumb: {s}", .{why}) catch "Plumb: invalid rule"); - // One blank between words, as the list shows it. - var rule: std.ArrayList(u8) = .empty; - defer rule.deinit(p.gpa); - var words = std.mem.tokenizeAny(u8, typed, " \t"); - while (words.next()) |w| { - if (rule.items.len > 0) rule.append(p.gpa, ' ') catch |err| return p.reportError(c.id, "Plumb", err); - rule.appendSlice(p.gpa, w) catch |err| return p.reportError(c.id, "Plumb", err); - } - p.plumb.ensureUnusedCapacity(p.gpa, 1) catch |err| return p.reportError(c.id, "Plumb", err); - p.plumb.appendAssumeCapacity(rule.toOwnedSlice(p.gpa) catch |err| return p.reportError(c.id, "Plumb", err)); - return; - } - var list: std.Io.Writer.Allocating = .init(p.scratch.allocator()); - list.writer.writeAll("Plumb:") catch |err| return p.reportError(c.id, "Plumb", err); - for (p.plumb.items, 0..) |rule, i| list.writer.print("{s} {s}", .{ if (i == 0) "" else ";", rule }) catch |err| return p.reportError(c.id, "Plumb", err); - if (p.plumb.items.len == 0) list.writer.writeAll(" none") catch |err| return p.reportError(c.id, "Plumb", err); - p.setMessage(c.id, list.written()); + if (std.mem.trim(u8, c.arg orelse "", " \t\r\n").len > 0) return c.p.reportFailure(c.id, PlumbRules.e_word); + var buf: [4096]u8 = undefined; + const path = PlumbRules.filePath(c.p, &buf) orelse + return c.p.reportFailure(c.id, "Plumb: no plumbing file here: no configuration directory"); + openConfigFile(c, "Plumb", path, "include basic\n"); } }; @@ -1087,11 +1059,11 @@ pub const Filter = struct { } }; -/// Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text. +/// Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text. `Diff ` stacks that diff's, `Diff ` git show's. /// The diff viewer's one registration: its word and traits here, all else /// its own (hunks.zig). pub const Diff = struct { - pub const needs: PaneKind = .diff; + pub const takes_arg = true; pub const output: OutputTraits = .{ .name = config.diff_buffer, .steps = true, .locations = true }; pub const run = @import("hunks.zig").word; }; @@ -1334,25 +1306,36 @@ pub const Config = struct { pub fn run(c: Ctx) void { const path = c.p.startupPath() orelse return c.p.reportFailure(c.id, "Config: no startup file here: no configuration directory"); - var real_buf: [4096]u8 = undefined; - const real = if (pardes.filesystem.resolveOs(path, &real_buf)) |r| r.path else null; - for (c.p.panes, 0..) |slot, id| { - const pane = slot orelse continue; - const f = pane.file orelse continue; - if (f.output != null) continue; - if (!std.mem.eql(u8, f.path, path) and !(if (real) |r| std.mem.eql(u8, f.path, r) else false)) continue; - return look.focusPaneLine(c.p, id, .{}, .keep); - } - if (real != null) return look.lookAt(c.p, c.id, path); - // Not there yet: a pane named for it, which Save makes. - const free = c.p.freeSlot() orelse return c.p.reportError(c.id, "Config", error.NoPaneSlots); - panes.newScratchFor(c.p, c.id, .scratch); - if (c.p.panes[free] == null) return; - @import("ninep/pane.zig").nameBuffer(c.p, free, path, false) catch |err| return c.p.reportError(c.id, "Config", err); - c.p.view().active = free; + openConfigFile(c, "Config", path, ""); } }; +/// A file of the configuration directory's (Config's init, Plumb's +/// plumbing) in a pane: its pane when it is open, else the file, else a +/// pane of that name holding `initial`, for Save to make it and its +/// directory. +fn openConfigFile(c: Ctx, name: []const u8, path: []const u8, initial: []const u8) void { + var real_buf: [4096]u8 = undefined; + const real = if (pardes.filesystem.resolveOs(path, &real_buf)) |r| r.path else null; + for (c.p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + const f = pane.file orelse continue; + if (f.output != null) continue; + if (!std.mem.eql(u8, f.path, path) and !(if (real) |r| std.mem.eql(u8, f.path, r) else false)) continue; + return look.focusPaneLine(c.p, id, .{}, .keep); + } + if (real != null) return look.lookAt(c.p, c.id, path); + // Not there yet: a pane named for it, which Save makes. + const free = c.p.freeSlot() orelse return c.p.reportError(c.id, name, error.NoPaneSlots); + panes.newScratchFor(c.p, c.id, .scratch); + const made = c.p.panes[free] orelse return; + @import("ninep/pane.zig").nameBuffer(c.p, free, path, false) catch |err| return c.p.reportError(c.id, name, err); + if (initial.len > 0) if (made.file) |*f| { + _ = panes.File.replace(c.p, f, 0, f.content.len, initial); + }; + c.p.view().active = free; +} + /// Open the settings in effect, each a word to click, and the startup /// file's path. pub const DumpConfig = struct { diff --git a/src/exec.zig b/src/exec.zig index ece4f98d..b0430674 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -735,7 +735,7 @@ pub fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { // Nor one leased: an open that was answered its serial and is still // open reads that pane's output, which another client's command must // not replace; a new pane runs it instead. - const reuse: ?usize = if (!p.exec_header and p.exec_column == null and p.exec_dir == null and src != null and src.?.command != null and src.?.command_done and !src.?.command_pty and !leased(p, src.?.serial)) from else for (p.panes, 0..) |slot, i| { + const reuse: ?usize = if (!p.exec_header and p.exec_column == null and src != null and src.?.command != null and src.?.command_done and !src.?.command_pty and !leased(p, src.?.serial)) from else for (p.panes, 0..) |slot, i| { const other = slot orelse continue; if (p.exec_column) |c| if (if (layout.findPane(p, i)) |f| f.col != c else true) continue; if (other.command != null and other.command_done and !other.command_pty and std.mem.eql(u8, other.cwdSlice(), dir) and !leased(p, other.serial)) break i; @@ -892,6 +892,7 @@ pub fn executeBuiltinLine(p: *Pardes, id: usize, txt: []const u8) bool { } pub fn applyStartupConfig(p: *Pardes) void { + @import("Plumb.zig").boot(p); applyInitText(p, p.opts.startup_config orelse return, false); } diff --git a/src/gui/gui.zig b/src/gui/gui.zig index 45157dd3..655272b9 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -2966,6 +2966,7 @@ const Shell = struct { .set_clipboard = setClipboard, .read_clipboard = readClipboard, .open_link = openLink, + .start = host_io.startDetached, .lsp = lsp, .pipe = pipe, .search = search, diff --git a/src/host_io.zig b/src/host_io.zig index 3141ff64..9e503e26 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -59,6 +59,9 @@ pub const Host = struct { set_clipboard: ?*const fn (ctx: ?*anyopaque, text: []const u8) void = null, read_clipboard: ?*const fn (ctx: ?*anyopaque) void = null, open_link: ?*const fn (ctx: ?*anyopaque, url: []const u8) void = null, + /// A plumbing rule's program (Effect.start): every host's is + /// startDetached. Null once it runs, else why not. + start: ?*const fn (ctx: ?*anyopaque, line: []const u8, why: []u8) ?[]const u8 = null, lsp: ?*const fn (ctx: ?*anyopaque, req: Lsp.Request) void = null, pipe: ?*const fn (ctx: ?*anyopaque, id: u32) void = null, /// Start the streaming search of this generation on a worker @@ -268,6 +271,9 @@ pub const Fallback = struct { files: std.StringHashMapUnmanaged([]u8) = .empty, clipboard: std.ArrayListUnmanaged(u8) = .empty, link: std.ArrayListUnmanaged(u8) = .empty, + /// The programs plumbing rules started, as Effect.start packs them, + /// one a line. + started: std.ArrayListUnmanaged(u8) = .empty, spawned: [pardes.MAX_PANES]bool = @splat(false), watched: [pardes.MAX_PANES]bool = @splat(false), @@ -280,6 +286,7 @@ pub const Fallback = struct { f.files.deinit(f.gpa); f.clipboard.deinit(f.gpa); f.link.deinit(f.gpa); + f.started.deinit(f.gpa); } pub fn writeFile(f: *Fallback, path: []const u8, bytes: []const u8) bool { @@ -315,6 +322,12 @@ pub const Fallback = struct { f.link.clearRetainingCapacity(); f.link.appendSlice(f.gpa, url) catch {}; } + + pub fn start(f: *Fallback, line: []const u8) ?[]const u8 { + f.started.appendSlice(f.gpa, line) catch return "out of memory"; + f.started.append(f.gpa, '\n') catch return "out of memory"; + return null; + } }; /// What a pixel host's loop takes from its workers, in order: each pane's @@ -2456,6 +2469,108 @@ const darwin = struct { } }; +/// A program a plumbing rule starts (Effect.start), as Plan 9's plumber +/// starts one (match.c's startup): out of the editor's way, a session of +/// its own reaped by init, stdin, stdout and stderr /dev/null and no other +/// fd of the editor's, its argv exec'd (no shell: a rule that wants one +/// says `sh -c`) in its directory. `line` is its directory, then its argv, +/// each ended by a NUL. Null once it runs, else why not, as errno says it, +/// in `why` (as the tape replays a host's words): a pipe closed at the +/// exec carries the child's errno back. +pub fn startDetached(_: ?*anyopaque, line: []const u8, why: []u8) ?[]const u8 { + const words = startWords(line) orelse return null; + const n = @min(words.len, why.len); + @memcpy(why[0..n], words[0..n]); + return why[0..n]; +} + +fn startWords(line: []const u8) ?[]const u8 { + var buf: [pardes.effect_path_cap]u8 = undefined; + if (line.len == 0 or line.len > buf.len or line[line.len - 1] != 0) return "malformed"; + @memcpy(buf[0..line.len], line); + var argv: [64:null]?[*:0]const u8 = @splat(null); + var n: usize = 0; + var at: usize = 0; + var dir: [*:0]const u8 = undefined; + while (at < line.len) { + const end = std.mem.indexOfScalarPos(u8, line, at, 0).?; + const word: [*:0]const u8 = @ptrCast(&buf[at]); + if (at == 0) dir = word else if (n < argv.len) { + argv[n] = word; + n += 1; + } else return "more than 64 words"; + at = end + 1; + } + if (n == 0) return "no program"; + var fds: [2]c_int = undefined; + if (libc.pipe(&fds) != 0) return "no pipe"; + for (fds) |fd| _ = libc.fcntl(fd, libc.F.SETFD, @as(c_int, libc.FD_CLOEXEC)); + const first = libc.fork(); + if (first < 0) { + _ = libc.close(fds[0]); + _ = libc.close(fds[1]); + return "no fork"; + } + if (first == 0) { + // Only async-signal-safe calls between fork and exec. + _ = libc.setsid(); + if (libc.fork() != 0) libc._exit(0); + resetChildSignals(); + // What failed, then errno: 'd' the directory, 'x' the exec. + const Fail = struct { + fn say(fd: c_int, what: u8) noreturn { + var said: [5]u8 = undefined; + said[0] = what; + std.mem.writeInt(u32, said[1..5], @intFromEnum(libc.errno(-1)), .little); + _ = libc.write(fd, &said, said.len); + libc._exit(127); + } + }; + const err_fd = libc.fcntl(fds[1], libc.F.DUPFD_CLOEXEC, @as(c_int, 3)); + if (err_fd < 0) libc._exit(127); + if (dir[0] != 0 and libc.chdir(dir) != 0) Fail.say(err_fd, 'd'); + const null_fd = libc.open("/dev/null", .{ .ACCMODE = .RDWR }, @as(libc.mode_t, 0)); + if (null_fd >= 0) for (0..3) |i| { + _ = libc.dup2(null_fd, @intCast(i)); + }; + // Every fd of the editor's but the errno pipe's gone: a pty's + // master held open would keep its terminal alive. + if (libc.dup2(err_fd, 3) < 0) libc._exit(127); + _ = libc.fcntl(3, libc.F.SETFD, @as(c_int, libc.FD_CLOEXEC)); + const shut = if (comptime builtin.os.tag == .linux) + std.os.linux.close_range(4, std.math.maxInt(i32), .{ .UNSHARE = false, .CLOEXEC = false }) == 0 + else + false; + if (!shut) { + var fd: c_int = 4; + while (fd < 1024) : (fd += 1) _ = libc.close(fd); + } + _ = execvp(argv[0].?, &argv); + Fail.say(3, 'x'); + } + _ = libc.close(fds[1]); + while (libc.waitpid(first, null, 0) < 0 and libc.errno(-1) == .INTR) {} + var said: [5]u8 = undefined; + var got: usize = 0; + while (got < said.len) { + const r = libc.read(fds[0], said[got..].ptr, said.len - got); + if (r < 0 and libc.errno(r) == .INTR) continue; + if (r <= 0) break; + got += @intCast(r); + } + _ = libc.close(fds[0]); + if (got < said.len) return null; + const code = std.mem.readInt(u32, said[1..5], .little); + const E = libc.E; + if (code == @intFromEnum(E.NOENT)) return if (said[0] == 'd') "its directory: no such directory" else "not found"; + if (code == @intFromEnum(E.ACCES)) return "permission denied"; + if (code == @intFromEnum(E.NOTDIR)) return "not a directory"; + if (code == @intFromEnum(E.NOEXEC)) return "not an executable"; + return if (said[0] == 'd') "its directory: cannot go there" else "cannot start it"; +} + +extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; + /// A terminal pane's shell is done with (its pane gone, its pty closed or at /// end of file): say hangup, for a shell that ignores the tty's, and see it /// reaped, killed if it is still there 100 ms on. A thread does the waiting @@ -3004,6 +3119,8 @@ pub fn writeFile(core: *pardes.Pardes, watches: *file_watch.Table, pane: u8, pat core.setMessage(pane, pardes.Messages.Message.stamp(&mbuf, "saved", path)); // The init file, saved here (Config): its settings take effect now. pardes.exec.reapplyInitFile(core, path, bytes); + // The plumbing file (Plumb): its rules in force now. + pardes.Plumb.saved(core, pane, path, bytes); } /// A Dump's write: into the state file under a label of its own @@ -3863,3 +3980,12 @@ test "LSP query answers, and a newer one cancels it" { core.update(.{ .lsp_resp = .{ .id = last, .rows = batch.items[0].lsp.rows } }); try std.testing.expect(core.lsp_ask.wait == null); } + +test "a plumbing rule's program starts detached, or says why not: a program not found, a directory not there" { + if (comptime builtin.os.tag != .linux) return; + var why: [64]u8 = undefined; + try std.testing.expect(startDetached(null, "/\x00true\x00", &why) == null); + try std.testing.expectEqualStrings("not found", startDetached(null, "/\x00no-such-program-x\x00", &why).?); + try std.testing.expectEqualStrings("its directory: no such directory", startDetached(null, "/no/such/dir\x00true\x00", &why).?); + try std.testing.expectEqualStrings("malformed", startDetached(null, "/\x00true", &why).?); +} diff --git a/src/hunks.zig b/src/hunks.zig index afd2ac9d..f316fe48 100644 --- a/src/hunks.zig +++ b/src/hunks.zig @@ -601,39 +601,77 @@ fn trimmedWidth(section: []const u8) usize { // ---- the +Diff in the editor ---- // -// Its word (Diff), the open and the text it goes back to; and the three -// hooks the generic code calls, one call each (look.zig's bare look and -// commit look, ninep/ctl.zig's filled +Pager), which a plumber's rules -// would replace. - -/// The `Diff` word (builtins.zig registers it): on a +Diff, the diff it -/// stacks as text; on a diff, its hunks stacked in a +Diff. +// Its word (Diff), the open and the text it goes back to; and the hook +// ninep/ctl.zig's filled +Pager calls, which the pager's plumbing message +// replaces. A bare look at a .diff and at a commit hash are plumbing +// rules that start Diff (src/plumbing). + +/// The `Diff` word (builtins.zig registers it). Bare, on a +Diff, the diff +/// it stacks as text; on a diff, its hunks stacked in a +Diff. With a file +/// (a .diff, a .patch: relative to the pane's directory), its hunks +/// stacked so; with a revision (7 to 40 lowercase hex digits, a letter and +/// a digit among them), `git show` of it, paged into a +Pager that stacks +/// its hunks (ctl.fillPager), run in the pane's git work tree. A plumbing +/// rule's Diff that cannot (no hunk, no work tree) declines, saying +/// nothing (Pardes.plumb_declined), and the look looks itself. pub fn word(c: pardes.builtins.Ctx) void { - const f = &c.pane.file.?; - if (diffSource(c.p, f)) |source| return showDiffText(c.p, c.id, source); - _ = openDiff(c.p, c.id, f.path, f.content) catch |err| switch (err) { - error.NoHunks => c.p.reportFailure(c.id, "Diff: no hunk in it"), - else => c.p.reportError(c.id, "hunks", err), + const p = c.p; + const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + if (arg.len == 0) { + if (!shows(c.pane)) return p.reportFailure(c.id, "Diff: only a diff or a +Diff pane takes it"); + const f = &c.pane.file.?; + if (diffSource(p, f)) |source| return showDiffText(p, c.id, source); + _ = openDiff(p, c.id, f.path, f.content) catch |err| switch (err) { + error.NoHunks => p.reportFailure(c.id, "Diff: no hunk in it"), + else => p.reportError(c.id, "hunks", err), + }; + return; + } + if (isCommitHash(arg)) { + var dir = pardes.filesystem.localPath(Pardes.paneDir(c.pane)) orelse return declined(p, c.id, "Diff: not in a git work tree"); + while (true) { + var buf: [4096]u8 = undefined; + const dot_git = std.fmt.bufPrint(&buf, "{s}/.git", .{dir}) catch return declined(p, c.id, "Diff: not in a git work tree"); + if (pardes.exec.kindOf(dot_git) != null) break; + dir = std.Io.Dir.path.dirname(dir) orelse return declined(p, c.id, "Diff: not in a git work tree"); + } + // ponytail: a hex word that names no commit leaves git's error in a command pane, not a search; check the object first if that bites. + var line: [64]u8 = undefined; + const dst = pardes.exec.execute(p, c.id, std.fmt.bufPrint(&line, "git show {s}", .{arg}) catch unreachable) orelse return; + if (p.panes[dst]) |cp| cp.command_pages = true; + return; + } + var buf: [4096]u8 = undefined; + const path = if (arg[0] == '/') arg else std.fmt.bufPrint(&buf, "{s}/{s}", .{ std.mem.trimEnd(u8, Pardes.paneDir(c.pane), "/"), arg }) catch arg; + const bytes = pardes.filesystem.read(p, path) catch |err| { + if (p.plumb_declined != null) return declined(p, c.id, ""); + return p.reportError(c.id, path, err); + }; + defer p.gpa.free(bytes); + p.view().active = openDiff(p, c.id, path, bytes) catch |err| switch (err) { + error.NoHunks => return declined(p, c.id, "Diff: no hunk in it"), + else => { + if (p.plumb_declined != null) return declined(p, c.id, ""); + return p.reportError(c.id, "hunks", err); + }, }; } -/// A pane the word works on: a diff (a .diff, a .patch, a +Pager holding -/// one) or a +Diff. -pub fn shows(pane: *const Pane) bool { - const f = pane.file orelse return false; - return pane.colorAlgo() == .diff or (f.output != null and std.meta.eql(f.output.?.from, Output.Origin{ .cmd = .Diff })); +/// A Diff that cannot do what it was asked: a plumbing rule's declines, +/// saying nothing; one typed says `why`. +fn declined(p: *Pardes, id: usize, why: []const u8) void { + if (p.plumb_declined) |*d| { + d.* = true; + return; + } + p.reportFailure(id, why); } -/// The hook of a bare look at a .diff or a .patch (look.zig's open): its -/// hunks stacked in a +Diff, which takes the keyboard as the file would; -/// false, for look to open it as text, when it is no such file, a place in -/// one, one with no hunk, or the text is what is asked (showDiffText). -pub fn lookedAt(p: *Pardes, id: usize, path: []const u8, at: pardes.look.Spot) bool { - if (p.look_text or at.line != 0 or !(std.mem.endsWith(u8, path, ".diff") or std.mem.endsWith(u8, path, ".patch"))) return false; - const bytes = pardes.filesystem.read(p, path) catch return false; - defer p.gpa.free(bytes); - p.view().active = openDiff(p, id, path, bytes) catch return false; - return true; +/// A pane the bare word works on: a diff (a .diff, a .patch, a +Pager +/// holding one) or a +Diff. +fn shows(pane: *const Pane) bool { + const f = pane.file orelse return false; + return pane.colorAlgo() == .diff or (f.output != null and std.meta.eql(f.output.?.from, Output.Origin{ .cmd = .Diff })); } /// The hook of a +Pager filled with a diff (ninep/ctl.zig's fillPager: @@ -650,26 +688,6 @@ pub fn paged(p: *Pardes, id: usize) void { if (p.panes[keyboard] != null) p.view().active = keyboard; } -/// The hook of a commit hash (7 to 40 hex digits, a letter and a digit -/// among them; look.zig's look at a word) looked at inside a git repository: `git show` it, paged into a +Pager, -/// which stacks its hunks in a +Diff (ctl.fillPager); the command pane -/// goes when it succeeds (Pane.commandDone). -// ponytail: a hex word that names no commit leaves git's error in a command pane, not a search; check the object first if that bites. -pub fn lookedAtCommit(p: *Pardes, id: usize, pane: *Pane, hash: []const u8) bool { - if (!isCommitHash(hash)) return false; - var dir = pardes.filesystem.localPath(Pardes.paneDir(pane)) orelse return false; - while (true) { - var buf: [4096]u8 = undefined; - const dot_git = std.fmt.bufPrint(&buf, "{s}/.git", .{dir}) catch return false; - if (pardes.exec.kindOf(dot_git) != null) break; - dir = std.Io.Dir.path.dirname(dir) orelse return false; - } - var line: [64]u8 = undefined; - const dst = pardes.exec.execute(p, id, std.fmt.bufPrint(&line, "git show {s}", .{hash}) catch return false) orelse return true; - if (p.panes[dst]) |c| c.command_pages = true; - return true; -} - fn isCommitHash(hex: []const u8) bool { if (hex.len < 7 or hex.len > 40) return false; var digit = false; diff --git a/src/look.zig b/src/look.zig index 115e3683..b32c46ac 100644 --- a/src/look.zig +++ b/src/look.zig @@ -4,7 +4,7 @@ const builtin = @import("builtin"); const libc = std.c; const pardes = @import("pardes.zig"); const exec = @import("exec.zig"); -const hunks = @import("hunks.zig"); +const Plumb = @import("Plumb.zig"); const config = @import("config.zig"); const diff = @import("diff.zig"); const platform_has_fs = filesystem.platform_has_fs; @@ -153,56 +153,6 @@ pub fn lineSpan(p: ?*pardes.Pardes, line: []const u8, cwd: []const u8, realbuf: return null; } -/// Where a `Plumb` rule sends what it matched: the targets the built-in -/// rules below make (url: the browser, through `xdg-open`), or a loaded -/// kind by its name (`image`, `pdf`). -pub const Port = enum { url, dir, file }; - -/// A rule as `Plumb` takes it, plumb(6)'s order on one line: ` -/// [word ...] to `, the test `prefix` (the text starts so), `suffix` -/// (an existing file's name ends so, any case), `isdir` or `isfile`; the -/// port `url`, `dir`, `file` or a kind `kinds` has. -/// Null when it is one; otherwise what is wrong with it, said. -pub fn plumbRuleError(kinds: *const Kind.Registry, rule: []const u8) ?[]const u8 { - var words = std.mem.tokenizeAny(u8, rule, " \t"); - const how = words.next() orelse return "a rule: [word ...] to "; - const takes = if (std.mem.eql(u8, how, "prefix") or std.mem.eql(u8, how, "suffix")) - true - else if (std.mem.eql(u8, how, "isdir") or std.mem.eql(u8, how, "isfile")) - false - else - return "invalid test: prefix, suffix, isdir or isfile"; - var n: usize = 0; - while (words.next()) |w| : (n += 1) { - if (!std.mem.eql(u8, w, "to")) continue; - if (takes and n == 0) return "invalid rule: prefix and suffix take a word"; - if (!takes and n > 0) return "invalid rule: isdir and isfile take no word"; - const port = words.next() orelse return "invalid rule: to names no port"; - if (std.meta.stringToEnum(Port, port) == null and kinds.byName(port) == null) - return "invalid port: url, dir, file or a loaded kind"; - if (words.next() != null) return "invalid rule: a word after the port"; - return null; - } - return "invalid rule: no `to `"; -} - -/// What a rule's port makes of what it matched; null when it cannot (no -/// such file, a directory to `file`, a kind gone since): the next rule tries. -fn plumbTarget(p: *pardes.Pardes, port: []const u8, text: []const u8, found: ?filesystem.Resolved, at: Spot) ?Target { - const to = std.meta.stringToEnum(Port, port); - if (to == .url) return .{ .url = if (found) |f| f.path else text }; - const f = found orelse return null; - if (to == null) { - const k = p.kinds.byName(port) orelse return null; - return if (f.dir) null else .{ .kind = .{ .path = f.path, .kind = k, .at = at } }; - } - return switch (to.?) { - .url => unreachable, - .dir => if (f.dir) .{ .dir = f.path } else null, - .file => if (f.dir) null else .{ .file = .{ .path = f.path, .at = at } }, - }; -} - pub fn resolve(p: ?*pardes.Pardes, word_raw: []const u8, cwd: []const u8, realbuf: *[4096]u8) Target { const trimmed = std.mem.trim(u8, word_raw, " \t\r\n"); const pl = parsePathLine(trimmed); @@ -225,42 +175,6 @@ pub fn resolve(p: ?*pardes.Pardes, word_raw: []const u8, cwd: []const u8, realbu } } - if (p) |pp| if (pp.plumb.items.len > 0) { - var found: ?filesystem.Resolved = null; - var looked = false; - for (pp.plumb.items) |rule| { - var words = std.mem.tokenizeAny(u8, rule, " \t"); - const how = words.next() orelse continue; - // The file is asked about once, and only by a rule that needs it. - const prefix = std.mem.eql(u8, how, "prefix"); - if (!looked and !prefix) { - found = filesystem.resolve(p, word, cwd, realbuf); - looked = true; - } - const file = if (found) |f| !f.dir else false; - var hit = std.mem.eql(u8, how, "isfile") and file or - std.mem.eql(u8, how, "isdir") and found != null and !file; - var port: []const u8 = ""; - while (words.next()) |w| { - if (std.mem.eql(u8, w, "to")) { - port = words.next() orelse ""; - break; - } - if (prefix and std.mem.startsWith(u8, trimmed, w)) hit = true; - // A suffix is a file's: plumb's basic pairs each with `arg isfile`. - if (std.mem.eql(u8, how, "suffix") and file and std.ascii.endsWithIgnoreCase(found.?.path, w)) hit = true; - } - if (!hit) continue; - const url = std.mem.eql(u8, port, "url"); - if (!looked and !url) { - found = filesystem.resolve(p, word, cwd, realbuf); - looked = true; - } - // A prefix rule's url is the text, never a file it also names. - if (plumbTarget(pp, port, trimmed, if (prefix and url) null else found, pl.at)) |t| return t; - } - }; - for (config.url_schemes) |scheme| { if (std.mem.startsWith(u8, trimmed, scheme)) return .{ .url = trimmed }; } @@ -873,25 +787,59 @@ pub fn clearNavigationSelection(p: *Pardes, pane: *Pane) void { if (v.drag == .select and p.panes[v.drag.select.id] == pane) v.drag = .none; } +/// The directories a relative name is looked for in, in order, as acme's +/// look tries its window's and then the other windows' (Incl's come +/// after, the caller's, as includename's): `first` (the pane's own, a +/// plumb message's wdir), then the directory of each pane of the jump list +/// but `from`, newest first, each once. +pub const Dirs = struct { + p: *Pardes, + from: ?usize, + seen: [MAX_PANES + 1][]const u8 = undefined, + nseen: usize = 0, + /// The next of the jump list's, counted from its newest. + n: usize = 1, + + pub fn init(p: *Pardes, from: ?usize, first: ?[]const u8) Dirs { + var d: Dirs = .{ .p = p, .from = from }; + if (first) |dir| { + d.seen[0] = dir; + d.nseen = 1; + d.n = 0; + } + return d; + } + + pub fn next(d: *Dirs) ?[]const u8 { + if (d.n == 0) { + d.n = 1; + return d.seen[0]; + } + const id = d.from orelse return null; + const jumps = &d.p.view().jumps; + cand: while (d.n <= jumps.n) { + const k = jumps.list[jumps.n - d.n].pane; + d.n += 1; + if (k == id) continue; + const dir = Pardes.paneDir(d.p.panes[k] orelse continue); + for (d.seen[0..d.nseen]) |s| if (std.mem.eql(u8, s, dir)) continue :cand; + d.seen[d.nseen] = dir; + d.nseen += 1; + return dir; + } + return null; + } +}; + /// Resolve without changing focus or falling back to search. PDF links use /// the same location rules as an ordinary Look before offering a choice. fn resolveLookTarget(p: *Pardes, id: usize, txt: []const u8, realbuf: *[4096]u8) Target { - const v = p.view(); const trimmed = std.mem.trim(u8, txt, " \t\r\n"); const pl = parsePathLine(trimmed); if (pl.path.len > 0) if (openPaneTarget(p, pl.path, pl.at)) |target| return target; var found: Target = .none; - var seen: [MAX_PANES][]const u8 = undefined; - var nseen: usize = 0; - var n: usize = 0; - cand: while (n <= v.jumps.n) : (n += 1) { - const k: usize = if (n == 0) id else v.jumps.list[v.jumps.n - n].pane; - if (n > 0 and k == id) continue; // tried first, skip the rerun - const op = p.panes[k] orelse continue; - const dir = Pardes.paneDir(op); - for (seen[0..nseen]) |s| if (std.mem.eql(u8, s, dir)) continue :cand; - seen[nseen] = dir; - nseen += 1; + var dirs: Dirs = .init(p, id, if (p.panes[id]) |op| Pardes.paneDir(op) else null); + while (dirs.next()) |dir| { if (pl.path.len > 0 and pl.path[0] != '/') { var joinbuf: [2048]u8 = undefined; if (std.fmt.bufPrint(&joinbuf, "{s}/{s}", .{ dir, pl.path }) catch null) |j| @@ -1090,7 +1038,6 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text: // 9P is no keyboard input, and searches whatever the key mode. if (pane.addon != null or (pane.body.mode == .tty and !p.fs.serving)) return; if (text.len == 0) return; - if (hunks.lookedAtCommit(p, id, pane, trimmed)) return; if (pane.file != null) return lookWord(p, id, pane, text); p.word_look = true; defer p.word_look = false; @@ -1558,6 +1505,36 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { for (0..pane.sel.len) |slot| pane.clearPointerSelection(slot); pane.sel = @splat(.{}); } + // The plumber, asked before Look's own look as acme asks it (look.c's + // look3): what is looked at, sent from this pane. A name already open + // in a pane is focused first, never sent; nor is a look that opens + // as text (look_text), or the edit port's open of what was. A message + // the rules give back to `edit` as sent is Look's own to open, on what + // it found; one nothing takes, Look's too. + const shown = switch (found) { + .pane => true, + .file => |f| openPaneTarget(p, f.path, f.at) != null, + .kind => |k| openPaneTarget(p, k.path, .{}) != null, + .none, .dir, .url => false, + }; + if (!shown and !p.look_text) { + const msg: Plumb.Msg = .{ + .src = if (pane.addon) |k| k.nameOf() else if (pane.body.mode == .tty and !p.fs.serving) "term" else "pardes", + .wdir = Pardes.paneDir(pane), + .type = "text", + .data = trimmed, + }; + const seen: Plumb.Seen = .{ .name = pl.path, .found = switch (found) { + .file => |f| .{ .path = f.path }, + .kind => |k| .{ .path = k.path }, + .dir => |d| .{ .path = d, .dir = true }, + .none, .url, .pane => null, + } }; + switch (Plumb.send(p, id, msg, seen)) { + .done => return, + .look, .refused => {}, + } + } switch (found) { .none => lookUnresolved(p, id, pane, trimmed, std.mem.trimEnd(u8, txt, "\r\n")), .pane => |t| { @@ -1582,7 +1559,8 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { focusPaneLine(p, t.id, t.at, .center); settleLine(p, id, trimmed, t.at, before, null); }, - .url => |u| if (u.len <= 256) p.emit(.{ .open_link = .from(u) }), + // acme's own look opens no URL: the plumber's web port does. + .url => lookUnresolved(p, id, pane, trimmed, std.mem.trimEnd(u8, txt, "\r\n")), .dir => |dir| { // A directory that is not there (the pane's own, gone): said, // ENOENT, no terminal made in it. @@ -1603,7 +1581,6 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { const before = v.active; var opened: ?usize = null; if (!focusPaneByPath(p, target.path, target.at)) { - if (hunks.lookedAt(p, id, target.path, target.at)) return; const free = p.freeSlot() orelse return p.reportError(id, "look", error.NoPaneSlots); const nt = panes.File.open(p, free, target.path, target.at.line) catch |err| return lookOpenFailed(p, id, target.path, err); @@ -2649,51 +2626,83 @@ test "Look on a diff line is the look of the address it names, selected by hand: try std.testing.expectEqual(@as(i32, 1), seen[0].row); } -test "Plumb: the user's rules come before the built-in ones, the first that matches wins, a bad rule is refused, a dump keeps them" { +test "Plumb: a look sends what it looks at, the rules written first: a rule's word or port takes it, a name open in a pane is focused unsent, one nothing takes is Look's own" { if (!platform_has_fs) return; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "pic.svg", .data = "" }); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "shot.PNG", .data = "x" }); var dir_buf: [4096]u8 = undefined; const root = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + var pic_buf: [4200]u8 = undefined; + const pic = try std.fmt.bufPrint(&pic_buf, "{s}/pic.svg", .{root}); const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30 }); defer p.deinit(); - // A kind as a library brings it, its name and extension (no code: a - // look only names it). - try std.testing.expect(p.kinds.take(.{ .name = "image", .exts = ".png" }, "") == null); + const pane = try p.setTestFile("see https://ziglang.org here\n"); + // The defaults: a URL to the web port, the host's opener; the hover + // asks resolve, as before. + lookAt(p, 0, "https://ziglang.org"); + var linked = false; + while (p.nextEffect()) |e| if (e == .open_link) { + try std.testing.expectEqualStrings("https://ziglang.org", e.open_link.slice()); + linked = true; + }; + try std.testing.expect(linked); var real: [4096]u8 = undefined; - // None by default: today's ladder. - try std.testing.expect(resolve(p, "pic.svg", root, &real) == .file); - try std.testing.expect(resolve(p, "shot.PNG", root, &real) == .kind); try std.testing.expect(resolve(p, "https://ziglang.org", root, &real) == .url); - try std.testing.expect(p.executeBuiltinLine(0, "Plumb suffix .svg .SVGZ to image")); - try std.testing.expect(p.executeBuiltinLine(0, "Plumb suffix .png to file")); - try std.testing.expect(p.executeBuiltinLine(0, "Plumb prefix https:// to file")); - try std.testing.expect(p.executeBuiltinLine(0, "Plumb prefix gopher:// to url")); - try std.testing.expect(resolve(p, "pic.svg", root, &real) == .kind); - // Any case, as the kinds' extensions are. - try std.testing.expect(resolve(p, "shot.PNG", root, &real) == .file); - // A rule that cannot make its target (no such file) lets the next try. - try std.testing.expect(resolve(p, "https://ziglang.org", root, &real) == .url); - try std.testing.expectEqualStrings("gopher://x", resolve(p, "gopher://x", root, &real).url); - // A suffix is a file's: a word naming no file matches none. - try std.testing.expect(resolve(p, "nothere.svg", root, &real) == .none); - // Refused, in words, the list as it was: a kind not loaded too. - for ([_][]const u8{ "Plumb matches x to image", "Plumb suffix to image", "Plumb isdir .x to dir", "Plumb suffix .x to nowhere", "Plumb suffix .x to pdf", "Plumb suffix .x", "Plumb suffix .x to image extra" }) |bad| - try std.testing.expect(p.executeBuiltinLine(0, bad)); - try std.testing.expectEqual(@as(usize, 4), p.plumb.items.len); - try std.testing.expectEqualStrings("suffix .svg .SVGZ to image", p.plumb.items[0]); - try std.testing.expect(p.executeBuiltinLine(0, "Plumb")); - const pane = p.panes[0].?; - try std.testing.expect(std.mem.indexOf(u8, pane.msg[0..pane.msg_len], "; suffix .png to file") != null); - try pardes.dump.dumpState(p); - const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); - defer restored.deinit(); - try std.testing.expectEqual(@as(usize, 4), restored.plumb.items.len); - // The kind gone, its rule is tried like any that cannot: the ladder's. - p.kinds.drop(p.kinds.byName("image").?); - try std.testing.expect(resolve(p, "pic.svg", root, &real) == .file); - try std.testing.expect(p.executeBuiltinLine(0, "Plumb -")); - try std.testing.expectEqual(@as(usize, 0), p.plumb.items.len); + // A rule set written first takes what it matches: its word started in + // place, from the looking pane, and no pane opened. + try std.testing.expect(Plumb.apply(p, false, "plumb/rules", "type is text\ndata matches '.*\\.svg'\narg isfile $data\nplumb start Msg svg $file\n\ninclude basic\n") == null); + lookAt(p, 0, pic); + try std.testing.expectEqual(@as(usize, 0), p.view().active); + var said_buf: [4300]u8 = undefined; + try std.testing.expectEqualStrings(try std.fmt.bufPrint(&said_buf, "svg {s}", .{pic}), pane.msg[0..pane.msg_len]); + // A name open in a pane is focused, never sent. + p.look_text = true; + lookAt(p, 0, pic); + p.look_text = false; + const opened = p.view().active; + try std.testing.expect(opened != 0); + p.view().active = 0; + p.setMessage(0, "before"); + lookAt(p, 0, pic); + try std.testing.expectEqual(opened, p.view().active); + try std.testing.expectEqualStrings("before", pane.msg[0..pane.msg_len]); + // With no web rule, a URL is a word Look searches for. + p.view().active = 0; + try std.testing.expect(Plumb.apply(p, false, "plumb/rules", "type is text\narg isfile $data\nplumb to edit\n") == null); + while (p.nextEffect()) |_| {} + lookAt(p, 0, "https://ziglang.org"); + while (p.nextEffect()) |e| try std.testing.expect(e != .open_link); + const dot = @import("ninep/pane.zig").dotOf(pane); + try std.testing.expectEqualStrings("https://ziglang.org", pane.file.?.content[dot.q0..dot.q1]); +} + +test "Plumb: a commit hash looked at in a git work tree is git show's, paged; outside one Diff declines, and the word is searched for" { + if (!platform_has_fs) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDir(std.testing.io, ".git", .default_dir); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "notes.txt", .data = "fixed in 3f2a9c1\n" }); + var dir_buf: [4096]u8 = undefined; + const root = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)]; + const p = try Pardes.init(std.testing.allocator, .{ .cols = 100, .rows = 30 }); + defer p.deinit(); + // /test.txt: its directory, /, is in no work tree. + const pane = try p.setTestFile("fixed in 3f2a9c1\n"); + lookAt(p, 0, "3f2a9c1"); + const dot = @import("ninep/pane.zig").dotOf(pane); + try std.testing.expectEqualStrings("3f2a9c1", pane.file.?.content[dot.q0..dot.q1]); + for (p.panes) |slot| if (slot) |pn| try std.testing.expect(pn.command == null); + var notes_buf: [4200]u8 = undefined; + lookAt(p, 0, try std.fmt.bufPrint(¬es_buf, "{s}/notes.txt", .{root})); + const notes = p.view().active; + try std.testing.expect(notes != 0); + lookAt(p, notes, "3f2a9c1"); + var paged = false; + for (p.panes) |slot| if (slot) |pn| if (pn.command) |cmd| { + try std.testing.expect(std.mem.endsWith(u8, cmd, "git show 3f2a9c1")); + try std.testing.expect(pn.command_pages); + paged = true; + }; + try std.testing.expect(paged); } diff --git a/src/macos.zig b/src/macos.zig index 254cf2a7..8ad8fd71 100644 --- a/src/macos.zig +++ b/src/macos.zig @@ -1624,6 +1624,7 @@ const vtable: pardes.Host.VTable = .{ .set_clipboard = setClipboard, .read_clipboard = readClipboard, .open_link = openLink, + .start = host_io.startDetached, .lsp = lspRequest, .pipe = pipeRequest, }; diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index 8902f11e..bd3f3b3b 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -1408,7 +1408,7 @@ fn writeNow(p: *Pardes, req: Req, target: Target) Reply { fn writeRules(p: *Pardes, req: Req) Reply { const done: Reply = .{ .tag = req.tag, .written = @intCast(req.data.len) }; // A close's rest (runClosedLines), or a write with no open: whole. - const o = openOf(p, req) orelse return if (Plumb.apply(p, true, req.data)) |why| failText(req.tag, E.INVAL, why) else done; + const o = openOf(p, req) orelse return if (Plumb.apply(p, true, "plumb/rules", req.data)) |why| failText(req.tag, E.INVAL, why) else done; if (o.pending.items.len + req.data.len > Plumb.max_text) { o.pending.clearRetainingCapacity(); return failText(req.tag, E.INVAL, std.fmt.comptimePrint("rules too long; max {d} KiB", .{Plumb.max_text / 1024})); @@ -1416,7 +1416,7 @@ fn writeRules(p: *Pardes, req: Req) Reply { o.pending.appendSlice(p.gpa, req.data) catch return Reply.fail(req.tag, E.NOMEM); const end = Plumb.wholeSets(o.pending.items); if (end == 0) return done; - const why = Plumb.apply(p, true, o.pending.items[0..end]); + const why = Plumb.apply(p, true, "plumb/rules", o.pending.items[0..end]); if (why != null) o.pending.clearRetainingCapacity() else { const rest = o.pending.items.len - end; std.mem.copyForwards(u8, o.pending.items[0..rest], o.pending.items[end..]); @@ -1449,7 +1449,10 @@ fn writeSend(p: *Pardes, req: Req) Reply { }, .msg => |m| { defer if (o) |op| op.pending.clearRetainingCapacity(); - if (Plumb.send(p, null, m)) |why| return failText(req.tag, E.IO, why); + switch (Plumb.send(p, null, m, null)) { + .refused => |why| return failText(req.tag, E.IO, why), + .done, .look => {}, + } return .{ .tag = req.tag, .written = @intCast(req.data.len) }; }, } diff --git a/src/pardes.zig b/src/pardes.zig index 511f7d35..b85d50ff 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -8,6 +8,7 @@ pub const glide = @import("glide.zig"); pub const FrameStats = @import("FrameStats.zig"); pub const modal = @import("modal.zig"); pub const look = @import("look.zig"); +pub const Plumb = @import("Plumb.zig"); pub const filesystem = @import("fs.zig"); pub const ctlfs = @import("ninep/tree.zig"); pub const syntax = @import("syntax.zig"); diff --git a/src/plumbing b/src/plumbing index 74c1f306..1a446f74 100644 --- a/src/plumbing +++ b/src/plumbing @@ -4,13 +4,24 @@ # hold takes it, and its actions say where it goes: a port pardes reads # itself (edit: a file or directory opened as Look opens one; web: the # host's browser; a loaded kind by its name, `image`, `pdf`), another -# port a program reads, or a word or command started. +# port a program reads, or a word or program started. One that none +# takes is Look's own: a file or directory opened, else the word +# searched for. A look sends what it looks at: type text, src pardes +# (term from a terminal's raw mode, a kind's name from its pane), wdir +# its pane's directory, data the name as Look reads it. # urls go to the web browser (the host's: xdg-open, open on macOS) type is text data matches 'https?://.*' plumb to web +# a diff or patch looked at bare is stacked in a +Diff; one with no +# hunk in it opens as text +type is text +data matches '.*\.(diff|patch)' +arg isfile $data +plumb start Diff $file + # existing directories, and existing files at the place written after # them, go to the editor; a file a kind shows (a picture, a PDF) to # that kind @@ -21,3 +32,13 @@ plumb to edit type is text arg isfile $data plumb to edit + +# a commit hash looked at in the editor, in a git work tree: git show, +# stacked in a +Diff (outside one, Diff declines and the word is +# searched for) +type is text +src is pardes +data matches '[0-9a-f]{7,40}' +data matches '[0-9a-f]*[0-9][0-9a-f]*' +data matches '[0-9a-f]*[a-f][0-9a-f]*' +plumb start Diff $0 diff --git a/src/tui/tui.zig b/src/tui/tui.zig index 77c8ce2b..394a9874 100644 --- a/src/tui/tui.zig +++ b/src/tui/tui.zig @@ -1311,6 +1311,7 @@ const Shell = struct { .set_clipboard = setClipboard, .read_clipboard = readClipboard, .open_link = openLink, + .start = host_io.startDetached, .lsp = lsp, .pipe = pipe, .search = search, -- cgit v1.3