diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-17 02:31:20 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-17 12:15:01 -0300 |
| commit | f749eb712d990a9b03f1db372d5311e77bd32edd (patch) | |
| tree | ee4d9966f1eb293054b7ed865c9d4d6eb49e432b /src | |
| parent | 8f6621f9f70db86d56266a59b56dfb92b324b0d9 (diff) | |
| parent | b3d32656413734952bc918c2d4cfd12fede6c214 (diff) | |
| download | pardes-f749eb712d990a9b03f1db372d5311e77bd32edd.tar.gz pardes-f749eb712d990a9b03f1db372d5311e77bd32edd.zip | |
integration: the terminal behind src/Term.zig, with the diff viewer and the plumber's first phase
A merge of term-phase0 and pardes-next. File.zig's recolorSyntax keeps the theme's grounds and names Term.Filter and Term.Span; the changelog keeps both sides' entries, the palette sentence in the place of the entry the terminal work cut down. core-test 985/985 on tui; the diff, pager and tree process cases pass, goldens unchanged.
Co-Authored-By: Claude Fable 5.2 <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'src')
| -rw-r--r-- | src/CHANGELOG.md | 45 | ||||
| -rw-r--r-- | src/Core.zig | 9 | ||||
| -rw-r--r-- | src/File.zig | 120 | ||||
| -rw-r--r-- | src/Output.zig | 97 | ||||
| -rw-r--r-- | src/Plumb.zig | 1241 | ||||
| -rw-r--r-- | src/Query.zig | 62 | ||||
| -rw-r--r-- | src/body_layer.zig | 2 | ||||
| -rw-r--r-- | src/builtins.zig | 14 | ||||
| -rw-r--r-- | src/colors.zig | 37 | ||||
| -rw-r--r-- | src/config.zig | 1 | ||||
| -rw-r--r-- | src/draw.zig | 95 | ||||
| -rw-r--r-- | src/exec.zig | 48 | ||||
| -rw-r--r-- | src/fs-help.txt | 6 | ||||
| -rw-r--r-- | src/grammar_manifest.zig | 108 | ||||
| -rw-r--r-- | src/gui/gui.zig | 14 | ||||
| -rw-r--r-- | src/hunks.zig | 350 | ||||
| -rw-r--r-- | src/layout.zig | 14 | ||||
| -rw-r--r-- | src/lib_syntax.zig | 19 | ||||
| -rw-r--r-- | src/locations.zig | 176 | ||||
| -rw-r--r-- | src/look.zig | 106 | ||||
| -rw-r--r-- | src/mouse.zig | 261 | ||||
| -rw-r--r-- | src/ninep/ctl.zig | 12 | ||||
| -rw-r--r-- | src/ninep/events.zig | 19 | ||||
| -rw-r--r-- | src/ninep/pane.zig | 93 | ||||
| -rw-r--r-- | src/ninep/pty.zig | 4 | ||||
| -rw-r--r-- | src/ninep/tree.zig | 144 | ||||
| -rw-r--r-- | src/panes.zig | 2 | ||||
| -rw-r--r-- | src/pardes.zig | 1 | ||||
| -rw-r--r-- | src/plumbing | 23 | ||||
| -rw-r--r-- | src/regexp.zig | 8 | ||||
| -rw-r--r-- | src/surface.zig | 18 | ||||
| -rw-r--r-- | src/syntax.zig | 171 |
32 files changed, 2406 insertions, 914 deletions
diff --git a/src/CHANGELOG.md b/src/CHANGELOG.md index 5aa8141c..e398b43f 100644 --- a/src/CHANGELOG.md +++ b/src/CHANGELOG.md @@ -9,6 +9,51 @@ (docs/next-terminal.md). Editing a terminal's text is the core's, on a copy of its rows, as before; nothing a session does changes. +- 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. + +- The plumber, Plan 9's, is in the session: `plumb/rules` holds its + rules in plumb(6)'s language (rule sets of `object verb arg` lines, + variables, `include`, `matches` over the whole text or around a click, + `isfile` and `isdir` finding a name as a look does), and `plumb/send` + takes a message and sends it where they say, to a port pardes reads + (`edit`, `web`, a loaded kind) or to a word or command started, with + Plan 9's words when it cannot. A session starts with `include basic`, + pardes's rules (`src/plumbing`). Kept in a dump. `$1`-`$9` are refused, + the regular expressions having no submatches. A look does not ask it + yet. + +- A query pane's row looked at on its address (its gutter) opens the + row's place however the look arrives, as a click there always did: an + empty look written back to the pane's `event` file, and the whole row + written to its `look` file, now take the address the row holds, not a + word of its text. A diff's lines answer all three ways through the same + one function (`look.rowAddressAt`). + +- Each pane's directory over 9P has a `rows` file: a line a body row of a + results pane (+Search, +Callstack, +Diff, a language server's list), + where it points (`path`, line, column, the address's end, where its code + starts) and how it is coloured (runs of `keyword`, `string`, ... and the + grounds `add`, `del`, `emph`, `line`), so a 9P client reads their + addresses as data, not by parsing the text. A write at offset 0 replaces + a pane's rows, a later one adds to them; rows its text cannot hold are + refused. An edit drops them, as before. The editor's own producers set + rows the same one way. + +- A drag draws no guide lines: no dashes where a pane or column would + land, no rail for a carried column, no dashed seam under a pane rule + held. The line between two columns no longer resizes them (nor, at a + pane's corner, the panes too): a press there is a press in the pane. + A column resizes by its box, left of its tag; a pane by its own box, + or in a window by the rule above it. + +- An edit to the core recompiles it about 3 s sooner (`core-test`, 13 s to + 10 s): the build keeps each grammar's highlight patterns that pardes + colours once, where every compile of every program that takes the core + did it again, a quarter of its time. A package that depends on pardes + is given the same filtered queries. + - The 256-colour palette Petscii art and the window draw a palette colour with is pardes's own (`colors.xterm`), ghostty-vt's default to the entry. diff --git a/src/Core.zig b/src/Core.zig index 5516265e..7d8cfb0e 100644 --- a/src/Core.zig +++ b/src/Core.zig @@ -39,6 +39,7 @@ const Rect = pardes.Rect; const Registers = pardes.Registers; const RowMetrics = pardes.RowMetrics; const Store = @import("Store.zig"); +const Plumb = @import("Plumb.zig"); const Db = pardes.Db; const Stream = pardes.Stream; const Surface = pardes.Surface; @@ -210,6 +211,9 @@ 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 = .{}, /// Zerox's groups of panes on one buffer (File.syncTwins), and the id /// the next takes. twin_groups: std.ArrayList(pardes.panes.File.TwinGroup) = .empty, @@ -226,6 +230,9 @@ 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, /// 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. @@ -758,6 +765,7 @@ pub fn deinit(p: *Pardes) void { 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); p.fs.batch.bytes.deinit(p.gpa); @@ -1711,6 +1719,7 @@ 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/File.zig b/src/File.zig index 2a7d5b40..64614191 100644 --- a/src/File.zig +++ b/src/File.zig @@ -616,6 +616,29 @@ pub fn setContent(p: *Pardes, f: *State, new: []u8) void { setContentSpan(p, f, new, null); } +/// `rows`, a row a line of the text from its first (where each points, how +/// it is coloured: locations.Row), made the pane's, taken: the one way a +/// pane's rows are set, by a producer in the editor (Output.fillRows, a +/// query pane) or from outside (the pane's `rows` file). RowsMismatch, the +/// rows still the caller's, for rows the text cannot hold: more of them +/// than it has lines, or an offset or styles past its line's end. Rows +/// equal to the pane's keep its painting; others drop it, to be painted +/// from them. An edit of the text drops them (setContentSpan). +pub fn setRows(p: *Pardes, f: *State, rows: []locations.Row) error{RowsMismatch}!void { + var lines = std.mem.splitScalar(u8, f.content, '\n'); + for (rows) |row| { + const line = lines.next() orelse return error.RowsMismatch; + if (row.location_end > line.len or row.code_start > line.len or row.colors.len > line.len - row.code_start) return error.RowsMismatch; + } + if (locations.equalRows(f.location_rows, rows)) return locations.freeRows(p.gpa, rows); + locations.freeRows(p.gpa, f.location_rows); + f.location_rows = rows; + if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); + f.highlights = &.{}; + f.highlight_start = 0; + f.syntax_dirty = true; +} + /// `setContent` for a splice that knows what it left alone at either end, /// so it is not found again by comparing the whole text. The edit is what /// lies between them, made by `edit`, which takes `new`, a whole text its @@ -1791,59 +1814,6 @@ fn fillBody(dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) const SynStyle = struct { fg: [3]u8, bold: bool }; -/// How added and removed diff lines are told apart in every theme: a row -/// ground a little way from the page toward green or red (the theme's own -/// ANSI green and red where it has a palette), and the prefix column in -/// that hue, pushed toward the ink until it reads on that ground. The -/// syntax colours are drawn over the ground unchanged. -pub const DiffTints = struct { - added_bg: [3]u8, - removed_bg: [3]u8, - /// The words a changed line changed (hunks.zig), on a stronger ground. - added_emph_bg: [3]u8, - removed_emph_bg: [3]u8, - /// A +Diff line added or removed whole: a faint ground. - added_line_bg: [3]u8, - removed_line_bg: [3]u8, - added_fg: [3]u8, - removed_fg: [3]u8, - - pub fn of(p: *Pardes) DiffTints { - const th = p.theme(); - const page = th.bg orelse th.tag_bg; - const ink = th.fg orelse th.tag_fg; - const green: [3]u8 = if (th.palette) |pal| pal[2] else .{ 0x2e, 0xa0, 0x43 }; - const red: [3]u8 = if (th.palette) |pal| pal[1] else .{ 0xcf, 0x22, 0x2e }; - const added_bg = Colors.mixOklab(page, green, 0.18); - const removed_bg = Colors.mixOklab(page, red, 0.18); - return .{ - .added_bg = added_bg, - .removed_bg = removed_bg, - .added_emph_bg = Colors.mixOklab(page, green, 0.28), - .removed_emph_bg = Colors.mixOklab(page, red, 0.28), - .added_line_bg = Colors.mixOklab(page, green, 0.07), - .removed_line_bg = Colors.mixOklab(page, red, 0.07), - .added_fg = legible(green, ink, added_bg), - .removed_fg = legible(red, ink, removed_bg), - }; - } - - fn legible(hue: [3]u8, ink: [3]u8, ground: [3]u8) [3]u8 { - var fg = hue; - var step: usize = 0; - while (step < 4 and Colors.contrast(fg, ground) < 3) : (step += 1) fg = Colors.mixOklab(fg, ink, 0.4); - return fg; - } - - /// The row ground and prefix ink for a line's style byte, if it is an - /// added or removed line. - pub fn forStyle(t: *const DiffTints, style: u8) ?struct { bg: [3]u8, fg: [3]u8, emph_bg: [3]u8, line_bg: [3]u8 } { - if (style & syntax.diff_added != 0) return .{ .bg = t.added_bg, .fg = t.added_fg, .emph_bg = t.added_emph_bg, .line_bg = t.added_line_bg }; - if (style & syntax.diff_removed != 0) return .{ .bg = t.removed_bg, .fg = t.removed_fg, .emph_bg = t.removed_emph_bg, .line_bg = t.removed_line_bg }; - return null; - } -}; - fn synStyle(p: *Pardes, sy: syntax.Syn) ?SynStyle { return .{ .fg = Colors.synInk(p.theme(), sy) orelse return null, .bold = false }; } @@ -1858,12 +1828,9 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. const prefix_width = gutterWidth(pane); const tz_recolor = tracy.zone(@src(), "synRecolor"); defer tz_recolor.end(); - // A diff's rows, and a +Diff's (hunks.zig): their markers coloured. - // A diff's whole row is tinted; a +Diff tints only the words a - // changed line changed. - const algo = pane.colorAlgo(); - const tints: ?DiffTints = if ((algo == .diff or algo == .locations) and highlights.len > 0) DiffTints.of(p) else null; - const row_tint = algo == .diff; + // A row whose first byte names a hue (syntax.ground_add, _del): its + // grounds, the theme's, worked out once a frame and only for one. + var grounds: ?Colors.Grounds = null; var filtered_storage: pardes.Term.Filter = undefined; const filtered: ?*pardes.Term.Filter = if (pane.tty_filter and spans.len > 0) blk: { filtered_storage = .init(p, null); @@ -1901,19 +1868,20 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. const metadata: ?locations.Row = if (row_index < f.location_rows.len) f.location_rows[row_index] else null; const decoration = Output.decorateRow(f.output, line, metadata); const chrome: ?*const pardes.ChromeTheme = if (decoration.plain()) null else p.bodyChrome(); - // An added or removed line's row, every wrapped row of it, is tinted. - const tint = if (tints) |*t| if (base >= highlight_start and base - highlight_start < highlights.len) - t.forStyle(highlights[base - highlight_start]) - else - null else null; + // The row's first byte: its hue and its ground, on every wrapped + // row of it (syntax.ground_add). + const lead: u8 = if (base >= highlight_start and base - highlight_start < highlights.len) highlights[base - highlight_start] else 0; + const tint: ?Colors.Grounds.Ground = if (lead & (syntax.ground_add | syntax.ground_del) == 0) null else (grounds orelse ground: { + grounds = .of(p.theme()); + break :ground grounds.?; + }).forStyle(lead); if (tint) |t| if (prefix_width < tw) { - // A +Diff line added or removed whole: faintly (hunks.zig). - const whole = highlights[base - highlight_start] & syntax.diff_whole != 0; - if (row_tint or whole) s.tint(tx + @as(u16, @intCast(prefix_width)), body_y + vr, tw -| @as(u16, @intCast(prefix_width)), if (row_tint) t.bg else t.line_bg, null); + const ground: ?[3]u8 = if (lead & syntax.ground_emph != 0) t.row else if (lead & syntax.ground_line != 0) t.line else null; + if (ground) |g| s.tint(tx + @as(u16, @intCast(prefix_width)), body_y + vr, tw -| @as(u16, @intCast(prefix_width)), g, null); }; - // A +Pager's own colours (Term.page) on every row but one the diff - // look tints: an added or removed line is drawn as pardes draws a - // diff, and git's red and green on it would only fight the tint. + // A +Pager's own colours (Term.page) on every row but one in a hue: + // an added or removed line is drawn as pardes draws a diff, and + // git's red and green on it would only fight the tint. var span_at = if (tint != null) spans.len else std.sort.partitionPoint(pardes.Term.Span, spans, base + hs, struct { fn before(at: usize, span: pardes.Term.Span) bool { return span.end <= at; @@ -1947,7 +1915,7 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. const hidx = idx - highlight_start; if (hidx < highlights.len) { if (if (tint != null and hs + c == 0) - SynStyle{ .fg = tint.?.fg, .bold = true } + SynStyle{ .fg = tint.?.ink, .bold = true } else synStyle(p, @fromBackingInt(@intCast(highlights[hidx] & syntax.syn_bits)))) |ss| { @@ -1959,10 +1927,10 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. cell.style.bold = ss.bold; } } - if (tint) |t| if (highlights[hidx] & syntax.diff_emph != 0) { + if (tint) |t| if (highlights[hidx] & syntax.ground_emph != 0 and hs + c > 0) { var fill: usize = 0; while (fill < cells and prefix_width + screen_c + fill < tw) : (fill += 1) - s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr).style.bg = .{ .rgb = t.emph_bg }; + s.at(tx + @as(u16, @intCast(prefix_width + screen_c + fill)), body_y + vr).style.bg = .{ .rgb = t.emph }; }; } } @@ -2131,7 +2099,7 @@ pub fn recolorDiffOutput(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, t } if (lo > hi) return; const styles = syntax.highlightDiffRows(arena, flat, lo, hi, true) catch return; - const tints = DiffTints.of(p); + const tints: Colors.Grounds = .of(p.theme()); const ink = p.theme().fg orelse p.theme().tag_fg; const body_y = p.bodyTop(pane, r); shown = std.mem.splitScalar(u8, body, '\n'); @@ -2140,7 +2108,7 @@ pub fn recolorDiffOutput(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, t const view = maybe orelse continue; const base = @intFromPtr(rows[view.row].ptr) - flat_start - lo; const tint = if (base < styles.len) tints.forStyle(styles[base]) else null; - if (tint) |t| s.tint(tx, body_y + @as(u16, @intCast(vr)), tw, t.bg, null); + if (tint) |t| s.tint(tx, body_y + @as(u16, @intCast(vr)), tw, t.row, null); var c: usize = 0; var screen_c: usize = 0; while (c < line.len and screen_c < tw) { @@ -2152,7 +2120,7 @@ pub fn recolorDiffOutput(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, t // On an added or removed line, what the program coloured red or // green is the tint's to say now: its code takes the page's ink. const paint: ?SynStyle = if (tint != null and prefix) - .{ .fg = tint.?.fg, .bold = true } + .{ .fg = tint.?.ink, .bold = true } else if (synStyle(p, @fromBackingInt(@intCast(style & syntax.syn_bits)))) |ss| ss else if (tint != null) diff --git a/src/Output.zig b/src/Output.zig index 0c6fdfc2..2e49ceb3 100644 --- a/src/Output.zig +++ b/src/Output.zig @@ -14,8 +14,6 @@ const lsp = @import("lsp/lsp.zig"); const look = @import("look.zig"); const locations = @import("locations.zig"); const layout = @import("layout.zig"); -const hunks = @import("hunks.zig"); -const diff = @import("diff.zig"); const Pane = panes.Pane; const File = panes.File; @@ -414,17 +412,19 @@ pub fn fillResults(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: [] result_rows = formatted.rows; anchor = formatted.anchor; } - _ = try fillRows(p, id, dir, from, arg, result_content, result_rows, anchor); + _ = try fillRows(p, id, dir, from, null, arg, result_content, result_rows, anchor); } /// Rows already laid out (`content`, `rows` its metadata, both taken /// when it succeeds, the caller's still when it fails) into the pane they -/// belong in: the one a run of `from` with `arg` in `dir` showed last, +/// belong in: the one named `name` (null: its origin's own name, as `open` +/// gives it) that a run of `from` with `arg` in `dir` showed last, /// refilled, else a new one placed by pane `id`. Its id. -pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []const u8, result_content: []u8, result_rows: []locations.Row, anchor: ?usize) !usize { +pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, name: ?[]const u8, arg: []const u8, result_content: []u8, result_rows: []locations.Row, anchor: ?usize) !usize { const pane = p.panes[id] orelse return error.MissingPane; if (arg.len > max_arg) return error.ArgumentTooLong; const by_arg = std.meta.activeTag(from) != .query; + const own = name orelse if (from == .kind) arg else traits(from).name; for (p.panes, 0..) |slot, i| { const rp = slot orelse continue; const rf = if (rp.file) |*f| f else continue; @@ -440,8 +440,7 @@ pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []con if (!shared and !std.meta.eql(o.from, from)) continue; if (!shared and by_arg and !std.mem.eql(u8, o.arg(), arg)) continue; if (!std.mem.eql(u8, std.Io.Dir.path.dirname(rf.path) orelse "", dir)) continue; - if (std.meta.eql(from, Origin{ .cmd = .Diff }) and - !std.mem.eql(u8, diff.commitHash(rf.content) orelse "", diff.commitHash(result_content) orelse "")) continue; + if (!std.mem.eql(u8, std.Io.Dir.path.basename(rf.path), std.Io.Dir.path.basename(own))) continue; o.from = from; p.fs.refilled = rp.serial; try setArg(o, arg); @@ -451,16 +450,10 @@ pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []con File.setContent(p, rf, result_content); resetBody(p, rp); } - if (locations.equalRows(rf.location_rows, result_rows)) { + File.setRows(p, rf, result_rows) catch |err| { locations.freeRows(p.gpa, result_rows); - } else { - locations.freeRows(p.gpa, rf.location_rows); - rf.location_rows = result_rows; - if (rf.highlights.len > 0) p.tree_sitter_gpa.free(rf.highlights); - rf.highlights = &.{}; - rf.highlight_start = 0; - rf.syntax_dirty = true; - } + p.reportError(id, "rows", err); + }; p.view().active = id; if (traits(from).steps) { pane.search_pane = i; @@ -470,8 +463,17 @@ pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []con return i; } const free = p.freeSlot() orelse return error.NoPaneSlots; + const path = if (name) |named| try std.fmt.allocPrint(p.gpa, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), named }) else null; + errdefer if (path) |owned| p.gpa.free(owned); const np = try open(p, free, dir, from, arg, result_content); - np.file.?.location_rows = result_rows; + if (path) |owned| { + p.gpa.free(np.file.?.path); + np.file.?.path = owned; + } + File.setRows(p, &np.file.?, result_rows) catch |err| { + locations.freeRows(p.gpa, result_rows); + p.reportError(id, "rows", err); + }; layout.placeNew(p, id, id, free, .doc); p.view().active = id; if (traits(from).steps) { @@ -482,67 +484,6 @@ pub fn fillRows(p: *Pardes, id: usize, dir: []const u8, from: Origin, arg: []con return free; } -/// Diff: `content`, the diff at `path` (a file, a +Pager), stacked as a -/// diff viewer shows it (hunks.zig), in a +Diff where its files are found -/// (hunks.sourceRoot), placed by pane `id`, refilled when it is there. Its -/// arg names the diff (its base name, or its whole path when the +Diff -/// stands elsewhere), for Diff to go back to it. The +Diff's id; -/// NoHunks when there is none in it. -pub fn openDiff(p: *Pardes, id: usize, path: []const u8, content: []const u8) !usize { - const dir = std.Io.Dir.path.dirname(path) orelse p.sessionDir(); - const root = hunks.sourceRoot(p, dir, content); - const result = try hunks.format(p, root, content); - errdefer { - p.gpa.free(result.content); - locations.freeRows(p.gpa, result.rows); - } - var has_hunk = false; - for (result.rows) |row| has_hunk = has_hunk or row.kind == .match; - if (!has_hunk) return error.NoHunks; - const arg = if (std.mem.eql(u8, root, dir) or path.len > max_arg) std.Io.Dir.path.basename(path) else path; - const title = if (diff.commitHash(content)) |hash| - try std.fmt.allocPrint(p.gpa, "{s}/{s}-{s}", .{ std.mem.trimEnd(u8, root, "/"), config.diff_buffer, hash[0..@min(hash.len, 12)] }) - else - null; - errdefer if (title) |name| p.gpa.free(name); - const hid = try fillRows(p, id, root, .{ .cmd = .Diff }, arg, result.content, result.rows, null); - if (title) |name| { - const f = &p.panes[hid].?.file.?; - p.gpa.free(f.path); - f.path = name; - } - return hid; -} - -/// Diff on a +Diff: the diff it stacks, as text. A pane holding it -/// already (the newest: a +Pager folded under its +Diff unfolds) is -/// shown; else the file is opened as text. -pub fn showDiffText(p: *Pardes, id: usize, source: []const u8) void { - var newest: ?usize = null; - for (p.panes, 0..) |slot, i| { - const f = (slot orelse continue).file orelse continue; - if (!std.mem.eql(u8, f.path, source)) continue; - if (newest == null or p.panes[newest.?].?.serial < slot.?.serial) newest = i; - } - if (newest) |i| { - if (p.panes[i].?.collapsed) layout.toggleCollapse(p, i); - p.view().active = i; - return; - } - p.look_text = true; - defer p.look_text = false; - look.lookAt(p, id, source); -} - -/// The diff a +Diff stacks (openDiff's arg): its path. -pub fn diffSource(p: *Pardes, f: *const File.State) ?[]const u8 { - const o = f.output orelse return null; - if (!std.meta.eql(o.from, Origin{ .cmd = .Diff })) return null; - const arg = o.arg(); - if (arg.len > 0 and arg[0] == '/') return arg; - return std.Io.Dir.path.join(p.scratch.allocator(), &.{ std.Io.Dir.path.dirname(f.path) orelse "", arg }) catch null; -} - pub fn openJumps(p: *Pardes, id: usize) !void { var out: std.Io.Writer.Allocating = .init(p.gpa); errdefer out.deinit(); diff --git a/src/Plumb.zig b/src/Plumb.zig new file mode 100644 index 00000000..57a19b14 --- /dev/null +++ b/src/Plumb.zig @@ -0,0 +1,1241 @@ +//! The plumber (Plan 9's plumber(4), windows/plumb/): the rules, and a +//! message matched against them and sent where they say. The language is +//! plumb(6)'s as rules.c and match.c read it, and its refusals are their +//! words; docs/next-plumber.md is the design. The rules are kept as their +//! text, a step's state as any other (digested, dumped, replicated), and +//! parsed again for each message: a send reads no file, and asks the disk +//! only at `isfile` and `isdir`, through the taped resolve sites Look uses. +const Plumb = @This(); +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; +const Pardes = pardes.Pardes; + +/// The rules in force once any were written, as plumb/rules reads them: +/// what `print` makes of them, an include's text in its place, in the +/// order they were written. +text: std.ArrayList(u8) = .empty, +/// Whether rules were written (or cleared): until then the rules in force +/// are `include basic`'s, so a session starts with the defaults, and so +/// does a dump made before the plumber. +written: bool = false, + +/// The default rules, which `include basic` names, as Plan 9's names +/// /lib/plumb/basic. +pub const basic = @embedFile("plumbing"); + +/// The most rule text kept (Plan 9's whole basic is about 4 KiB), variables +/// and ports, as Plan 9's NDIR less its fixed files; deeper includes, as +/// rules.c's pushinput. +pub const max_text = 64 * 1024; +const max_vars = 32; +const max_ports = 32; +const max_depth = 10; + +/// fsys.c's and match.c's words for a message that went nowhere. +pub const e_bad_msg = "bad plumb message format"; +pub const e_no_port = "couldn't find destination for message"; +pub const e_no_start = "no start action for plumb message"; +pub const e_client = "no port for \"client\" rule"; +pub const e_empty = "empty argument list"; + +pub fn deinit(pl: *Plumb, gpa: std.mem.Allocator) void { + pl.text.deinit(gpa); +} + +// ---- the message ---- + +/// A plumb message (plumb.h, plumb(6)): six lines of header, then `data`. +pub const Msg = struct { + src: []const u8 = "", + dst: []const u8 = "", + wdir: []const u8 = "", + type: []const u8 = "", + /// `name=value` pairs, blank-separated, as they are packed: a value + /// holding a blank, a quote, `=` or a tab quoted rc's way. + attr: []const u8 = "", + data: []const u8 = "", + + /// plumbpack: the header lines, the data's length, the data. + pub fn pack(m: Msg, w: *std.Io.Writer) std.Io.Writer.Error!void { + try w.print("{s}\n{s}\n{s}\n{s}\n{s}\n{d}\n{s}", .{ m.src, m.dst, m.wdir, m.type, m.attr, m.data.len, m.data }); + } +}; + +/// plumbunpackpartial: a whole message, `more` bytes of its data still to +/// come, or one malformed (a header line short, a count the data passes). +pub const Unpacked = union(enum) { msg: Msg, more: usize, bad }; + +pub fn unpack(bytes: []const u8) Unpacked { + var lines: [6][]const u8 = undefined; + var at: usize = 0; + for (&lines) |*line| { + const nl = std.mem.indexOfScalarPos(u8, bytes, at, '\n') orelse return .bad; + line.* = bytes[at..nl]; + at = nl + 1; + } + // atoi's: digits after blanks, else 0. + const count = std.mem.trimStart(u8, lines[5], " \t"); + var n: usize = 0; + for (count) |c| { + if (c < '0' or c > '9') break; + n = std.math.mul(usize, n, 10) catch return .bad; + n = std.math.add(usize, n, c - '0') catch return .bad; + } + const rest = bytes.len - at; + if (n > rest) return .{ .more = n - rest }; + if (n < rest) return .bad; + return .{ .msg = .{ .src = lines[0], .dst = lines[1], .wdir = lines[2], .type = lines[3], .attr = lines[4], .data = bytes[at..] } }; +} + +/// One `name=value` of packed attributes, its value unquoted. +const Attr = struct { name: []const u8, value: []const u8 }; + +/// The attribute at `at.*` in `attr`, read as plumbunpackattr reads it, +/// its value unquoted into `buf`; null at their end, or at one with no +/// `=`, where Plan 9 stops. +fn nextAttr(attr: []const u8, at: *usize, buf: *[4096]u8) ?Attr { + var i = at.*; + while (i < attr.len and (attr[i] == ' ' or attr[i] == '\t')) i += 1; + if (i >= attr.len or attr[i] == '\n') return null; + const start = i; + while (i < attr.len and attr[i] != '=' and attr[i] != ' ' and attr[i] != '\t' and attr[i] != '\n') i += 1; + if (i >= attr.len or attr[i] != '=') return null; + const name = attr[start..i]; + i += 1; + var n: usize = 0; + var quoting = false; + while (i < attr.len and attr[i] != '\n' and n < buf.len) { + const c = attr[i]; + i += 1; + if (c == '\'') { + if (!quoting) { + quoting = true; + continue; + } + if (i < attr.len and attr[i] == '\'') { + i += 1; + } else { + quoting = false; + continue; + } + } else if (!quoting and (c == ' ' or c == '\t')) break; + buf[n] = c; + n += 1; + } + at.* = i; + return .{ .name = name, .value = buf[0..n] }; +} + +/// plumblookup: the first attribute named `name`'s value. +fn attrValue(attr: []const u8, name: []const u8, buf: *[4096]u8) ?[]const u8 { + var at: usize = 0; + while (nextAttr(attr, &at, buf)) |a| if (std.mem.eql(u8, a.name, name)) return a.value; + return null; +} + +/// `attr` packed again (plumbpackattr): the first attribute named `drop` +/// left out (plumbdelattr), those of `add` after it (plumbaddattr). +fn repack(arena: std.mem.Allocator, attr: []const u8, drop: ?[]const u8, add: []const u8) error{OutOfMemory}![]const u8 { + var out: std.Io.Writer.Allocating = .init(arena); + var dropped = drop == null; + var buf: [4096]u8 = undefined; + for ([2][]const u8{ attr, add }) |from| { + var at: usize = 0; + while (nextAttr(from, &at, &buf)) |a| { + if (!dropped and std.mem.eql(u8, a.name, drop.?)) { + dropped = true; + continue; + } + const w = &out.writer; + if (out.written().len > 0) w.writeByte(' ') catch return error.OutOfMemory; + w.print("{s}=", .{a.name}) catch return error.OutOfMemory; + // mesg.c's quote: a value with a blank, a quote, `=` or a tab. + if (std.mem.indexOfAny(u8, a.value, " '=\t") == null) { + w.writeAll(a.value) catch return error.OutOfMemory; + continue; + } + w.writeByte('\'') catch return error.OutOfMemory; + for (a.value) |c| { + if (c == '\'') w.writeByte('\'') catch return error.OutOfMemory; + w.writeByte(c) catch return error.OutOfMemory; + } + w.writeByte('\'') catch return error.OutOfMemory; + } + } + return out.written(); +} + +// ---- the rules ---- + +/// rules.c's objects and verbs, in its order (`kind` is an old `type`). +const Obj = enum { arg, attr, data, dst, plumb, src, type, wdir }; +const Verb = enum { add, client, delete, is, isdir, isfile, matches, set, start, to }; + +/// A line `object verb arg`: `qarg` is `arg` expanded with the variables +/// alone, its first word, as rules.c's parserule keeps it. +const Rule = struct { obj: Obj, verb: Verb, arg: []const u8, qarg: []const u8 }; +const Set = struct { pats: []const Rule, acts: []const Rule, port: ?[]const u8 }; +const Var = struct { name: []const u8, value: []const u8, qvalue: []const u8 }; + +/// The rules as read, each item where it was written: printed back in +/// that order, a variable given again later means what it meant to the +/// rules between (Plan 9's printrules puts every variable first). +const Rules = struct { + items: std.ArrayList(union(enum) { variable: Var, ports: []const Rule, set: Set }) = .empty, + vars: std.ArrayList(Var) = .empty, + /// Every port a rule set or a declaration names, once, in order. + ports: std.ArrayList([]const u8) = .empty, + + fn print(r: *const Rules, w: *std.Io.Writer) std.Io.Writer.Error!void { + for (r.items.items) |item| switch (item) { + .variable => |v| try w.print("{s}={s}\n\n", .{ v.name, v.value }), + .ports => |acts| { + for (acts) |a| try printRule(w, a); + try w.writeByte('\n'); + }, + .set => |set| { + for (set.pats) |a| try printRule(w, a); + for (set.acts) |a| try printRule(w, a); + try w.writeByte('\n'); + }, + }; + } + + fn printRule(w: *std.Io.Writer, r: Rule) std.Io.Writer.Error!void { + try w.print("{s}\t{s}\t{s}\n", .{ @tagName(r.obj), @tagName(r.verb), r.arg }); + } + + fn named(r: *const Rules, port: []const u8) bool { + for (r.ports.items) |n| if (std.mem.eql(u8, n, port)) return true; + return false; + } +}; + +/// What a message is matched with, beside the rules: the message, and what +/// the rule set's patterns found so far (match.c's Exec). +const Exec = struct { + m: *Msg, + /// The last `data matches`'s match, `$0`. + match0: []const u8 = "", + /// The span a click match took, which every other `data matches` of + /// the set must take too. + span: ?[2]usize = null, + clearclick: bool = false, + setdata: bool = false, + /// What `isfile` and `isdir` found: `$file`, `$dir`. + file: ?[]const u8 = null, + dir: ?[]const u8 = null, +}; + +/// rules.c's expand: the first word of `s` (a blank outside quotes ends +/// it), quotes rc's (`'...'`, `''` a quote), `$name` a variable's value, +/// with a message the message's (`$data`, `$0`, `$file`, ...); a `$` that +/// names nothing stays. Past `out` (Plan 9's 4 KiB ebuf), `TooLong`. +/// Answers the word and how much of `s` it took. +fn expand(r: *const Rules, e: ?*const Exec, s: []const u8, out: *[4096]u8) error{TooLong}!struct { []const u8, usize } { + var w = std.Io.Writer.fixed(out); + var i: usize = 0; + var quoting = false; + while (i < s.len and (quoting or (s[i] != ' ' and s[i] != '\t'))) { + if (s[i] == '\'') { + i += 1; + if (!quoting) { + quoting = true; + } else if (i < s.len and s[i] == '\'') { + w.writeByte('\'') catch return error.TooLong; + i += 1; + } else quoting = false; + continue; + } + if (quoting or s[i] != '$') { + w.writeByte(s[i]) catch return error.TooLong; + i += 1; + continue; + } + i += 1; + const took = dollar(r, e, s[i..], &w) catch return error.TooLong; + if (took) |n| i += n else w.writeByte('$') catch return error.TooLong; + } + return .{ w.buffered(), i }; +} + +/// rules.c's dollar: the value `$` then `s` names, written to `w`; how +/// much of `s` its name took, or null when it names nothing. +fn dollar(r: *const Rules, e: ?*const Exec, s: []const u8, w: *std.Io.Writer) std.Io.Writer.Error!?usize { + if (e) |x| if (s.len > 0 and std.ascii.isDigit(s[0])) { + // `$1`-`$9` were refused at parse (no submatches): `$0` alone. + if (s[0] == '0') try w.writeAll(x.match0); + return 1; + }; + var n: usize = 0; + while (n < s.len and std.ascii.isAlphanumeric(s[n])) n += 1; + const name = s[0..n]; + if (e) |x| { + const m = x.m; + const field: ?[]const u8 = if (std.mem.eql(u8, name, "src")) m.src else if (std.mem.eql(u8, name, "dst")) m.dst else if (std.mem.eql(u8, name, "attr")) m.attr else if (std.mem.eql(u8, name, "data")) m.data else if (std.mem.eql(u8, name, "type")) m.type else if (std.mem.eql(u8, name, "wdir")) m.wdir else null; + if (field) |f| { + try w.writeAll(f); + return n; + } + // rules.c's filename: what isfile or isdir found, else the data + // made absolute in wdir. + const found = if (std.mem.eql(u8, name, "file")) x.file else if (std.mem.eql(u8, name, "dir")) x.dir else null; + if (found != null or std.mem.eql(u8, name, "file") or std.mem.eql(u8, name, "dir")) { + if (found) |f| { + try w.writeAll(f); + } else if ((m.data.len > 0 and m.data[0] == '/') or m.wdir.len == 0) { + try w.writeAll(m.data); + } else try w.print("{s}/{s}", .{ m.wdir, m.data }); + return n; + } + } + for (r.vars.items) |v| if (std.mem.eql(u8, v.name, name)) { + try w.writeAll(v.qvalue); + return n; + }; + return null; +} + +/// Reads rule text into `rules` (rules.c's readrules): line by line, a +/// blank line (or a comment, or a variable) ending a rule set, an include +/// read in its place. A refusal is `why`: `<file>:<line>: <rules.c's words>`. +const Parser = struct { + arena: std.mem.Allocator, + /// Where an include is read from: none, only `basic`. + p: ?*Pardes, + /// Rules written, not the ones in force read again: their patterns + /// compiled and their bounds counted. + check: bool, + rules: Rules = .{}, + pats: std.ArrayList(Rule) = .empty, + acts: std.ArrayList(Rule) = .empty, + port: ?[]const u8 = null, + commands: usize = 0, + file: []const u8 = "", + line: usize = 0, + depth: usize = 0, + why: []const u8 = "", + + const Error = error{ Parse, OutOfMemory }; + + fn fail(ps: *Parser, comptime fmt: []const u8, args: anytype) Error { + ps.why = try std.fmt.allocPrint(ps.arena, "{s}:{d}: " ++ fmt, .{ ps.file, ps.line } ++ args); + return error.Parse; + } + + fn feed(ps: *Parser, name: []const u8, text: []const u8) Error!void { + ps.file = name; + ps.line = 0; + const whole = if (std.mem.endsWith(u8, text, "\n")) text[0 .. text.len - 1] else text; + var lines = std.mem.splitScalar(u8, whole, '\n'); + while (lines.next()) |line| { + ps.line += 1; + try ps.take(line); + } + } + + /// The text read, ended as its end ends a rule set. + fn finish(ps: *Parser) Error!void { + try ps.endSet(); + } + + /// rules.c's readrule, for one line. + fn take(ps: *Parser, raw: []const u8) Error!void { + const l = std.mem.trimStart(u8, raw, " \t"); + if (l.len == 0 or l[0] == '#') return ps.endSet(); + if (std.mem.startsWith(u8, l, "include")) return ps.include(l); + if (try ps.assignment(l)) return; + const obj_end = std.mem.indexOfAny(u8, l, " \t") orelse return ps.fail("malformed rule", .{}); + const obj_word = l[0..obj_end]; + const obj = std.meta.stringToEnum(Obj, obj_word) orelse + if (std.mem.eql(u8, obj_word, "kind")) .type else return ps.fail("unknown object {s}", .{obj_word}); + const rest = std.mem.trimStart(u8, l[obj_end..], " \t"); + const verb_end = std.mem.indexOfAny(u8, rest, " \t") orelse return ps.fail("malformed rule", .{}); + const verb = std.meta.stringToEnum(Verb, rest[0..verb_end]) orelse return ps.fail("unknown verb {s}", .{rest[0..verb_end]}); + const arg = std.mem.trimStart(u8, rest[verb_end..], " \t"); + if (arg.len == 0) return ps.fail("malformed rule", .{}); + // parserule. + const action = verb == .client or verb == .start or verb == .to; + if ((obj == .plumb) != action or (obj != .attr and (verb == .add or verb == .delete))) + return ps.fail("{s} not valid verb for object {s}", .{ @tagName(verb), @tagName(obj) }); + // pardes's regular expressions have no capture groups (regexp.zig, + // mvzr), and the user chose never to have an engine of pardes's + // own: a submatch is refused, never silently empty. + var quoting = false; + for (arg, 0..) |c, i| { + if (c == '\'') quoting = !quoting; + if (!quoting and c == '$' and i + 1 < arg.len and arg[i + 1] >= '1' and arg[i + 1] <= '9') + return ps.fail("${c}: no submatches (the regular expressions have no capture groups): use $0 and several matches", .{arg[i + 1]}); + } + const r: Rule = .{ .obj = obj, .verb = verb, .arg = arg, .qarg = try ps.word(arg) }; + if (verb == .matches and ps.check) { + var pat: [4096 + 4]u8 = undefined; + _ = Regex.compile(anchored(r.qarg, &pat)) catch |err| return ps.fail("{s}", .{Regex.message(err)}); + } + if (obj != .plumb) return ps.pats.append(ps.arena, r); + try ps.acts.append(ps.arena, r); + if (verb != .to) { + ps.commands += 1; + return; + } + // readruleset's: a declaration names many, a rule set one. + if (ps.pats.items.len > 0 and ps.port != null) return ps.fail("too many ports", .{}); + for ([_][]const u8{ ".", "..", "send", "rules" }) |bad| if (std.mem.eql(u8, r.qarg, bad)) + return ps.fail("illegal port name {s}", .{r.qarg}); + ps.port = r.qarg; + } + + /// readruleset's end: a rule set kept, ports declared, or a refusal. + fn endSet(ps: *Parser) Error!void { + const pats = ps.pats.items; + const acts = ps.acts.items; + const port = ps.port; + const commands = ps.commands; + ps.pats = .empty; + ps.acts = .empty; + ps.port = null; + ps.commands = 0; + if (commands > 1) return ps.fail("ruleset has more than one client or start action", .{}); + if (pats.len == 0 and acts.len == 0) return; + if (pats.len > 0 and acts.len > 0) { + try ps.rules.items.append(ps.arena, .{ .set = .{ .pats = pats, .acts = acts, .port = port } }); + } else { + if (acts.len == 0 or port == null) return ps.fail("ruleset must have patterns and actions", .{}); + for (acts) |a| if (a.verb != .to) return ps.fail("ruleset must have actions", .{}); + try ps.rules.items.append(ps.arena, .{ .ports = acts }); + } + for (acts) |a| if (a.verb == .to and !ps.rules.named(a.qarg)) { + if (ps.check and ps.rules.ports.items.len >= max_ports) return ps.fail("too many ports; max {d}", .{max_ports}); + try ps.rules.ports.append(ps.arena, a.qarg); + }; + } + + /// `s`'s first word expanded with the variables: a slice of `s` when + /// that changes nothing (no quote, no `$`), as in most rules. What a + /// parse keeps slices the text it read, which outlives it (the rules in + /// force, a write's, an include read into the arena, src/plumbing). + fn word(ps: *Parser, s: []const u8) Error![]const u8 { + var buf: [4096]u8 = undefined; + const w, const took = expand(&ps.rules, null, s, &buf) catch return ps.fail("string-too-long", .{}); + return if (std.mem.eql(u8, w, s[0..took])) s[0..took] else ps.arena.dupe(u8, w); + } + + /// rules.c's assignment: `name=value`, its value expanded once, now; + /// it ends a rule set as a blank line does. + fn assignment(ps: *Parser, l: []const u8) Error!bool { + if (!std.ascii.isAlphabetic(l[0])) return false; + var i: usize = 0; + while (i < l.len and std.ascii.isAlphanumeric(l[i])) i += 1; + const name = l[0..i]; + while (i < l.len and (l[i] == ' ' or l[i] == '\t')) i += 1; + if (i >= l.len or l[i] != '=') return false; + try ps.endSet(); + const value = std.mem.trimStart(u8, l[i + 1 ..], " \t"); + const v: Var = .{ .name = name, .value = value, .qvalue = try ps.word(value) }; + try ps.rules.items.append(ps.arena, .{ .variable = v }); + for (ps.rules.vars.items) |*old| if (std.mem.eql(u8, old.name, name)) { + old.* = v; + return true; + }; + if (ps.check and ps.rules.vars.items.len >= max_vars) return ps.fail("too many variables; max {d}", .{max_vars}); + try ps.rules.vars.append(ps.arena, v); + return true; + } + + /// rules.c's include: `include basic` is src/plumbing; another name + /// the configuration directory's file, an absolute one where it says. + fn include(ps: *Parser, l: []const u8) Error!void { + var words = std.mem.tokenizeAny(u8, l, " \t"); + const first = words.next().?; + const name = words.next() orelse ""; + const third = words.next(); + if (!std.mem.eql(u8, first, "include") or name.len == 0 or name[0] == '#' or (third != null and third.?[0] != '#')) + return ps.fail("malformed include statement", .{}); + if (ps.depth >= max_depth) return ps.fail("include stack too deep; max {d}", .{max_depth}); + const text = if (std.mem.eql(u8, name, "basic")) basic else text: { + var buf: [4096]u8 = undefined; + const p = ps.p orelse return ps.fail("can't open {s} for inclusion", .{name}); + const path = if (name[0] == '/') name else std.fmt.bufPrint(&buf, "{s}/{s}", .{ p.configDir() orelse "", name }) catch name; + break :text fs.readFile(ps.arena, path) catch return ps.fail("can't open {s} for inclusion", .{path}); + }; + const file = ps.file; + const line = ps.line; + ps.depth += 1; + try ps.feed(name, text); + ps.depth -= 1; + ps.file = file; + ps.line = line; + } +}; + +/// `pat` matching only the whole of what it is run over: `^(pat)$` (its +/// own anchors dropped, mvzr taking `^` only first), in `out`. +fn anchored(pat: []const u8, out: *[4096 + 4]u8) []const u8 { + var core = pat; + if (core.len > 0 and core[0] == '^') core = core[1..]; + if (core.len > 1 and core[core.len - 1] == '$' and core[core.len - 2] != '\\') core = core[0 .. core.len - 1]; + return std.fmt.bufPrint(out, "^({s})$", .{core}) catch pat; +} + +/// The rules in force as text to read again. +fn source(p: *Pardes) []const u8 { + return if (p.plumber.written) p.plumber.text.items else "include basic\n"; +} + +/// The rules in force read, for a send. +fn rulesOf(p: *Pardes, arena: std.mem.Allocator) Parser.Error!Rules { + var ps: Parser = .{ .arena = arena, .p = p, .check = false }; + try ps.feed("plumb/rules", source(p)); + try ps.finish(); + return ps.rules; +} + +/// The rules in force as plumb/rules reads them, the defaults printed +/// (in the step's scratch) while none were written. +pub fn inForce(p: *Pardes) []const u8 { + if (p.plumber.written) return p.plumber.text.items; + const arena = p.scratch.allocator(); + const rules = rulesOf(p, arena) catch return ""; + var out: std.Io.Writer.Allocating = .init(arena); + rules.print(&out.writer) catch return ""; + return out.written(); +} + +/// 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 { + const arena = p.scratch.allocator(); + var ps: Parser = .{ .arena = arena, .p = p, .check = true }; + const said = said: { + if (keep) { + 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.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"; + if (out.written().len > max_text) break :said std.fmt.comptimePrint("rules too long; max {d} KiB", .{max_text / 1024}); + p.plumber.text.clearRetainingCapacity(); + p.plumber.text.appendSlice(p.gpa, out.written()) catch break :said "out of memory"; + p.plumber.written = true; + return null; + }; + return if (said.len > 0) said else "out of memory"; +} + +// ---- matching ---- + +/// One message's match (fsys.c's write of `send` through dispose): the +/// rules, and what the disk said of a name, asked once however many rules +/// ask it. +const Send = struct { + p: *Pardes, + /// The pane a look sent from, whose jump list's directories a name is + /// looked for in too; none from plumb/send. + from: ?usize, + arena: std.mem.Allocator, + rules: Rules, + memo_name: ?[]const u8 = null, + memo_wdir: []const u8 = "", + memo: ?fs.Resolved = null, + memo_buf: [4096]u8 = undefined, + + /// Where a name is, as Look finds it: the place written after it + /// (`:12`, `:12:5`) no part of it, then the message's directory, the + /// jump list's panes' (from a look), then Incl's (look.zig's + /// resolveLookTarget). Each stat is a taped resolve site; a name is + /// asked once a send. + fn resolve(s: *Send, wdir: []const u8, raw: []const u8) ?fs.Resolved { + const name = look.parsePathLine(std.mem.trim(u8, raw, " \t\r\n")).path; + if (s.memo_name) |n| if (std.mem.eql(u8, n, name) and std.mem.eql(u8, s.memo_wdir, wdir)) return s.memo; + s.memo_name = s.arena.dupe(u8, name) catch return null; + s.memo_wdir = s.arena.dupe(u8, wdir) catch return null; + s.memo = s.search(wdir, name); + return s.memo; + } + + 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; + } + } + for (s.p.incl.items) |dir| if (fs.resolve(s.p, name, dir, &s.memo_buf)) |found| return found; + return null; + } + + /// match.c's matchruleset: the message tried against `set`, rewritten + /// in place by its patterns (a `set` stays though a later one fails). + fn matchSet(s: *Send, set: Set, e: *Exec) error{OutOfMemory}!bool { + const m = e.m; + if (m.dst.len > 0 and set.port != null and !std.mem.eql(u8, m.dst, set.port.?)) return false; + for (set.pats) |r| if (!try s.pattern(e, r)) return false; + if (set.port) |port| if (m.dst.len == 0) { + m.dst = port; + }; + // match.c's rewrite: a click match's span is the data now. + if (e.clearclick) { + m.attr = try repack(s.arena, m.attr, "click", ""); + if (e.setdata) m.data = e.match0; + } + return true; + } + + /// match.c's matchpat. + fn pattern(s: *Send, e: *Exec, r: Rule) error{OutOfMemory}!bool { + const m = e.m; + const field: ?*[]const u8 = switch (r.obj) { + .data => &m.data, + .dst => &m.dst, + .type => &m.type, + .wdir => &m.wdir, + .src => &m.src, + .arg, .attr, .plumb => null, + }; + var buf: [4096]u8 = undefined; + switch (r.verb) { + .is => return if (field) |f| std.mem.eql(u8, f.*, r.qarg) else false, + .set => { + const f = field orelse return true; + const value = (expand(&s.rules, e, r.arg, &buf) catch return false)[0]; + f.* = try s.arena.dupe(u8, value); + if (r.obj == .data) { + e.span = null; + e.setdata = false; + } + return true; + }, + .add, .delete => { + if (r.obj != .attr) return false; + const value = (expand(&s.rules, e, r.arg, &buf) catch return false)[0]; + if (r.verb == .add) { + m.attr = try repack(s.arena, m.attr, null, value); + return true; + } + // The code's, not the man page's: an absent one fails. + var vbuf: [4096]u8 = undefined; + if (attrValue(m.attr, value, &vbuf) == null) return false; + m.attr = try repack(s.arena, m.attr, value, ""); + return true; + }, + .isfile, .isdir => { + const name = switch (r.obj) { + .arg => (expand(&s.rules, e, r.arg, &buf) catch return false)[0], + .data => m.data, + .wdir => m.wdir, + else => return false, + }; + const found = s.resolve(m.wdir, name) orelse return false; + if (found.dir != (r.verb == .isdir)) return false; + const path = try s.arena.dupe(u8, found.path); + if (r.verb == .isdir) e.dir = path else e.file = path; + return true; + }, + .matches => { + const text = (field orelse return false).*; + var pat: [4096 + 4]u8 = undefined; + var click_buf: [4096]u8 = undefined; + const click = if (r.obj == .data) attrValue(m.attr, "click", &click_buf) else null; + if (click == null) { + // The whole of it, as match.c asks of regexec's answer. + var rx = Regex.compile(anchored(r.qarg, &pat)) catch return false; + const hit = (rx.find(text, 0, 0, text.len) catch return false) orelse return false; + if (hit.start != 0 or hit.end != text.len) return false; + e.match0 = text; + return true; + } + // clickmatch: the first match from each start up to the + // click that holds it, the click counted in runes. + const runes = std.fmt.parseInt(usize, std.mem.trim(u8, click.?, " \t"), 10) catch 0; + var at: usize = 0; + var n: usize = 0; + while (n < runes and at < text.len) : (n += 1) at += std.unicode.utf8ByteSequenceLength(text[at]) catch 1; + at = @min(at, text.len); + var rx = Regex.compile(r.qarg) catch return false; + var from: usize = 0; + const hit = while (from <= at) { + const h = (rx.find(text, from, at, text.len) catch return false) orelse return false; + if (h.start <= at and at <= h.end) break h; + // Every start before the next match finds this one. + from = h.start + 1; + while (from < text.len and text[from] & 0xC0 == 0x80) from += 1; + } else return false; + if (e.span) |sp| if (sp[0] != hit.start or sp[1] != hit.end) return false; + e.span = .{ hit.start, hit.end }; + e.clearclick = true; + e.setdata = true; + e.match0 = text[hit.start..hit.end]; + return true; + }, + .client, .start, .to => return false, + } + } +}; + +/// The ports pardes reads itself, as acme reads `edit`; and every loaded +/// kind by its name. +const Port = enum { + /// A file or directory opened as Look opens one, at the place written + /// after its name or given as `addr=`. + edit, + /// A URL given to the host's browser (xdg-open, open on macOS). + web, +}; + +/// 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 { + 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 m = msg; + var e: Exec = .{ .m = &m }; + const set: ?Set = for (s.rules.items.items) |item| { + const candidate = switch (item) { + .set => |x| x, + else => continue, + }; + e = .{ .m = &m }; + if (s.matchSet(candidate, &e) catch return "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 (p.kinds.byName(m.dst)) |k| { + openInKind(&s, id, k, &m); + return null; + } + // 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); +} + +/// 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 { + 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; + break a; + } + } else return e_no_start; + // buildargv: one expansion a word. + var argv: std.ArrayList([]const u8) = .empty; + var rest = act.arg; + while (true) { + 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"; + rest = rest[took..]; + } + if (argv.items.len == 0) return e_empty; + run(s.p, id, e.m.wdir, argv.items); + return null; +} + +/// 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 { + 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()); +} + +/// 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 { + 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) }); + }, + .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 ""; + 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); + look.lookAt(p, id, text); + }, + } +} + +/// A message to a loaded kind's port: its data, a file, opened in that kind +/// (or its pane given the keyboard, when one shows it). +fn openInKind(s: *Send, id: usize, k: u8, m: *const Msg) void { + const p = s.p; + const found = s.resolve(m.wdir, m.data) orelse return p.reportFailure(id, "plumb: no such file"); + if (found.dir) return p.reportFailure(id, "plumb: a directory is no kind's"); + const path = s.arena.dupe(u8, found.path) catch return; + for (p.panes, 0..) |slot, i| if (slot) |pn| if (pn.addon) |a| if (std.mem.eql(u8, a.path, path)) { + p.view().active = i; + return; + }; + const free = p.freeSlot() orelse return p.reportError(id, "plumb", error.NoPaneSlots); + const made = Kind.openFile(p, free, k, path) catch |err| return p.reportError(id, path, err); + if (made.addon.?.refused.len > 0) { + made.vweight = 0; + p.unplaced.set(free); + return p.reportFailure(id, s.arena.dupe(u8, made.addon.?.refused.slice()) catch "plumb: refused"); + } + layout.placeNew(p, id, id, free, .doc); +} + +/// Where rule text written in pieces is whole: through its last blank line +/// (rules.c's morerules), 0 when none is. +pub fn wholeSets(text: []const u8) usize { + return if (std.mem.lastIndexOf(u8, text, "\n\n")) |at| at + 2 else 0; +} + +// ---- tests ---- + +const testing = std.testing; + +/// The rules `text` read as written ones are, printed; or the refusal. +fn reread(arena: std.mem.Allocator, text: []const u8) ![]const u8 { + var ps: Parser = .{ .arena = arena, .p = null, .check = true }; + ps.feed("t", text) catch return ps.why; + ps.finish() catch return ps.why; + var out: std.Io.Writer.Allocating = .init(arena); + try ps.rules.print(&out.writer); + return out.written(); +} + +test "plumb: a message packs as plumb(6)'s six lines and its data, and unpacks whole, short of its data, or malformed" { + var buf: [256]u8 = undefined; + var w = std.Io.Writer.fixed(&buf); + const m: Msg = .{ .src = "pardes", .wdir = "/tmp", .type = "text", .attr = "click=3 addr=12", .data = "a b\nc" }; + try m.pack(&w); + try testing.expectEqualStrings("pardes\n\n/tmp\ntext\nclick=3 addr=12\n5\na b\nc", w.buffered()); + const back = unpack(w.buffered()).msg; + inline for (.{ "src", "dst", "wdir", "type", "attr", "data" }) |f| try testing.expectEqualStrings(@field(m, f), @field(back, f)); + try testing.expectEqual(@as(usize, 2), unpack(w.buffered()[0 .. w.buffered().len - 2]).more); + // A header line short is no message at all, as is data past its count. + try testing.expect(unpack("pardes\n\n/tmp\ntext\n") == .bad); + try testing.expect(unpack("a\nb\nc\nd\ne\n1\nxy") == .bad); + try testing.expect(unpack("a\nb\nc\nd\ne\nzz\n") == .msg); +} + +test "plumb: attributes read rc's quotes, a value that needs them is quoted again, delete takes the first, add appends" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var buf: [4096]u8 = undefined; + const attr = "action=showdata filename='/a b/it''s' click=4"; + try testing.expectEqualStrings("/a b/it's", attrValue(attr, "filename", &buf).?); + try testing.expectEqualStrings("4", attrValue(attr, "click", &buf).?); + try testing.expect(attrValue(attr, "addr", &buf) == null); + try testing.expectEqualStrings("action=showdata filename='/a b/it''s'", try repack(a, attr, "click", "")); + try testing.expectEqualStrings("action=showdata filename='/a b/it''s' click=4 addr='x=1'", try repack(a, attr, null, "addr='x=1'")); + // One with no `=` ends them, as plumbunpackattr stops there. + try testing.expect(attrValue("a=1 bogus b=2", "b", &buf) == null); +} + +test "plumb: every parse error in rules.c's words, with its line" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + for ([_][2][]const u8{ + .{ "type is text\nbogus\n", "t:2: malformed rule" }, + .{ "type is\n", "t:1: malformed rule" }, + .{ "type \n", "t:1: malformed rule" }, + .{ "colour is red\n", "t:1: unknown object colour" }, + .{ "type equals text\n", "t:1: unknown verb equals" }, + .{ "data to edit\n", "t:1: to not valid verb for object data" }, + .{ "type start x\n", "t:1: start not valid verb for object type" }, + .{ "data add x=1\n", "t:1: add not valid verb for object data" }, + .{ "plumb is edit\n", "t:1: is not valid verb for object plumb" }, + .{ "type is text\nplumb to a\nplumb to b\n", "t:3: too many ports" }, + .{ "type is text\nplumb to send\n", "t:2: illegal port name send" }, + .{ "plumb to ..\n", "t:1: illegal port name .." }, + .{ "plumb to rules\n", "t:1: illegal port name rules" }, + .{ "type is text\nplumb start a\nplumb client b\n", "t:3: ruleset has more than one client or start action" }, + .{ "type is text\n\n", "t:2: ruleset must have patterns and actions" }, + .{ "plumb start x\n", "t:1: ruleset must have patterns and actions" }, + .{ "plumb to a\nplumb start x\n\n", "t:3: ruleset must have actions" }, + .{ "include\n", "t:1: malformed include statement" }, + .{ "include a b\n", "t:1: malformed include statement" }, + .{ "includes x\n", "t:1: malformed include statement" }, + .{ "include nowhere\n", "t:1: can't open nowhere for inclusion" }, + .{ "data matches '[a-'\nplumb to edit\n", "t:1: bad regular expression" }, + .{ "data matches '([a-z]+)\\.c'\narg isfile $1\nplumb to edit\n", "t:2: $1: no submatches (the regular expressions have no capture groups): use $0 and several matches" }, + }) |c| try testing.expectEqualStrings(c[1], try reread(a, c[0])); + // Inside quotes a `$1` is the text `$1`. + try testing.expectEqualStrings("data\tis\t'$1'\nplumb\tto\tedit\n\n", try reread(a, "data is '$1'\nplumb to edit\n")); + // The most variables, and ports, are bounded. + var many: std.Io.Writer.Allocating = .init(a); + for (0..max_vars + 1) |i| try many.writer.print("v{d}=x\n", .{i}); + try testing.expectEqualStrings("t:33: too many variables; max 32", try reread(a, many.written())); + many.clearRetainingCapacity(); + for (0..max_ports + 1) |i| try many.writer.print("plumb to p{d}\n", .{i}); + try testing.expectEqualStrings("t:33: too many ports; max 32", try reread(a, many.written())); +} + +test "plumb: rules print as rule sets of tab-separated lines, variables where they were set, and read back the same" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const text = + \\# a comment ends nothing it is not in + \\x = '[a-z]+' + \\plumb to seemail + \\plumb to showmail + \\ + \\kind is text + \\data matches $x + \\plumb to edit + \\x=other + \\type is text + \\data set $x + \\plumb start Msg $data + ; + const printed = try reread(a, text); + try testing.expectEqualStrings("x='[a-z]+'\n\nplumb\tto\tseemail\nplumb\tto\tshowmail\n\ntype\tis\ttext\ndata\tmatches\t$x\nplumb\tto\tedit\n\nx=other\n\ntype\tis\ttext\ndata\tset\t$x\nplumb\tstart\tMsg $data\n\n", printed); + try testing.expectEqualStrings(printed, try reread(a, printed)); + // The default rules read, and print as they read. + const defaults = try reread(a, "include basic\n"); + try testing.expect(std.mem.indexOf(u8, defaults, "data\tmatches\t'https?://.*'\nplumb\tto\tweb\n") != null); + try testing.expectEqualStrings(defaults, try reread(a, defaults)); +} + +test "plumb: rc's quoting, variables and the message's in an expansion, the first word alone" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + var ps: Parser = .{ .arena = arena.allocator(), .p = null, .check = true }; + try ps.feed("t", "v='a b'\nw=x$v'y'\n"); + var m: Msg = .{ .src = "pardes", .wdir = "/w", .data = "f.c" }; + var e: Exec = .{ .m = &m, .match0 = "zero" }; + var buf: [4096]u8 = undefined; + for ([_][2][]const u8{ + .{ "'it''s' rest", "it's" }, + .{ "pre$v.post", "prea b.post" }, + .{ "$w", "xa by" }, + .{ "'$v'", "$v" }, + .{ "$nothere$", "$nothere$" }, + .{ "$src:$wdir:$data:$0:$file", "pardes:/w:f.c:zero:/w/f.c" }, + }) |c| try testing.expectEqualStrings(c[1], (try expand(&ps.rules, &e, c[0], &buf))[0]); + e.file = "/real/f.c"; + try testing.expectEqualStrings("/real/f.c", (try expand(&ps.rules, &e, "$file", &buf))[0]); + // Past 4 KiB: too long, never cut. + const long = try arena.allocator().alloc(u8, 5000); + @memset(long, 'a'); + m.data = long; + try testing.expectError(error.TooLong, expand(&ps.rules, &e, "$data", &buf)); +} + +/// A send against `text`'s rules on a session of its own: the message +/// after its match, the rule set that took it (its index among the sets, +/// null for none) and what dispose said. +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); + const arena = p.scratch.allocator(); + var s: Send = .{ .p = p, .from = null, .arena = arena, .rules = try rulesOf(p, arena) }; + var m = msg; + var e: Exec = .{ .m = &m }; + var n: usize = 0; + for (s.rules.items.items) |item| { + const set = switch (item) { + .set => |x| x, + else => continue, + }; + e = .{ .m = &m }; + if (try s.matchSet(set, &e)) return .{ .m = m, .set = n }; + n += 1; + } + return .{ .m = m, .set = null }; +} + +test "plumb: matches takes the whole text, or with a click the run around it: Pike's horse.gift is no gif" { + const p = try Pardes.init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer p.deinit(); + const rules = + \\type is text + \\data matches '[a-zA-Z0-9_\-./]+' + \\data matches '([a-zA-Z0-9_\-./]+)\.(gif|jpe?g)' + \\plumb to image + \\ + ; + try testing.expectEqual(@as(?usize, 0), (try tryRules(p, rules, .{ .type = "text", .data = "horse.gif" })).set); + try testing.expect((try tryRules(p, rules, .{ .type = "text", .data = "horse.gift" })).set == null); + try testing.expect((try tryRules(p, rules, .{ .type = "text", .data = "see horse.gif" })).set == null); + // A click inside the name: the run of file characters around it, the + // data cut to it and the click gone. + const hit = try tryRules(p, rules, .{ .type = "text", .attr = "click=7", .data = "see horse.gif now" }); + try testing.expectEqual(@as(?usize, 0), hit.set); + try testing.expectEqualStrings("horse.gif", hit.m.data); + try testing.expectEqualStrings("", hit.m.attr); + try testing.expectEqualStrings("image", hit.m.dst); + try testing.expect((try tryRules(p, rules, .{ .type = "text", .attr = "click=7", .data = "see horse.gift now" })).set == null); + // The click counts runes: two bytes of é before it. + try testing.expectEqualStrings("horse.gif", (try tryRules(p, rules, .{ .type = "text", .attr = "click=3", .data = "é horse.gif" })).m.data); + // Each object a rule matches whole. + const src = "src\tmatches\t'par.*'\ntype\tmatches\t'te(x|y)t'\nplumb\tto\tedit\n"; + try testing.expectEqual(@as(?usize, 0), (try tryRules(p, src, .{ .src = "pardes", .type = "text" })).set); + try testing.expect((try tryRules(p, src, .{ .src = "pardes", .type = "texts" })).set == null); + // The default rules' URL: http and https, whole. + try testing.expectEqual(@as(?usize, 0), (try tryRules(p, basic, .{ .type = "text", .data = "https://ziglang.org/x?y" })).set); + try testing.expect((try tryRules(p, basic, .{ .type = "text", .data = "see https://ziglang.org" })).set == null); +} + +test "plumb: a set rewrites the message for good, attr delete of one absent fails, a message to a port tries only rule sets to it" { + const p = try Pardes.init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer p.deinit(); + const rules = + \\data set changed + \\type is never + \\plumb to a + \\ + \\attr delete action + \\attr add 'action=showdiff filename=x' + \\plumb to b + \\ + \\data is changed + \\plumb to c + \\ + ; + // The first set fails after its `set`: the data stays changed; the + // second fails at its delete; the third sees the changed data. + const t = try tryRules(p, rules, .{ .type = "text", .data = "orig" }); + try testing.expectEqual(@as(?usize, 2), t.set); + try testing.expectEqualStrings("changed", t.m.data); + try testing.expectEqualStrings("c", t.m.dst); + const d = try tryRules(p, rules, .{ .type = "text", .attr = "action=showdata", .data = "x" }); + try testing.expectEqual(@as(?usize, 1), d.set); + try testing.expectEqualStrings("action=showdiff filename=x", d.m.attr); + // dst names a port: rule sets to another are passed over. + const to_a = try tryRules(p, "data\tis\tx\nplumb\tto\ta\n\ndata\tis\tx\nplumb\tto\tb\n\n", .{ .dst = "b", .data = "x" }); + try testing.expectEqual(@as(?usize, 1), to_a.set); +} + +test "plumb: isfile and isdir find a name as Look does, past its place, in the message's directory then Incl's; $file is where" { + if (!fs.platform_has_fs) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "it.zig", .data = "x\n" }); + try tmp.dir.createDir(testing.io, "sub", .default_dir); + 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 = 80, .rows = 24 }); + defer p.deinit(); + const rules = "arg\tisfile\t$data\ndata\tset\t$file\nplumb\tto\tedit\n\narg\tisdir\t$data\ndata\tset\t$dir\nplumb\tto\tedit\n\n"; + const file = try tryRules(p, rules, .{ .wdir = root, .data = "it.zig:3:2" }); + try testing.expectEqual(@as(?usize, 0), file.set); + try testing.expect(std.mem.endsWith(u8, file.m.data, "/it.zig")); + const dir = try tryRules(p, rules, .{ .wdir = root, .data = "sub" }); + try testing.expectEqual(@as(?usize, 1), dir.set); + try testing.expect(std.mem.endsWith(u8, dir.m.data, "/sub")); + try testing.expect((try tryRules(p, rules, .{ .wdir = root, .data = "nothere.zig" })).set == null); + // Not in wdir: Incl's directories, as acme's includename. + try p.incl.append(p.gpa, try p.gpa.dupe(u8, root)); + try testing.expectEqual(@as(?usize, 0), (try tryRules(p, rules, .{ .wdir = "/", .data = "it.zig" })).set); + try testing.expect((try tryRules(p, rules, .{ .wdir = "/", .data = "./it.zig" })).set == null); +} + +test "plumb: dispose: no rule and no dst, a start, the web port, a port no rule names" { + 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" }).?); + // A start of a builtin runs it in place. + try testing.expect(send(p, null, .{ .type = "msg", .data = "hello" }) == null); + 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" }).?); + // A port no rule names goes nowhere, said nothing (fsys.c's dispose). + try testing.expect(send(p, null, .{ .dst = "elsewhere", .data = "x" }) == null); + // 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); + var opened = false; + while (p.nextEffect()) |e| switch (e) { + .open_link => |u| { + try testing.expectEqualStrings("https://ziglang.org", u.slice()); + opened = true; + }, + else => {}, + }; + try testing.expect(opened); +} + +test "plumb: rules written replace or add, a refusal keeps them as they were, and a dump keeps them" { + const p = try Pardes.init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer p.deinit(); + // 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.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("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"); + defer restored.deinit(); + try testing.expectEqualStrings(p.plumber.text.items, restored.plumber.text.items); + try testing.expect(restored.plumber.written); +} + +test "plumb: plan9port's basic parses, its ¡- classes UTF-8's bytes and its submatch rule sets left out, and its rules match" { + var arena: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena.deinit(); + // plan9port's plumb/basic and fileaddr; `¡-` is `\x80-\xf4`, the bytes + // of UTF-8's multi-byte runes (a run of them is whole runes: UTF-8 is + // self-synchronising), and the rule sets that need `$1`-`$5` are gone. + const p9p = + \\addrelem='((#?[0-9]+)|(/[A-Za-z0-9_\^]+/?)|[.$])' + \\addr=:($addrelem([,;+\-]$addrelem)*) + \\ + \\plumb to seemail + \\plumb to showmail + \\ + \\type is text + \\data matches '(https?|ftp|file|gopher|mailto|news|nntp|telnet|wais|prospero)://[a-zA-Z0-9_@\-]+([.:][a-zA-Z0-9_@\-]+)*/?[a-zA-Z0-9_?,%#~&/\-+=]+([:.][a-zA-Z0-9_?,%#~&/\-+=]+)*' + \\plumb to web + \\plumb start web $0 + \\ + \\type is text + \\data matches '[a-zA-Z\x80-\xf40-9_\-./]+' + \\data matches '([a-zA-Z\x80-\xf40-9_\-./]+)\.(doc|rtf)' + \\arg isfile $0 + \\plumb to msword + \\plumb start wdoc2txt $file + \\ + \\type is text + \\dst is msword + \\plumb to msword + \\plumb start wdoc2txt $file + \\ + \\type is text + \\data matches '[a-zA-Z\x80-\xf40-9_\-./@]+' + \\data matches '([a-zA-Z\x80-\xf40-9_\-./@]+)\.(jpe?g|JPE?G|gif|GIF|tiff?|TIFF?|ppm|bit|png|PNG)' + \\arg isfile $0 + \\plumb to image + \\plumb start 9 page $file + \\ + \\type is text + \\data matches '[a-zA-Z\x80-\xf40-9_\-./@]+' + \\data matches '([a-zA-Z\x80-\xf40-9_\-./@]+)\.(ps|PS|eps|EPS|pdf|PDF|dvi|DVI)' + \\arg isfile $0 + \\plumb to postscript + \\plumb start 9 page $file + \\ + \\data matches '[a-zA-Z\x80-\xf40-9_\-./@]+' + \\data matches '([a-zA-Z\x80-\xf40-9_\-./@]+)\.([Ss][XxTt][CcDdIiGgMmWw]|[Dd][Oo][Cc]|[Xx][Ll][Ss]|[Pp][Pp][Tt])' + \\arg isfile $0 + \\plumb to openoffice + \\plumb start openoffice $file + \\ + \\type is text + \\data matches '[a-zA-Z\x80-\xf40-9_\-./]+' + \\data matches '/mail/fs/[a-zA-Z\x80-\xf40-9/]+/[0-9]+' + \\plumb to showmail + \\plumb start window -r 4 120 750 600 upas/nedmail -s $0 + \\ + \\type is text + \\data matches '[a-zA-Z0-9_+.\-]+@[a-zA-Z0-9_+.\-]*' + \\plumb to sendmail + \\plumb start wmail $0 + \\ + \\dst is image + \\arg isfile $data + \\plumb to image + \\plumb start 9 page $data + \\ + \\dst is postscript + \\arg isfile $data + \\plumb start 9 page $data + \\ + ; + const printed = try reread(arena.allocator(), p9p); + try testing.expect(std.mem.startsWith(u8, printed, "addrelem='((#?[0-9]+)|(/[A-Za-z0-9_\\^]+/?)|[.$])'\n\naddr=:($addrelem([,;+\\-]$addrelem)*)\n\nplumb\tto\tseemail\n")); + try testing.expectEqualStrings(printed, try reread(arena.allocator(), printed)); + const p = try Pardes.init(testing.allocator, .{ .cols = 80, .rows = 24 }); + defer p.deinit(); + // Clicked in a line: the URL's run, the mail address's, and the + // faces' path, whole runes of a name that is not ASCII. + const url = try tryRules(p, p9p, .{ .type = "text", .attr = "click=10", .data = "see https://9fans.github.io/plan9port/ now" }); + try testing.expectEqual(@as(?usize, 0), url.set); + try testing.expectEqualStrings("https://9fans.github.io/plan9port/", url.m.data); + try testing.expectEqualStrings("web", url.m.dst); + const mail = try tryRules(p, p9p, .{ .type = "text", .attr = "click=12", .data = "write to [email protected]." }); + try testing.expectEqualStrings("sendmail", mail.m.dst); + try testing.expectEqualStrings("[email protected].", mail.m.data); + const face = try tryRules(p, p9p, .{ .type = "text", .attr = "click=3", .data = "x /mail/fs/café/12 y" }); + try testing.expectEqualStrings("showmail", face.m.dst); + try testing.expectEqualStrings("/mail/fs/café/12", face.m.data); + // An image named in UTF-8, and Pike's horse.gift, by the image set's + // two patterns alone. + const pics = "data matches '[a-zA-Z\\x80-\\xf40-9_\\-./@]+'\ndata matches '([a-zA-Z\\x80-\\xf40-9_\\-./@]+)\\.(jpe?g|gif|png)'\nplumb to image\n"; + try testing.expectEqualStrings("Ångström.png", (try tryRules(p, pics, .{ .attr = "click=2", .data = "Ångström.png" })).m.data); + try testing.expect((try tryRules(p, pics, .{ .attr = "click=2", .data = "horse.gift" })).set == null); + // 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")); +} diff --git a/src/Query.zig b/src/Query.zig index 27b83e1c..4cede3c5 100644 --- a/src/Query.zig +++ b/src/Query.zig @@ -859,19 +859,14 @@ fn setRows(p: *Pardes, rp: *Pane, out: *std.ArrayList(u8), rows: *std.ArrayList( if (std.mem.eql(u8, content, f.content)) { // Same text: the metadata alone, no undo step, no syntax pass. p.gpa.free(content); - if (locations.equalRows(f.location_rows, meta)) { - locations.freeRows(p.gpa, meta); - } else { - locations.freeRows(p.gpa, f.location_rows); - f.location_rows = meta; - dropHighlights(p, f); - } } else { File.setContent(p, f, content); - locations.freeRows(p.gpa, f.location_rows); - f.location_rows = meta; f.saved_revision = f.revision; } + File.setRows(p, f, meta) catch |err| { + locations.freeRows(p.gpa, meta); + if (p.paneBySerial(rp.serial)) |id| p.reportError(id, "rows", err); + }; if (f.pager_spans.len > 0) p.gpa.free(f.pager_spans); f.pager_spans = &.{}; // The cursor stays where it was typing; on a row that went, the last. @@ -996,24 +991,10 @@ pub fn recolor(p: *Pardes) void { fresh = rows; @memcpy(rows[i].colors[0..got.len], got); } - if (fresh) |rows| { - locations.freeRows(p.gpa, f.location_rows); - f.location_rows = rows; - dropHighlights(p, f); - } + if (fresh) |rows| File.setRows(p, f, rows) catch locations.freeRows(p.gpa, rows); } } -/// The pane's painted colours let go, so the next frame paints them from -/// its rows again: with its text the same, a frame would keep the old ones -/// (refreshHighlights keeps a painting that covers the view). -fn dropHighlights(p: *Pardes, f: *File.State) void { - if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); - f.highlights = &.{}; - f.highlight_start = 0; - f.syntax_dirty = true; -} - /// The path a row of pane `tp`'s text says: its file's, or `@pN` for a /// text that is no file (a list, a scratch). fn addressOf(arena: std.mem.Allocator, tp: *const Pane) []const u8 { @@ -1910,8 +1891,10 @@ pub fn cancel(p: *Pardes, id: usize) void { } const f = &rp.file.?; File.setContent(p, f, s.content); - locations.freeRows(p.gpa, f.location_rows); - f.location_rows = s.rows; + File.setRows(p, f, s.rows) catch |err| { + locations.freeRows(p.gpa, s.rows); + p.reportError(id, "query", err); + }; p.gpa.free(q.asked); q.asked = s.asked; q.source = s.source; @@ -2745,3 +2728,30 @@ test "a row's address is the shortest path a Look from the query pane resolves: } else return error.TestUnexpectedResult; } } + +test "a query row's address reaches every way a look arrives: an empty look written back to event and the whole row written to look, as the mouse on it" { + if (!filesystem.platform_has_fs) return; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 120, .rows = 48 }); + defer p.deinit(); + const a = try testFileIn(p, &tmp, "a.txt", "zero\none needle\ntwo\nthree needle here\n"); + leader(p, "fg"); + typeKeys(p, "needle"); + settle(p); + const qid = queryPane(p).?; + const qp = p.panes[qid].?; + const f = &qp.file.?; + const at = std.mem.indexOf(u8, f.content, "\na.txt:4:7").? + 1; + const line = f.content[at..std.mem.indexOfScalarPos(u8, f.content, at, '\n').?]; + // an empty look written back, on the address: the row's address whole, + // its path as the row keeps it + try std.testing.expect(std.mem.endsWith(u8, @import("ninep/events.zig").expandAt(p, qp, f.content, at + 3, true, true), "/a.txt:4:7")); + // on its code: the word there + try std.testing.expectEqualStrings("three", @import("ninep/events.zig").expandAt(p, qp, f.content, at + line.len - "three needle here".len + 1, true, true)); + // the whole row written to the pane's look: the place + a.body.cur_row = 0; + const tree = @import("ninep/tree.zig"); + try std.testing.expectEqual(tree.Status.ok, @import("ninep/testing.zig").wr(p, tree.Node.of(qp.serial, .look), line).reply.status); + try std.testing.expectEqual(@as(i32, 3), a.body.cur_row); +} diff --git a/src/body_layer.zig b/src/body_layer.zig index 942d7895..6c0ffcea 100644 --- a/src/body_layer.zig +++ b/src/body_layer.zig @@ -195,7 +195,7 @@ pub fn joinBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, layer.id = @intCast(id); layer.serial = pane.serial; const body = s.region(.body, id).?; - layer.viewport = .{ .x = body.rect.x, .y = body.rect.y, .w = body.rect.w - body.clip, .h = body.rect.h }; + layer.viewport = .{ .x = body.rect.x, .y = body.rect.y, .w = body.rect.w, .h = body.rect.h }; layer.cols = width; layer.rows = @intCast(logical_rows); layer.context_rows = pane.context_rows; diff --git a/src/builtins.zig b/src/builtins.zig index b2690920..d106330e 100644 --- a/src/builtins.zig +++ b/src/builtins.zig @@ -74,8 +74,7 @@ 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 => if (pane.file) |f| pane.colorAlgo() == .diff or - (f.output != null and std.meta.eql(f.output.?.from, panes.Output.Origin{ .cmd = .Diff })) else false, + .diff => @import("hunks.zig").shows(pane), }; } @@ -1094,17 +1093,12 @@ 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. +/// 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 output: OutputTraits = .{ .name = config.diff_buffer, .steps = true, .locations = true }; - pub fn run(c: Ctx) void { - const f = &c.pane.file.?; - if (panes.Output.diffSource(c.p, f)) |source| return panes.Output.showDiffText(c.p, c.id, source); - _ = panes.Output.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), - }; - } + pub const run = @import("hunks.zig").word; }; /// Cycle the pane's input modes: terminals add raw tty mode to normal/insert. diff --git a/src/colors.zig b/src/colors.zig index fab1b95d..d3ab82e2 100644 --- a/src/colors.zig +++ b/src/colors.zig @@ -322,6 +322,43 @@ pub fn synInk(th: *const Theme, sy: @import("syntax.zig").Syn) ?[3]u8 { }; } +/// The grounds a style byte's high bits name (syntax.ground_add and the +/// rest) in a theme: a row added or removed on a ground a little way from +/// the page toward the theme's green or red (its own ANSI ones where it has +/// a palette), a stronger one, a faint one, and the row's marker in that +/// hue, pushed toward the ink until it reads on the row's ground. Syntax +/// colours are drawn over a ground unchanged. +pub const Grounds = struct { + add: Ground, + del: Ground, + + pub const Ground = struct { row: [3]u8, emph: [3]u8, line: [3]u8, ink: [3]u8 }; + + pub fn of(th: *const Theme) Grounds { + const page = th.bg orelse th.tag_bg; + const ink = th.fg orelse th.tag_fg; + const green: [3]u8 = if (th.palette) |pal| pal[2] else .{ 0x2e, 0xa0, 0x43 }; + const red: [3]u8 = if (th.palette) |pal| pal[1] else .{ 0xcf, 0x22, 0x2e }; + return .{ .add = ground(page, ink, green), .del = ground(page, ink, red) }; + } + + fn ground(page: [3]u8, ink: [3]u8, hue: [3]u8) Ground { + const row = mixOklab(page, hue, 0.18); + var marker = hue; + var step: usize = 0; + while (step < 4 and contrast(marker, row) < 3) : (step += 1) marker = mixOklab(marker, ink, 0.4); + return .{ .row = row, .emph = mixOklab(page, hue, 0.28), .line = mixOklab(page, hue, 0.07), .ink = marker }; + } + + /// The ground of a byte's hue, if it has one. + pub fn forStyle(g: *const Grounds, style: u8) ?Ground { + const syntax = @import("syntax.zig"); + if (style & syntax.ground_add != 0) return g.add; + if (style & syntax.ground_del != 0) return g.del; + return null; + } +}; + /// One family, its twelve backgrounds a theme each (`curated`). const seoul256 = @import("themes/seoul256.zig"); diff --git a/src/config.zig b/src/config.zig index 3a846206..8a1528a8 100644 --- a/src/config.zig +++ b/src/config.zig @@ -1818,6 +1818,7 @@ test "reference.typ's #fstree is the tree the session serves, file for file" { for (std.enums.values(tree.TopFile)) |f| switch (f) { .root => {}, .new => try served.put(gpa, "pane/new", {}), + .rules, .send => try served.put(gpa, try std.fmt.allocPrint(gpa, "plumb/{s}", .{f.fileName()}), {}), else => try served.put(gpa, if (f.dir()) try std.fmt.allocPrint(gpa, "{s}/", .{f.fileName()}) else f.fileName(), {}), }; try served.put(gpa, "os/", {}); diff --git a/src/draw.zig b/src/draw.zig index 9a71ab1d..a73613ac 100644 --- a/src/draw.zig +++ b/src/draw.zig @@ -116,24 +116,6 @@ pub fn place(p: *Pardes, s: *Surface) void { } if (p.settings.workspace_tag) s.addRegion(.{ .kind = .workspace_tag, .rect = .{ .x = 0, .y = 0, .w = s.cols, .h = p.topBarHeight() } }); - // A column carried to the window's right edge shows where it lands as a - // rail in the last cell: the layers under it stop a cell short. - if (v.drag == .column_move) rail: { - const d = v.drag.column_move; - const source = layout.columnBySerial(p, d.serial) orelse break :rail; - const edge: u16 = switch (layout.columnDrop(p, source, d.cur_x, d.grab)) { - .stay => break :rail, - .reorder => |target| if (target < source) v.col_x[target] else v.col_x[target] + v.col_w[target], - .edge => |x| x, - }; - if (edge != s.cols) break :rail; - for (s.regions[0..s.nregions]) |*region| switch (region.kind) { - .body, .tag, .notice, .column_tag => if (region.rect.x + region.rect.w == s.cols) { - region.clip = 1; - }, - else => {}, - }; - } } /// A pane's grip in the grid: `box` focused, else halfway between its ring @@ -252,8 +234,6 @@ fn joinNotice(p: *Pardes, s: *Surface, arena: std.mem.Allocator, region: Region) if (layer.cursor) |caret| { if (caret.x >= skip) s.cursor = .{ .x = region.rect.x + caret.x - @as(u16, @intCast(skip)), .y = region.rect.y, .bar = caret.bar }; } - // Laid out at its full width; only shown short of the rail. - layer.viewport.w -|= region.clip; } pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { @@ -328,77 +308,6 @@ pub fn render(p: *Pardes, arena: std.mem.Allocator) !*Surface { try paintHeaders(p, s); - switch (v.drag) { - .border_v => |d| { - if (d.cur_x < s.cols) { - var row: u16 = p.topBarHeight(); - while (row < s.rows) : (row += 1) s.overlayDash(d.cur_x, row, "╎"); - s.addRegion(.{ .kind = .guide, .rect = .{ .x = d.cur_x, .y = p.topBarHeight(), .w = 1, .h = s.rows -| p.topBarHeight() } }); - } - if (d.corner) |k| if (d.cur_y < s.rows) { - const first = if (k.col == d.left_col) v.col_x[k.col] else d.cur_x +| 1; - const end = if (k.col == d.left_col) d.cur_x else v.col_x[k.col] +| v.col_w[k.col] -| 1; - var col = first; - while (col <= end and col < s.cols) : (col += 1) s.overlayDash(col, d.cur_y, "╌"); - if (col > first) s.addRegion(.{ .kind = .guide, .rect = .{ .x = first, .y = d.cur_y, .w = col - first, .h = 1 } }); - }; - }, - // A column that went away mid-drag has nothing to guide. - .border_h => |d| if (d.cur_y < s.rows and d.col < v.ncol and v.col_x[d.col] < s.cols) { - const end = @min(s.cols, v.col_x[d.col] + v.col_w[d.col]); - var col = v.col_x[d.col]; - while (col < end) : (col += 1) s.overlayDash(col, d.cur_y, "╌"); - s.addRegion(.{ .kind = .guide, .rect = .{ .x = v.col_x[d.col], .y = d.cur_y, .w = end - v.col_x[d.col], .h = 1 } }); - }, - .column_move => |d| rail: { - const source = layout.columnBySerial(p, d.serial) orelse break :rail; - if (s.cols == 0) break :rail; - // Where the column's left edge would land, reordered or not. - const edge: u16 = switch (layout.columnDrop(p, source, d.cur_x, d.grab)) { - .stay => break :rail, - .reorder => |target| if (target < source) v.col_x[target] else v.col_x[target] + v.col_w[target], - .edge => |x| x, - }; - // The layers under an outside rail stop a cell short of it: - // `place` clipped them. - // The rail runs in the seam cell left of the edge, where a - // border drag's does: the edge cell itself is a gutter, which - // the GUI paints as a scroll rail that swallowed the dashes. - // At the window's left edge there is no seam, so it runs just - // past that scroll rail instead. It takes the lit grip's - // color: this is where the grabbed column lands. - const x = @min(if (edge == 0) config.GUTTER - 1 else edge - 1, s.cols -| 1); - var row: u16 = p.topBarHeight(); - // A guide region for each run of it the tags do not break. - var run: u16 = row; - while (row < s.rows) : (row += 1) { - // Past the left edge's scroll rail the rail would cut - // through column 0's grip and pane boxes: leave them whole. - if (edge == 0 and s.at(x, row).style.font_role == .tagline) { - if (row > run) s.addRegion(.{ .kind = .guide, .rect = .{ .x = x, .y = run, .w = 1, .h = row - run } }); - run = row + 1; - continue; - } - s.overlayDash(x, row, "╎"); - s.at(x, row).style.fg = .{ .rgb = chrome.column_box }; - } - if (row > run) s.addRegion(.{ .kind = .guide, .rect = .{ .x = x, .y = run, .w = 1, .h = row - run } }); - }, - .move => |d| if (d.cur_x < s.cols) { - if (layout.movePlacement(p, d.id, d.cur_x, d.cur_y)) |placement| if (placement.row < s.rows and v.col_x[placement.preview_col] + v.col_w[placement.preview_col] <= s.cols) { - var col: u16 = v.col_x[placement.preview_col]; - while (col < v.col_x[placement.preview_col] + v.col_w[placement.preview_col]) : (col += 1) { - s.set(col, placement.row, "╌", .{ .fg = .{ .rgb = chrome.lineno } }); - } - s.set(d.cur_x, placement.row, "▌", .{ .fg = .{ .rgb = chrome.lineno } }); - s.addRegion(.{ .kind = .guide, .rect = .{ .x = v.col_x[placement.preview_col], .y = placement.row, .w = v.col_w[placement.preview_col], .h = 1 } }); - s.addRegion(.{ .kind = .guide, .rect = .{ .x = d.cur_x, .y = placement.row, .w = 1, .h = 1 } }); - }; - }, - // A hover draws no hint: columns resize by their grips. - .none, .select => {}, - } - // debug overlay: a small stats box drawn last, top-right ("Debug") if (p.settings.debug) if (p.panes[v.active]) |at| { var nlive: usize = 0; @@ -607,8 +516,6 @@ fn paintHeaders(p: *Pardes, s: *Surface) !void { const layer = &s.tag_layers[MAX_PANES + c]; try renderHeaderLayer(p, layer, .column, @intCast(c), region.rect, tagline.columnTag(p, c), top, bg, fg); if (v.col_x[c] < s.cols) joinHeaderRows(s, layer, fg); - // Laid out at its full width; only shown short of the rail. - layer.viewport.w -|= region.clip; }; } @@ -810,7 +717,7 @@ fn joinPaneTag(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane, r layer.kind = .pane; layer.id = @intCast(id); layer.serial = pane.serial; - layer.viewport = .{ .x = region.rect.x, .y = region.rect.y, .w = region.rect.w - region.clip, .h = rows }; + layer.viewport = .{ .x = region.rect.x, .y = region.rect.y, .w = region.rect.w, .h = rows }; layer.cols = columns; layer.rows = rows; layer.context_rows = 0; diff --git a/src/exec.zig b/src/exec.zig index 3593bb72..b4c20f45 100644 --- a/src/exec.zig +++ b/src/exec.zig @@ -165,44 +165,30 @@ pub fn operandAt(p: *Pardes, pane: *Pane, clicked: Pane.Sel, borrow: bool, for_l return result; } } - // In a diff, a file or hunk header, and a hunk line pointed at on its - // `+`/`-`/` ` prefix, expand to the whole line (the hover shows it) and - // the look is of the address it names (look.diffAddress), a regular - // look from there. A hunk line's code is words, looked at as ever: - // the code's, the prefix never one of them. - // A query pane's row pointed at on its gutter (its line number): the - // look is of the row's address (Query.rowAddress), as a +Diff line's - // prefix is its place; the row's code is words, looked at as ever. - if (for_look and pane.query != null and clicked.r0 >= pane.tag_rows and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1 and row >= 0 and col >= 0) gutter: { - var address_buf: [4096 + 32]u8 = undefined; - const address = panes.Query.rowAddress(pane, @intCast(row), @intCast(col), &address_buf) orelse break :gutter; - const meta = pane.file.?.location_rows[@intCast(row)]; - result.text = p.scratch.allocator().dupe(u8, address) catch break :gutter; - result.file_word = .{ .row = row, .lo = 0, .hi = @intCast(meta.location_end) }; - const expanded = fileWordCells(pane, clicked, row, 0, @intCast(meta.location_end)) orelse return result; - result.preview = expanded; - result.expanded = expanded; - return result; - } + // A row that names an address (look.rowAddressAt), pointed at on it: a + // query pane's row on its address (its gutter), a diff's file or hunk + // header anywhere, a hunk line on its `+`/`-`/` ` prefix. It expands + // to the address's text (the hover shows it) and the look is of the + // address, a regular look from there. A row's code is words, looked at + // as ever: the code's, the prefix never one of them. A click left of a + // query pane's text is no part of its row. var word_from: usize = 0; - if (for_look and clicked.r0 >= pane.tag_rows and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1 and row >= 0) diff: { + if (for_look and clicked.r0 >= pane.tag_rows and clicked.r0 == clicked.r1 and clicked.c0 == clicked.c1 and row >= 0 and (col >= 0 or pane.query == null)) row_address: { var address_buf: [4096 + 32]u8 = undefined; - const at: usize = @intCast(row); - const click = look.diffClick(p, pane, at, @intCast(@max(0, col)), &address_buf) orelse break :diff; - const address = click.address orelse { - word_from = click.word_from; - break :diff; + const got = look.rowAddressAt(p, pane, @intCast(row), @intCast(@max(0, col)), &address_buf) orelse break :row_address; + const address = got.address orelse { + word_from = got.word_from; + break :row_address; }; - const line = (look.diffLines(p, pane) orelse break :diff)[at]; - result.text = p.scratch.allocator().dupe(u8, address) catch break :diff; - const hi = std.math.cast(i32, line.len) orelse return result; + result.text = p.scratch.allocator().dupe(u8, address) catch break :row_address; + const hi = std.math.cast(i32, got.end) orelse return result; if (hi == 0) return result; var expanded = clicked; if (pane.file != null) { result.file_word = .{ .row = row, .lo = 0, .hi = hi }; expanded = fileWordCells(pane, clicked, row, 0, hi) orelse return result; } else { - const shown = if (raw) raw_line else line; + const shown = if (raw) raw_line else got.line; expanded.c0 = 0; expanded.c1 = @as(i32, @intCast(panes.File.rawDisplayCol(shown, shown.len))) - 1; } @@ -737,7 +723,7 @@ pub fn executeFrom(p: *Pardes, id: usize, txt: []const u8, from_body: bool) ?usi /// is done, else a new one, placed as layout.placeNew places a command pane. /// A pane reused keeps what it showed: the new command runs below a line /// naming it, as acme appends to +Errors and never clears it (util.c:213). -fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { +pub fn runCommand(p: *Pardes, from: usize, line: []const u8) ?usize { if (line.len > command_max) { p.reportFailure(from, "exec: a command line is at most 1024 bytes"); return null; @@ -760,7 +746,7 @@ 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 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 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 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; diff --git a/src/fs-help.txt b/src/fs-help.txt index bc699418..4e43a476 100644 --- a/src/fs-help.txt +++ b/src/fs-help.txt @@ -19,13 +19,13 @@ recent files opened lately, closed ones too: open|closed <path> dumps the dumps the state file keeps, the newest first: <label> <date> <size> <panes> layout a line per column: serial index x width current|notcurrent empty|full pane-serials; then active <serial> tag the workspace tag, tagexec a word as a click in it; col/<serial>/ a column's tag, ctl, exec; rmdir: empty only +plumb/ rules: the plumber's rules, plumb(6)'s (a write adds rule sets, > replaces); send: write a message, six lines then data pane/new open it to make a pane (<session dir>/+New) in the active column; the read answers its serial -pane/<n>/ name body tag ctl addr dot limit data xdata sel dirty mark scroll errors event look exec tagexec; rmdir closes +pane/<n>/ name body tag ctl addr dot limit data xdata sel dirty mark scroll errors event look exec tagexec rows; rmdir closes + rows: a line a row, kind (m c p; d decl, u unmarked) line col end_line end_col source_column location_end code_start styles path; styles - or N:start+len=role,... (keyword string number comment, add del emph line, joined by .); a write at 0 replaces on terminals pty/data (keys in, output out), pty/status, pty/ctl (winsize, sig, exec), pty/run (a line, its exit and output) os/, src/ the host filesystem; the editor's own sources - $m below: $PARDES_MOUNT (set under 9ns --mntgen); without it, 9p -a "unix!$PARDES_9P". - cat $m/index which panes exist n=$(cat $m/pane/new) make a pane of your own (each open makes one), take its serial exec 3<>$m/pane/$n/look; echo /etc/hosts:3 >&3; cat <&3 open a file through it, see the pane it went to diff --git a/src/grammar_manifest.zig b/src/grammar_manifest.zig index 38c54916..711c31a4 100644 --- a/src/grammar_manifest.zig +++ b/src/grammar_manifest.zig @@ -1,6 +1,7 @@ //! Dependency-free tree-sitter grammar metadata shared by build.zig and the -//! runtime syntax registry. Keep target symbols and query values out of this -//! file: the build runner imports it as host code. +//! runtime syntax registry, and the highlight-query filter the build runs. +//! Keep target symbols and query values out of this file: the build runner +//! imports it as host code. const std = @import("std"); @@ -14,6 +15,8 @@ pub const Grammar = struct { src: []const u8 = "src", scanner: bool = false, query: []const u8 = "queries/highlights.scm", + /// Patterns appended to the highlights query before it is filtered. + highlights_extra: []const u8 = "", }; pub const all = [_]Grammar{ @@ -48,7 +51,13 @@ pub const all = [_]Grammar{ .{ .name = "ruby", .dep = "ts_ruby", .exts = &.{ ".rb", ".rake" }, .tier = .full, .scanner = true }, .{ .name = "rust", .dep = "ts_rust", .exts = &.{".rs"}, .tier = .full, .scanner = true }, .{ .name = "scala", .dep = "ts_scala", .exts = &.{ ".scala", ".sc" }, .tier = .full, .scanner = true }, - .{ .name = "typst", .dep = "ts_typst", .exts = &.{ ".typ", ".typst" }, .tier = .full, .scanner = true, .query = "queries/typst/highlights.scm" }, + .{ .name = "typst", .dep = "ts_typst", .exts = &.{ ".typ", ".typst" }, .tier = .full, .scanner = true, .query = "queries/typst/highlights.scm", .highlights_extra = + \\ + \\(call item: (ident) @keyword) + \\(call item: (field field: (ident) @keyword)) + \\"#" @keyword + \\ + }, .{ .name = "zig", .dep = "ts_zig", .exts = &.{ ".zig", ".zon" }, .tier = .zig }, }; @@ -92,3 +101,96 @@ pub fn byPath(path: []const u8) ?usize { for (all, 0..) |g, i| for (g.exts) |e| if (std.ascii.eqlIgnoreCase(ext, e)) return i; return null; } + +/// pardes's syntax classes: what a capture colours a byte as. +pub const Syn = enum(u8) { none, keyword, string, number, comment }; + +pub fn synFor(name: []const u8) Syn { + for ([_]struct { []const u8, Syn }{ + .{ "comment", .comment }, + .{ "string", .string }, + .{ "character", .string }, + .{ "number", .number }, + .{ "numeric", .number }, + .{ "float", .number }, + .{ "boolean", .number }, + .{ "keyword", .keyword }, + .{ "include", .keyword }, + .{ "conditional", .keyword }, + .{ "repeat", .keyword }, + .{ "title", .keyword }, + .{ "uri", .string }, + .{ "reference", .number }, + .{ "heading", .keyword }, + .{ "strong", .comment }, + .{ "bold", .comment }, + .{ "emphasis", .number }, + .{ "italic", .number }, + .{ "literal", .string }, + .{ "raw", .string }, + }) |m| { + if (std.mem.indexOf(u8, name, m[0]) != null) return m[1]; + } + return .none; +} + +/// The patterns of highlights query `source` that capture a class (synFor), +/// written to `out` (source.len bytes): what a grammar's query compiles to. +/// build.zig filters each one with it, ts_queries' `<name>_highlights`. +pub fn colorQuery(source: []const u8, out: []u8) []u8 { + var written: usize = 0; + var at: usize = 0; + while (at < source.len) { + while (at < source.len) { + if (std.ascii.isWhitespace(source[at])) { + at += 1; + } else if (source[at] == ';') { + while (at < source.len and source[at] != '\n') at += 1; + } else break; + } + const begin = at; + var depth: usize = 0; + var colored = false; + var complete = false; + while (at < source.len) { + const byte = source[at]; + if (complete and (byte == '(' or byte == '[' or byte == '"')) break; + if (byte == ';') { + while (at < source.len and source[at] != '\n') at += 1; + continue; + } + if (byte == '"') { + at += 1; + while (at < source.len) : (at += 1) { + if (source[at] == '\\') { + at += 1; + } else if (source[at] == '"') { + at += 1; + break; + } + } + if (depth == 0) complete = true; + continue; + } + if (byte == '(' or byte == '[') depth += 1; + if (byte == ')' or byte == ']') { + depth -= 1; + if (depth == 0) complete = true; + } + if (byte == '@') { + const name = at + 1; + at = name; + while (at < source.len and (std.ascii.isAlphanumeric(source[at]) or + source[at] == '_' or source[at] == '.' or source[at] == '-')) at += 1; + colored = colored or synFor(source[name..at]) != .none; + continue; + } + at += 1; + } + if (colored) { + @memcpy(out[written..][0 .. at - begin], source[begin..at]); + written += at - begin; + } + } + return out[0..written]; +} diff --git a/src/gui/gui.zig b/src/gui/gui.zig index c2a4ad15..1ec3bca3 100644 --- a/src/gui/gui.zig +++ b/src/gui/gui.zig @@ -868,12 +868,12 @@ const Group = struct { }; /// The frame's draw groups, bottom to top: the page and the panes, the -/// notices floating over them, the guides and the debug box the core paints -/// over those, and ink (the bar cursors; the cursor's glide draws after it). +/// notices floating over them, the debug box the core paints over those, +/// and ink (the bar cursors; the cursor's glide draws after it). const Groups = struct { items: [4]Group = @splat(.{}), notices: usize = 1, - guides: usize = 2, + debug: usize = 2, ink: usize = 3, len: usize = 4, }; @@ -883,7 +883,7 @@ const Groups = struct { const Cover = packed struct(u16) { /// A layer draws it; the grid's copy is not drawn. layer: bool = false, - /// Under a guide or the debug box: drawn from the grid over the panes. + /// Under the debug box: drawn from the grid over the panes. floating: bool = false, /// In a pane's grip, `grip_offset` cells from its left: the grip's /// glyph is the cell that far to the left. @@ -950,7 +950,7 @@ fn coverFrame(cover: []Cover, cols: u16, rows: u16, body_layers: []const pardes. mark.rect(cover, cols, rows, .{ .x = region.rect.x, .y = 0, .w = 1, .h = rows }, "anchor", true); if (region.active) if (bar) |b| mark.rect(cover, cols, rows, .{ .x = region.rect.x, .y = b.y, .w = region.rect.w, .h = b.h }, "focus", true); }, - .guide, .debug => mark.rect(cover, cols, rows, region.rect, "floating", true), + .debug => mark.rect(cover, cols, rows, region.rect, "floating", true), else => {}, }; } @@ -4559,7 +4559,7 @@ fn renderFrame( while (col < surface.cols) : (col += 1) { const at = @as(usize, row) * surface.cols + col; if (covered[at].layer and !covered[at].floating) continue; - const group_index = if (covered[at].floating) groups.guides else 0; + const group_index = if (covered[at].floating) groups.debug else 0; groups.items[group_index].cell_count = std.math.add(u32, groups.items[group_index].cell_count, cellInstanceCount(&surface.cells[at])) catch return error.GpuCapacity; } } @@ -4608,7 +4608,7 @@ fn renderFrame( while (col < surface.cols) : (col += 1) { const at = @as(usize, row) * surface.cols + col; if (covered[at].layer and !covered[at].floating) continue; - const group_index = if (covered[at].floating) groups.guides else 0; + const group_index = if (covered[at].floating) groups.debug else 0; emitSurfaceCell( g, chrome, diff --git a/src/hunks.zig b/src/hunks.zig index 8f4b4233..afd2ac9d 100644 --- a/src/hunks.zig +++ b/src/hunks.zig @@ -6,21 +6,48 @@ //! a tinted ground as delta emphasises them (its edits.rs and align.rs, here as `inferEdits` //! and `Alignment`). const std = @import("std"); -const pardes = @import("pardes.zig"); const diff = @import("diff.zig"); const syntax = @import("syntax.zig"); const locations = @import("locations.zig"); +const pardes = @import("pardes.zig"); const Pardes = pardes.Pardes; +const Pane = pardes.Pane; +const Output = pardes.panes.Output; + const Row = locations.Row; +/// What `format` takes of the editor it stacks for: its allocators, the +/// files a diff names read as the editor reads them (in pardes an open +/// pane's text, else the disk's, each read a site of the step's tape: +/// openDiff), their declarations, and one setting. +pub const Ctx = struct { + /// The text and rows made, the caller's. + gpa: std.mem.Allocator, + /// All else, the call's. + arena: std.mem.Allocator, + /// `path` as a look from `dir` finds it, its text the arena's (or the + /// editor's, good for the call); null when it is not there. + source: *const fn (ctx: *const Ctx, dir: []const u8, path: []const u8) ?Source, + /// The declarations of `bytes`, the file at `path`, outermost first + /// (syntax.analyzeSource's), the arena's. + declarations: *const fn (ctx: *const Ctx, path: []const u8, bytes: []const u8) error{OutOfMemory}![]const syntax.ContextDeclaration, + /// The two above's own. + host: *anyopaque, + /// A declaration above a hunk gets its `path:line` row too + /// (LocationsConfig's tslocations). + tslocations: bool, +}; + +/// A file's text, and its path as `dir` and the path named resolve. +pub const Source = struct { path: []const u8, bytes: []const u8 }; + /// The rows `content`, a diff, stacks to, for a pane in `dir`, with each -/// row's metadata (Output.fillRows). Text and rows are `p.gpa`'s; all else -/// is the step's scratch. -pub fn format(p: *Pardes, dir: []const u8, content: []const u8) !locations.Result { - const arena = p.scratch.allocator(); +/// row's metadata (Output.fillRows). Text and rows are `ctx.gpa`'s. +pub fn format(ctx: *const Ctx, dir: []const u8, content: []const u8) !locations.Result { + const arena = ctx.arena; const styles = try syntax.highlightDiff(arena, content, 0, content.len); - var out: Out = .{ .p = p, .text = .init(p.gpa) }; + var out: Out = .{ .gpa = ctx.gpa, .text = .init(ctx.gpa) }; errdefer out.deinit(); var walk: diff.Walk = .{}; var hunk: Hunk = .{}; @@ -46,7 +73,7 @@ pub fn format(p: *Pardes, dir: []const u8, content: []const u8) !locations.Resul // A `\ No newline` belongs to the line above, as delta shows it. .no_newline => {}, else => { - try flush(&out, &hunk, &source, dir); + try flush(ctx, &out, &hunk, &source, dir); switch (got.kind) { .hunk => hunk = .{ .path = walk.path(), @@ -69,9 +96,9 @@ pub fn format(p: *Pardes, dir: []const u8, content: []const u8) !locations.Resul } at = nl + 1; } - try flush(&out, &hunk, &source, dir); - const rows = try out.rows.toOwnedSlice(p.gpa); - errdefer locations.freeRows(p.gpa, rows); + try flush(ctx, &out, &hunk, &source, dir); + const rows = try out.rows.toOwnedSlice(ctx.gpa); + errdefer locations.freeRows(ctx.gpa, rows); return .{ .content = try out.text.toOwnedSlice(), .rows = rows, .anchor = null }; } @@ -105,13 +132,13 @@ fn gitContext(line: []const u8) []const u8 { } const Out = struct { - p: *Pardes, + gpa: std.mem.Allocator, text: std.Io.Writer.Allocating, rows: std.ArrayList(Row) = .empty, fn deinit(out: *Out) void { out.text.deinit(); - locations.freeRowList(out.p.gpa, &out.rows); + locations.freeRowList(out.gpa, &out.rows); } const Meta = struct { @@ -127,7 +154,7 @@ const Out = struct { fn row(out: *Out, text: []const u8, path: []const u8, meta: Meta) !void { try out.text.writer.writeAll(text); try out.text.writer.writeByte('\n'); - try locations.appendRow(out.p.gpa, &out.rows, .{ + try locations.appendRow(out.gpa, &out.rows, .{ .kind = meta.kind, .declaration = meta.declaration, .path = @constCast(path), @@ -153,7 +180,7 @@ const SourceMemo = struct { /// Where a +Diff of `content`, a diff in `dir`, stands: the directory its /// first file is found from (`dir` or one above it, as `findSource` looks), /// so its rows name their files as the diff does; `dir` when none is found. -pub fn sourceRoot(p: *Pardes, dir: []const u8, content: []const u8) []const u8 { +pub fn sourceRoot(ctx: *const Ctx, dir: []const u8, content: []const u8) []const u8 { var walk: diff.Walk = .{}; var lines = std.mem.splitScalar(u8, content, '\n'); const path = while (lines.next()) |line| { @@ -161,31 +188,27 @@ pub fn sourceRoot(p: *Pardes, dir: []const u8, content: []const u8) []const u8 { } else return dir; var base: []const u8 = dir; for (0..8) |_| { - if (locations.sourceText(p, p.scratch.allocator(), base, path) != null) return base; + if (ctx.source(ctx, base, path) != null) return base; base = std.Io.Dir.path.dirname(base) orelse return dir; } return dir; } -fn findSource(p: *Pardes, memo: *SourceMemo, dir: []const u8, path: []const u8) !void { +fn findSource(ctx: *const Ctx, memo: *SourceMemo, dir: []const u8, path: []const u8) !void { if (std.mem.eql(u8, memo.path, path)) return; - const arena = p.scratch.allocator(); + const arena = ctx.arena; memo.* = .{ .path = path }; // ponytail: eight directories up; a repository deeper than that under // its patch is looked for from the patch's own directory only. var base: []const u8 = dir; for (0..8) |_| { - if (locations.sourceText(p, arena, base, path)) |text| { + if (ctx.source(ctx, base, path)) |text| { memo.shown = if (base.ptr == dir.ptr) path else try std.Io.Dir.path.relativePosix(arena, "/", dir, text.path); var lines: std.ArrayList([]const u8) = .empty; var split = std.mem.splitScalar(u8, text.bytes, '\n'); while (split.next()) |line| try lines.append(arena, std.mem.trimEnd(u8, line, "\r")); memo.lines = lines.items; - var hit = p.locations_cache.get(p.tree_sitter_gpa, text.path, text.bytes, true, false) catch - locations.Cache.Hit{ .analysis = syntax.analyzeSource(arena, text.path, text.bytes, true, false) catch .{} }; - defer hit.deinit(p.tree_sitter_gpa); - // The cache's may go at its next use: kept for the section. - memo.declarations = try arena.dupe(syntax.ContextDeclaration, hit.analysis.declarations); + memo.declarations = try ctx.declarations(ctx, text.path, text.bytes); return; } base = std.Io.Dir.path.dirname(base) orelse return; @@ -251,12 +274,11 @@ fn heldAt(memo: *const SourceMemo, hunk: *const Hunk, comptime side: Side, start return .{ .held = held, .of = @max(of, 1) }; } -fn flush(out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []const u8) !void { +fn flush(ctx: *const Ctx, out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []const u8) !void { defer hunk.* = .{}; if (hunk.path.len == 0 or hunk.lines.items.len == 0) return; - const p = out.p; - const arena = p.scratch.allocator(); - try findSource(p, memo, dir, hunk.path); + const arena = ctx.arena; + try findSource(ctx, memo, dir, hunk.path); const disk = sideOnDisk(memo, hunk); const side = disk.side; // A line number of the hunk's, where the file has it now. @@ -287,7 +309,7 @@ fn flush(out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []const u8) !void { var row = declaration.start_line; while (row <= declaration.header_end_line and row < start_row) : (row += 1) { const at: @FieldType(Row, "at") = .{ .line = row + 1 }; - if (row == declaration.start_line and p.locations_config.tslocations) { + if (row == declaration.start_line and ctx.tslocations) { const label = try std.fmt.allocPrint(arena, "{s}:{d}", .{ shown, row + 1 }); try out.row(label, shown, .{ .kind = .context, .declaration = true, .at = at, .location_end = label.len, .code_start = label.len }); } @@ -331,10 +353,10 @@ fn flush(out: *Out, hunk: *Hunk, memo: *SourceMemo, dir: []const u8) !void { // has it: the marker coloured, the line as its file's. for (lines) |line| { const flag: u8 = switch (line.kind) { - .added => syntax.diff_added, - .removed => syntax.diff_removed, + .added => syntax.ground_add, + .removed => syntax.ground_del, else => 0, - } | @as(u8, if (line.kind != .context and !line.paired) syntax.diff_whole else 0); + } | @as(u8, if (line.kind != .context and !line.paired) syntax.ground_line else 0); const text = try std.fmt.allocPrint(arena, "{c}{s}", .{ @as(u8, switch (line.kind) { .added => '+', .removed => '-', @@ -389,10 +411,10 @@ fn inferEdits(arena: std.mem.Allocator, minus: []HunkLine, plus: []HunkLine) !vo const marks = annotate(pair, &alignment, m.code, plus[j].code) catch continue; if (marks.distance > max_line_distance) continue; for (marks.minus) |r| for (m.styles[r[0]..r[1]]) |*b| { - b.* |= syntax.diff_emph; + b.* |= syntax.ground_emph; }; for (marks.plus) |r| for (plus[j].styles[r[0]..r[1]]) |*b| { - b.* |= syntax.diff_emph; + b.* |= syntax.ground_emph; }; m.paired = true; plus[j].paired = true; @@ -574,16 +596,208 @@ fn annotate(arena: std.mem.Allocator, a: *const Alignment, minus_line: []const u } fn trimmedWidth(section: []const u8) usize { - return pardes.panes.File.displayWidth(std.mem.trim(u8, section, " \t")); + return @import("File.zig").displayWidth(std.mem.trim(u8, section, " \t")); +} + +// ---- 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. +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), + }; +} + +/// 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 })); +} + +/// 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; +} + +/// The hook of a +Pager filled with a diff (ninep/ctl.zig's fillPager: +/// `git show`, difftui's patches): its hunks stacked in a +Diff in the +/// +Pager's place, the +Pager closed. The keyboard stays where it was, as +/// a page's. +pub fn paged(p: *Pardes, id: usize) void { + const f = &p.panes[id].?.file.?; + const keyboard = p.view().active; + if (openDiff(p, id, f.path, f.content)) |hid| { + // ponytail: the text is gone with it; Diff on the +Diff says no such file. + p.removePane(id, hid) catch |err| p.reportError(id, "pager", err); + } else |_| {} + 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; + var letter = false; + for (hex) |c| switch (c) { + '0'...'9' => digit = true, + 'a'...'f' => letter = true, + else => return false, + }; + return digit and letter; +} + +/// Diff: `content`, the diff at `path` (a file, a +Pager), stacked as a +/// diff viewer shows it (format), in a +Diff where its files are found +/// (sourceRoot), placed by pane `id`, refilled when it is there. Its +/// arg names the diff (its base name, or its whole path when the +Diff +/// stands elsewhere), for Diff to go back to it; a commit's (`git show`, a +/// mailed patch) is named for it too, `+Diff-<12 hex>`, so each commit +/// keeps a +Diff of its own. The +Diff's id; NoHunks when there is none in +/// it. +pub fn openDiff(p: *Pardes, id: usize, path: []const u8, content: []const u8) !usize { + const dir = std.Io.Dir.path.dirname(path) orelse p.sessionDir(); + // Each file read is a site of the step's tape (fs.zig): a replica + // replays the authority's bytes and reads no disk of its own. + const Read = struct { + fn source(ctx: *const Ctx, from: []const u8, name: []const u8) ?Source { + const pp: *Pardes = @ptrCast(@alignCast(ctx.host)); + const text = locations.sourceText(pp, ctx.arena, from, name) orelse return null; + return .{ .path = text.path, .bytes = text.bytes }; + } + fn declarations(ctx: *const Ctx, name: []const u8, bytes: []const u8) error{OutOfMemory}![]const syntax.ContextDeclaration { + const pp: *Pardes = @ptrCast(@alignCast(ctx.host)); + var hit = pp.locations_cache.get(pp.tree_sitter_gpa, name, bytes, true, false) catch + locations.Cache.Hit{ .analysis = syntax.analyzeSource(ctx.arena, name, bytes, true, false) catch .{} }; + defer hit.deinit(pp.tree_sitter_gpa); + // The cache's may go at its next use: kept for the call. + return ctx.arena.dupe(syntax.ContextDeclaration, hit.analysis.declarations); + } + }; + const ctx: Ctx = .{ + .gpa = p.gpa, + .arena = p.scratch.allocator(), + .source = Read.source, + .declarations = Read.declarations, + .host = p, + .tslocations = p.locations_config.tslocations, + }; + const root = sourceRoot(&ctx, dir, content); + const result = try format(&ctx, root, content); + errdefer { + p.gpa.free(result.content); + locations.freeRows(p.gpa, result.rows); + } + var has_hunk = false; + for (result.rows) |row| has_hunk = has_hunk or row.kind == .match; + if (!has_hunk) return error.NoHunks; + const arg = if (std.mem.eql(u8, root, dir) or path.len > Output.max_arg) std.Io.Dir.path.basename(path) else path; + var name_buf: [pardes.config.diff_buffer.len + 13]u8 = undefined; + const name = if (diff.commitHash(content)) |hash| + std.fmt.bufPrint(&name_buf, "{s}-{s}", .{ pardes.config.diff_buffer, hash[0..@min(hash.len, 12)] }) catch unreachable + else + null; + return Output.fillRows(p, id, root, .{ .cmd = .Diff }, name, arg, result.content, result.rows, null); +} + +/// Diff on a +Diff: the diff it stacks, as text. A pane holding it +/// already (the newest: a +Pager folded under its +Diff unfolds) is +/// shown; else the file is opened as text. +pub fn showDiffText(p: *Pardes, id: usize, source: []const u8) void { + var newest: ?usize = null; + for (p.panes, 0..) |slot, i| { + const f = (slot orelse continue).file orelse continue; + if (!std.mem.eql(u8, f.path, source)) continue; + if (newest == null or p.panes[newest.?].?.serial < slot.?.serial) newest = i; + } + if (newest) |i| { + if (p.panes[i].?.collapsed) pardes.layout.toggleCollapse(p, i); + p.view().active = i; + return; + } + p.look_text = true; + defer p.look_text = false; + pardes.look.lookAt(p, id, source); +} + +/// The diff a +Diff stacks (openDiff's arg): its path. +pub fn diffSource(p: *Pardes, f: *const pardes.panes.File.State) ?[]const u8 { + const o = f.output orelse return null; + if (!std.meta.eql(o.from, Output.Origin{ .cmd = .Diff })) return null; + const arg = o.arg(); + if (arg.len > 0 and arg[0] == '/') return arg; + return std.Io.Dir.path.join(p.scratch.allocator(), &.{ std.Io.Dir.path.dirname(f.path) orelse "", arg }) catch null; } // ---- tests ---- const testing = std.testing; +/// A Ctx over the disk, as the editor's is without panes or a cache. +const TestCtx = struct { + arena_state: std.heap.ArenaAllocator, + ctx: Ctx, + + fn init(t: *TestCtx) void { + t.arena_state = .init(testing.allocator); + t.ctx = .{ .gpa = testing.allocator, .arena = t.arena_state.allocator(), .source = source, .declarations = declarations, .host = t, .tslocations = true }; + syntax.start(testing.allocator); + } + + fn deinit(t: *TestCtx) void { + syntax.stop(); + t.arena_state.deinit(); + } + + fn source(ctx: *const Ctx, dir: []const u8, path: []const u8) ?Source { + const full = std.Io.Dir.path.resolvePosix(ctx.arena, &.{ dir, path }) catch return null; + const bytes = std.Io.Dir.cwd().readFileAlloc(testing.io, full, ctx.arena, .limited(1 << 20)) catch return null; + return .{ .path = full, .bytes = bytes }; + } + + fn declarations(ctx: *const Ctx, path: []const u8, bytes: []const u8) error{OutOfMemory}![]const syntax.ContextDeclaration { + return (syntax.analyzeSource(ctx.arena, path, bytes, true, false) catch return &.{}).declarations; + } +}; + fn emphasised(line: HunkLine) ![]const u8 { var out: std.ArrayList(u8) = .empty; - for (line.code, line.styles) |c, s| try out.append(testing.allocator, if (s & syntax.diff_emph != 0) c else '.'); + for (line.code, line.styles) |c, s| try out.append(testing.allocator, if (s & syntax.ground_emph != 0) c else '.'); return out.toOwnedSlice(testing.allocator); } @@ -631,8 +845,9 @@ test "delta's alignment: kitten to sitting, as align.rs has it" { } test "a diff stacks to a label a hunk and its lines, markers gone, tinted and stepped" { - const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); - defer p.deinit(); + var t: TestCtx = undefined; + t.init(); + defer t.deinit(); const patch = \\diff --git a/nowhere/x.txt b/nowhere/x.txt \\--- a/nowhere/x.txt @@ -644,28 +859,29 @@ test "a diff stacks to a label a hunk and its lines, markers gone, tinted and st \\ tail \\ ; - const result = try format(p, "/pardes-surely-missing-dir", patch); - defer p.gpa.free(result.content); - defer locations.freeRows(p.gpa, result.rows); + const result = try format(&t.ctx, "/pardes-surely-missing-dir", patch); + defer testing.allocator.free(result.content); + defer locations.freeRows(testing.allocator, result.rows); try testing.expectEqualStrings("nowhere/x.txt:2\n section one\n keep\n-old value\n+new value\n tail\n", result.content); try testing.expectEqual(@as(usize, 6), result.rows.len); try testing.expectEqual(.match, result.rows[0].kind); try testing.expectEqual(@as(usize, "nowhere/x.txt:2".len), result.rows[0].location_end); try testing.expect(result.rows[1].declaration); const removed = result.rows[3]; - try testing.expect(removed.colors[0] & syntax.diff_removed != 0); + try testing.expect(removed.colors[0] & syntax.ground_del != 0); // Paired with the line it changed: no whole-line tint. - try testing.expect(removed.colors[0] & syntax.diff_whole == 0); - try testing.expect(removed.colors[1] & syntax.diff_emph != 0); - try testing.expect(removed.colors[5] & syntax.diff_emph == 0); - try testing.expect(result.rows[4].colors[0] & syntax.diff_added != 0); - try testing.expect(result.rows[2].colors[0] & (syntax.diff_added | syntax.diff_removed) == 0); + try testing.expect(removed.colors[0] & syntax.ground_line == 0); + try testing.expect(removed.colors[1] & syntax.ground_emph != 0); + try testing.expect(removed.colors[5] & syntax.ground_emph == 0); + try testing.expect(result.rows[4].colors[0] & syntax.ground_add != 0); + try testing.expect(result.rows[2].colors[0] & (syntax.ground_add | syntax.ground_del) == 0); } test "a hunk the file has moved since is found where it went, inside its declaration" { if (!syntax.supportsPath("a.zig")) return error.SkipZigTest; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); - defer p.deinit(); + var t: TestCtx = undefined; + t.init(); + defer t.deinit(); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); // Two lines more above it than the patch knows of. @@ -682,16 +898,17 @@ test "a hunk the file has moved since is found where it went, inside its declara \\ b(); \\ ; - const result = try format(p, dir, patch); - defer p.gpa.free(result.content); - defer locations.freeRows(p.gpa, result.rows); + const result = try format(&t.ctx, dir, patch); + defer testing.allocator.free(result.content); + defer locations.freeRows(testing.allocator, result.rows); try testing.expect(std.mem.indexOf(u8, result.content, "a.zig:3\n const S = struct {\na.zig:5 *\n") != null); try testing.expect(std.mem.indexOf(u8, result.content, "git's guess") == null); } test "a mailed patch keeps its headers, message and diffstat above its hunks" { - const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); - defer p.deinit(); + var t: TestCtx = undefined; + t.init(); + defer t.deinit(); const patch = \\From 0123 Mon Sep 17 00:00:00 2001 \\Subject: [PATCH] change x @@ -709,9 +926,9 @@ test "a mailed patch keeps its headers, message and diffstat above its hunks" { \\+b \\ ; - const result = try format(p, "/pardes-surely-missing-dir", patch); - defer p.gpa.free(result.content); - defer locations.freeRows(p.gpa, result.rows); + const result = try format(&t.ctx, "/pardes-surely-missing-dir", patch); + defer testing.allocator.free(result.content); + defer locations.freeRows(testing.allocator, result.rows); try testing.expectEqualStrings("From 0123 Mon Sep 17 00:00:00 2001\nSubject: [PATCH] change x\n\nWhy it changed.\n---\n x.txt | 2 +-\n\nx.txt:1\n-a\n+b\n", result.content); } @@ -755,8 +972,9 @@ test "a .patch looked at opens its +Diff, and Diff goes to the text and back" { test "a hunk edited since, beside siblings with its signature's tail, is found in its own function" { if (!syntax.supportsPath("a.rs")) return error.SkipZigTest; - const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); - defer p.deinit(); + var t: TestCtx = undefined; + t.init(); + defer t.deinit(); var tmp = testing.tmpDir(.{}); defer tmp.cleanup(); // Three functions ending in one signature's tail; the patch is for the @@ -799,9 +1017,9 @@ test "a hunk edited since, beside siblings with its signature's tail, is found i \\ c \\ ; - const result = try format(p, dir, patch); - defer p.gpa.free(result.content); - defer locations.freeRows(p.gpa, result.rows); + const result = try format(&t.ctx, dir, patch); + defer testing.allocator.free(result.content); + defer locations.freeRows(testing.allocator, result.rows); try testing.expect(std.mem.indexOf(u8, result.content, "a.rs:12\n fn three(\na.rs:15 *\n") != null); } @@ -837,3 +1055,13 @@ test "patch panes keep different commits and reuse only the same commit" { try testing.expectEqual(first, try Page.open(p, a)); try testing.expectEqualStrings(original, p.panes[first].?.file.?.content); } + +test "a commit hash is 7 to 40 lowercase hex digits with a letter and a digit" { + try std.testing.expect(isCommitHash("9bffa7041c")); + try std.testing.expect(isCommitHash("9bffa7041cd2e8a0b6b1f7c3e4d5a6b7c8d9e0f1")); + try std.testing.expect(!isCommitHash("9bffa7")); + try std.testing.expect(!isCommitHash("defaced")); + try std.testing.expect(!isCommitHash("1234567")); + try std.testing.expect(!isCommitHash("0x9bffa7041c")); + try std.testing.expect(!isCommitHash("9BFFA7041C")); +} diff --git a/src/layout.zig b/src/layout.zig index 73114e45..dfbea067 100644 --- a/src/layout.zig +++ b/src/layout.zig @@ -180,8 +180,8 @@ pub fn columnDrop(p: *const Pardes, source: usize, x: u16, grab: u16) ColumnDrop } /// Share out the width of columns `left` and `left + 1` so the left one is -/// `left_width` cells, neither below MINW. A border drag and a column grip -/// dropped inside its own place both end here. +/// `left_width` cells, neither below MINW. A column grip dropped inside its +/// own place ends here. pub fn setColumnPairWidth(p: *Pardes, left: usize, left_width: u64) void { const v = p.view(); if (left + 1 >= v.ncol) return; @@ -2099,15 +2099,7 @@ test "repeated non-dyadic column splits preserve every unrelated boundary" { try std.testing.expect(splitColumn(p, 0, 1, false)); p.sync(); - const handle = p.view().col_x[0] + p.view().col_w[0] - 1; - const untouched = weightsOf(p); - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = TOPBAR_H + 1 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle, .row = TOPBAR_H + 1 } }); - try std.testing.expectEqual(untouched, weightsOf(p)); - - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = TOPBAR_H + 1 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = 417, .row = TOPBAR_H + 1 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = 417, .row = TOPBAR_H + 1 } }); + setColumnPairWidth(p, 0, 418); p.sync(); try std.testing.expectEqual(@as(u16, 418), p.view().rects[0].w); diff --git a/src/lib_syntax.zig b/src/lib_syntax.zig index 395a02f0..a25af884 100644 --- a/src/lib_syntax.zig +++ b/src/lib_syntax.zig @@ -51,6 +51,25 @@ pub const SourceAnalysis = syntax.SourceAnalysis; pub const ContextDeclaration = syntax.ContextDeclaration; pub const analyzeSource = syntax.analyzeSource; +/// A unified diff as a language: `diff` walks one a line at a time +/// (`Walk`: a line's kind, the file its section names, the hunk's line +/// numbers) and says what a row of it points at (`targetAt`); +/// `highlightDiff` is a style byte for each byte of `content[start..end]`, +/// the caller's to free: headers as comments, `@@` lines as keywords, each +/// hunk's code in the language of the file its section names (old and new +/// side each parsed whole), and over that an added or removed line's +/// grounds (`ground_add`, `ground_del`; its first byte `ground_emph`, the +/// strong row). A byte's low bits (`syn_bits`) are a `Syn`; `Grounds` are +/// a theme's colours for the rest. +pub const diff = @import("diff.zig"); +pub const highlightDiff = syntax.highlightDiff; +pub const syn_bits = syntax.syn_bits; +pub const ground_add = syntax.ground_add; +pub const ground_del = syntax.ground_del; +pub const ground_emph = syntax.ground_emph; +pub const ground_line = syntax.ground_line; +pub const Grounds = colors.Grounds; + /// The tree-sitter bindings a tree is read through: `tree.rootNode()`, and /// a node's `kind()`, `startByte()`, `endByte()`, `child(i)`, `parent()`. pub const ts = syntax.ts; diff --git a/src/locations.zig b/src/locations.zig index fc39f92d..ca6b7a7d 100644 --- a/src/locations.zig +++ b/src/locations.zig @@ -103,6 +103,135 @@ pub fn equalRows(a: []const Row, b: []const Row) bool { return true; } +// ---- rows as text: a pane's `rows` file (ninep/pane.zig) ---- + +/// Rows as text, a line a row, its fields one blank apart and its path +/// last (a path may hold blanks): its kind (`m` a match n/N step to, `c` +/// context, `p` a preview of source; then `d` when it is a declaration and +/// `u` when its occurrence is not marked), its place (line, col, end_line, +/// end_col; 0 for none), source_column, location_end and code_start (byte +/// offsets in its line), its styles and its path. Styles are `-` for none, +/// else how many bytes they cover from code_start, a colon and the runs +/// that are not plain, `start+len=role`, comma-separated: a role is a +/// syntax class (keyword string number comment) and grounds (add del emph +/// line, syntax.ground_add's), joined by dots. `p 12 0 0 0 0 0 0 +/// 9:0+1=add.line,5+3=keyword.add src/a.zig`. +pub fn formatRows(rows: []const Row, w: *std.Io.Writer) std.Io.Writer.Error!void { + for (rows) |r| { + try w.writeByte(switch (r.kind) { + .match => 'm', + .context => 'c', + .preview => 'p', + }); + if (r.declaration) try w.writeByte('d'); + if (!r.mark_occurrence) try w.writeByte('u'); + try w.print(" {d} {d} {d} {d} {d} {d} {d} ", .{ r.at.line, r.at.col, r.at.end_line, r.at.end_col, r.source_column, r.location_end, r.code_start }); + if (r.colors.len == 0) try w.writeByte('-') else try w.print("{d}:", .{r.colors.len}); + var sep = false; + var at: usize = 0; + while (at < r.colors.len) { + const style = r.colors[at]; + var end = at + 1; + while (end < r.colors.len and r.colors[end] == style) end += 1; + defer at = end; + if (style == 0) continue; + if (sep) try w.writeByte(','); + sep = true; + try w.print("{d}+{d}=", .{ at, end - at }); + var dot = false; + const syn = style & syntax.syn_bits; + if (syn != 0) { + if (std.enums.fromInt(syntax.Syn, syn)) |known| try w.writeAll(@tagName(known)) else try w.print("{d}", .{syn}); + dot = true; + } + for (grounds) |g| if (style & g[0] != 0) { + if (dot) try w.writeByte('.'); + try w.writeAll(g[1]); + dot = true; + }; + } + try w.print(" {s}\n", .{r.path}); + } +} + +const grounds = [_]struct { u8, []const u8 }{ .{ syntax.ground_add, "add" }, .{ syntax.ground_del, "del" }, .{ syntax.ground_emph, "emph" }, .{ syntax.ground_line, "line" } }; + +/// formatRows' text read back, the rows and all they own `arena`'s. +/// BadRows for a line that is not one; a last newline ends the last row. +pub fn parseRows(arena: std.mem.Allocator, text: []const u8) error{ OutOfMemory, BadRows }![]Row { + const body = if (std.mem.endsWith(u8, text, "\n")) text[0 .. text.len - 1] else text; + if (body.len == 0) return &.{}; + var rows: std.ArrayList(Row) = .empty; + var lines = std.mem.splitScalar(u8, body, '\n'); + while (lines.next()) |line| { + var fields: [9][]const u8 = undefined; + var at: usize = 0; + for (&fields) |*field| { + const blank = std.mem.indexOfScalarPos(u8, line, at, ' ') orelse return error.BadRows; + field.* = line[at..blank]; + at = blank + 1; + } + const kind = fields[0]; + if (kind.len == 0) return error.BadRows; + var row: Row = .{ + .kind = switch (kind[0]) { + 'm' => .match, + 'c' => .context, + 'p' => .preview, + else => return error.BadRows, + }, + .path = try arena.dupe(u8, line[at..]), + .at = .{}, + .location_end = 0, + .code_start = 0, + }; + for (kind[1..]) |flag| switch (flag) { + 'd' => row.declaration = true, + 'u' => row.mark_occurrence = false, + else => return error.BadRows, + }; + var numbers: [7]usize = undefined; + for (&numbers, fields[1..8]) |*n, field| n.* = std.fmt.parseInt(usize, field, 10) catch return error.BadRows; + row.at = .{ .line = numbers[0], .col = numbers[1], .end_line = numbers[2], .end_col = numbers[3] }; + row.source_column = numbers[4]; + row.location_end = numbers[5]; + row.code_start = numbers[6]; + const styles = fields[8]; + if (!std.mem.eql(u8, styles, "-")) { + const colon = std.mem.indexOfScalar(u8, styles, ':') orelse return error.BadRows; + const len = std.fmt.parseInt(usize, styles[0..colon], 10) catch return error.BadRows; + // A line is never longer than a file: bounded before it is made. + if (len > @import("memory.zig").limits.max_file_bytes) return error.BadRows; + row.colors = try arena.alloc(u8, len); + @memset(row.colors, 0); + var runs = std.mem.splitScalar(u8, styles[colon + 1 ..], ','); + while (runs.next()) |run| { + if (run.len == 0) continue; + const plus = std.mem.indexOfScalar(u8, run, '+') orelse return error.BadRows; + const eq = std.mem.indexOfScalarPos(u8, run, plus, '=') orelse return error.BadRows; + const start = std.fmt.parseInt(usize, run[0..plus], 10) catch return error.BadRows; + const n = std.fmt.parseInt(usize, run[plus + 1 .. eq], 10) catch return error.BadRows; + if (start > len or n > len - start) return error.BadRows; + var style: u8 = 0; + var names = std.mem.splitScalar(u8, run[eq + 1 ..], '.'); + names: while (names.next()) |name| { + for (grounds) |g| if (std.mem.eql(u8, name, g[1])) { + style |= g[0]; + continue :names; + }; + if (style & syntax.syn_bits != 0) return error.BadRows; + const syn: u8 = if (std.meta.stringToEnum(syntax.Syn, name)) |known| @backingInt(known) else std.fmt.parseInt(u4, name, 10) catch return error.BadRows; + if (syn == 0) return error.BadRows; + style |= syn; + } + @memset(row.colors[start..][0..n], style); + } + } + try rows.append(arena, row); + } + return rows.items; +} + /// Compare native producer rows with an already formatted, context-free view. /// Identical refreshes retain allocations, syntax and selection state. pub fn sameInput(input: []const u8, rendered: []const u8, rows: []const Row, layout: Config.Layout) bool { @@ -984,3 +1113,50 @@ test "locations cache transfers oversized completed analysis without reparsing" try std.testing.expectEqual(@as(usize, 0), cache.len); try std.testing.expectEqual(@as(usize, 0), cache.bytes); } + +test "rows read back from their text are the rows: +Search's, +Callstack's and +Diff's" { + const testing = std.testing; + const p = try pardes.Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = "const S = struct {\n fn f() void {\n a(\"x y\");\n b();\n }\n};\n" }); + var buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const dir = buf[0..try tmp.dir.realPath(testing.io, &buf)]; + const patch = try std.Io.Dir.path.join(testing.allocator, &.{ dir, "c.patch" }); + defer testing.allocator.free(patch); + const search = try format(p, dir, "a.zig:3:9 a(\"x y\");\na.zig:4:9 b();\n", null, true); + defer p.gpa.free(search.content); + defer freeRows(p.gpa, search.rows); + const callstack = try formatCallstack(p, dir, "a.zig:2:8 f\n└─ a.zig:3:9 a\n"); + defer p.gpa.free(callstack.content); + defer freeRows(p.gpa, callstack.rows); + const hid = try @import("hunks.zig").openDiff(p, 0, patch, "--- a.zig\n+++ a.zig\n@@ -2,3 +2,4 @@\n fn f() void {\n- a(\"x\");\n+ a(\"x y\");\n+ b();\n }\n"); + const stacked = p.panes[hid].?.file.?.location_rows; + // A +Diff's rows carry styles with grounds: the codec is tried on them. + var grounded = false; + for (stacked) |row| for (row.colors) |c| { + grounded = grounded or c & syntax.ground_add != 0; + }; + try testing.expect(grounded and search.rows.len > 0 and callstack.rows.len > 0); + var arena_state: std.heap.ArenaAllocator = .init(testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + for ([_][]const Row{ search.rows, callstack.rows, stacked }) |rows| { + var text: std.Io.Writer.Allocating = .init(arena); + try formatRows(rows, &text.writer); + const back = try parseRows(arena, text.written()); + try testing.expect(equalRows(rows, back)); + var again: std.Io.Writer.Allocating = .init(arena); + try formatRows(back, &again.writer); + try testing.expectEqualStrings(text.written(), again.written()); + } + try testing.expectError(error.BadRows, parseRows(arena, "x 1 0 0 0 0 0 0 - a\n")); + try testing.expectError(error.BadRows, parseRows(arena, "m 1 0 0 0 0 0 0 2:0+3=keyword a\n")); + try testing.expectError(error.BadRows, parseRows(arena, "m 1 0 0 0 0 0 0 2:0+1=keyword.string a\n")); + try testing.expectError(error.BadRows, parseRows(arena, "m 1 0 0\n")); + const one = try parseRows(arena, "pd 12 3 0 0 0 0 0 4:0+1=add.line,1+2=keyword.add src/a b.zig\n"); + try testing.expectEqualStrings("src/a b.zig", one[0].path); + try testing.expect(one[0].declaration and one[0].kind == .preview and one[0].at.line == 12 and one[0].at.col == 3); + try testing.expectEqualSlices(u8, &.{ syntax.ground_add | syntax.ground_line, @backingInt(syntax.Syn.keyword) | syntax.ground_add, @backingInt(syntax.Syn.keyword) | syntax.ground_add, 0 }, one[0].colors); +} diff --git a/src/look.zig b/src/look.zig index 082565ed..115e3683 100644 --- a/src/look.zig +++ b/src/look.zig @@ -4,6 +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 config = @import("config.zig"); const diff = @import("diff.zig"); const platform_has_fs = filesystem.platform_has_fs; @@ -1089,7 +1090,7 @@ 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 (lookCommit(p, id, pane, trimmed)) 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; @@ -1110,38 +1111,6 @@ fn lookUnresolved(p: *Pardes, id: usize, pane: *Pane, trimmed: []const u8, text: } } -/// A commit hash (7 to 40 hex digits, a letter and a digit among them) -/// 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. -fn lookCommit(p: *Pardes, id: usize, pane: *Pane, word: []const u8) bool { - if (!isCommitHash(word)) return false; - var dir = 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 (exec.kindOf(dot_git) != null) break; - dir = std.Io.Dir.path.dirname(dir) orelse return false; - } - var line: [64]u8 = undefined; - const dst = exec.execute(p, id, std.fmt.bufPrint(&line, "git show {s}", .{word}) catch return false) orelse return true; - if (p.panes[dst]) |c| c.command_pages = true; - return true; -} - -fn isCommitHash(word: []const u8) bool { - if (word.len < 7 or word.len > 40) return false; - var digit = false; - var letter = false; - for (word) |c| switch (c) { - '0'...'9' => digit = true, - 'a'...'f' => letter = true, - else => return false, - }; - return digit and letter; -} - /// Opens (or finds) `path` as Look would, `id`'s own pane when it is empty, /// and selects what `expr` addresses there from its dot. An address that /// does not evaluate moves nothing and says why (acme: no jump). @@ -1390,18 +1359,32 @@ pub fn diffAddress(pane: *const Pane, lines: []const []const u8, row: usize, buf return target.address(buf); } -/// What a click at byte `col` of line `row` of a diff pane takes, the one -/// answer for every way a click arrives (a mouse click, a 9P look of the -/// whole line, an empty look or exec written back to `event`): a file or -/// hunk header anywhere, or a hunk line on its `+`/`-`/` ` prefix, is the -/// address the line names (diffAddress); a hunk line's code is words, from -/// `word_from` on, the prefix never one of them. Null when the pane shows -/// no diff or the line is no part of one. -pub const DiffClick = struct { address: ?[]const u8 = null, word_from: usize = 0 }; +/// What a click at byte `col` of line `row` of a diff pane takes: a file +/// or hunk header anywhere, or a hunk line on its `+`/`-`/` ` prefix, is +/// the address the line names (diffAddress); a hunk line's code is words, +/// from `word_from` on, the prefix never one of them. Null when the line is +/// no part of a diff. +const DiffClick = struct { address: ?[]const u8 = null, word_from: usize = 0 }; + +/// What a click at byte `col` of row `row` takes, the one answer for every +/// way a click arrives (the mouse, exec.operandAt; an empty look written +/// back to `event`, events.expandAt; a whole line written to `look`): the +/// address a row's producer gave it (a query pane's row on its address, +/// Query.rowAddress), else the one the pane's language reads in the line (a +/// diff's: diffClickIn); or where its words start, the address no part of +/// them. `line` is the row's text it was read from, and the address's text +/// in it ends at `end`. Null for a row that names no address. +pub const RowAddress = struct { address: ?[]const u8 = null, word_from: usize = 0, line: []const u8, end: usize }; -pub fn diffClick(p: *Pardes, pane: *Pane, row: usize, col: usize, buf: []u8) ?DiffClick { +pub fn rowAddressAt(p: *Pardes, pane: *Pane, row: usize, col: usize, buf: []u8) ?RowAddress { + if (panes.Query.rowAddress(pane, row, col, buf)) |address| { + const f = &pane.file.?; + return .{ .address = address, .line = modal.lineSlice(f.content, row), .end = f.location_rows[row].location_end }; + } const lines = diffLines(p, pane) orelse return null; - return diffClickIn(pane, lines, row, col, buf); + if (row >= lines.len) return null; + const click = diffClickIn(pane, lines, row, col, buf) orelse return null; + return .{ .address = click.address, .word_from = click.word_from, .line = lines[row], .end = lines[row].len }; } fn diffClickIn(pane: *const Pane, lines: []const []const u8, row: usize, col: usize, buf: []u8) ?DiffClick { @@ -1417,18 +1400,19 @@ fn diffClickIn(pane: *const Pane, lines: []const []const u8, row: usize, col: us return .{ .address = address }; } -/// A look written over 9P of a whole line of a diff pane (the cursor's line -/// first, then the first after it): what a click on its first column takes. +/// A look written over 9P of a whole line of a pane whose rows name +/// addresses (a diff's, a query pane's: rowAddressAt), the cursor's line +/// first, then the first after it: what a click on its first column takes. /// A blank context line (` `) is a line too. -fn diffLineAddress(p: *Pardes, pane: *Pane, operand: []const u8, buf: []u8) ?[]const u8 { +fn lineAddress(p: *Pardes, pane: *Pane, operand: []const u8, buf: []u8) ?[]const u8 { const text = std.mem.trimEnd(u8, operand, "\r\n"); if (text.len == 0) return null; - const lines = diffLines(p, pane) orelse return null; + const lines = (if (pane.query != null) panes.File.cursorLines(p.scratch.allocator(), pane, &pane.file.?) catch null else diffLines(p, pane)) orelse return null; const cur: usize = @intCast(@max(0, pane.body.cur_row)); for (0..lines.len) |k| { const i = (cur + k) % lines.len; if (std.mem.eql(u8, std.mem.trimEnd(u8, lines[i], "\r"), text)) - return (diffClickIn(pane, lines, i, 0, buf) orelse return null).address; + return (rowAddressAt(p, pane, i, 0, buf) orelse return null).address; } return null; } @@ -1524,7 +1508,7 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { // A whole line of a diff written over 9P (a context line ` Del` // included) is a look at the address it names, never the word run. var diff_buf: [4096 + 32]u8 = undefined; - const looked: []const u8 = diffLineAddress(p, pane, operand_raw, &diff_buf) orelse looked: { + const looked: []const u8 = lineAddress(p, pane, operand_raw, &diff_buf) orelse looked: { if (config.commandWord(command)) |cmd| { if (exec.execute(p, id, cmd)) |dst| v.active = dst; return; @@ -1619,18 +1603,7 @@ 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)) { - // A .diff or .patch looked at bare: its hunks stacked in a - // +Diff, which takes the keyboard as the file would; one - // with none in it opens as text. - if (!p.look_text and target.at.line == 0 and - (std.mem.endsWith(u8, target.path, ".diff") or std.mem.endsWith(u8, target.path, ".patch"))) - if (filesystem.read(p, target.path)) |bytes| { - defer p.gpa.free(bytes); - if (panes.Output.openDiff(p, id, target.path, bytes)) |hid| { - v.active = hid; - return; - } else |_| {} - } else |_| {}; + 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); @@ -1900,15 +1873,6 @@ test "a zero column after a path is found, in every spelling a look takes" { for ([_][]const u8{ "", ":3", ":3:1", ":3:2-5", ":3:2-5:7", ":30:10" }) |rest| try std.testing.expect(!zeroColumn(rest)); } -test "a commit hash is 7 to 40 lowercase hex digits with a letter and a digit" { - try std.testing.expect(isCommitHash("9bffa7041c")); - try std.testing.expect(isCommitHash("9bffa7041cd2e8a0b6b1f7c3e4d5a6b7c8d9e0f1")); - try std.testing.expect(!isCommitHash("9bffa7")); - try std.testing.expect(!isCommitHash("defaced")); - try std.testing.expect(!isCommitHash("1234567")); - try std.testing.expect(!isCommitHash("0x9bffa7041c")); - try std.testing.expect(!isCommitHash("9BFFA7041C")); -} test "Look hover waits without mutating the pane and input cancels it" { const delay = config.look_preview_delay_frames; @@ -2331,7 +2295,7 @@ test "a click, a 9P whole-line look and an empty event write-back take one expan if (at.whole_line) { const lines = diffLines(p, pane).?; var buf: [4096 + 32]u8 = undefined; - const whole = diffLineAddress(p, pane, lines[at.row], &buf) orelse return error.NoWholeLineAddress; + const whole = lineAddress(p, pane, lines[at.row], &buf) orelse return error.NoWholeLineAddress; try std.testing.expectEqualStrings(at.want, whole); } } diff --git a/src/mouse.zig b/src/mouse.zig index 06f3a755..a5ea9bed 100644 --- a/src/mouse.zig +++ b/src/mouse.zig @@ -1,6 +1,5 @@ //! The mouse: what a pointer is over, the three buttons' presses, drags and -//! releases (acme's chords, border and seam drags, gestures), and the -//! chrome targets a shell asks about. +//! releases (acme's chords, grip and seam drags, gestures). const pardes = @import("pardes.zig"); const tagline = @import("tagline.zig"); const exec = @import("exec.zig"); @@ -19,7 +18,6 @@ const Pane = panes.Pane; const MAX_PANES = pardes.MAX_PANES; const Layer = @import("Layer.zig"); const Jump = @import("Jump.zig"); -const TOPBAR_H = pardes.TOPBAR_H; const BOX_H = pardes.BOX_H; const TAG_TEXT_INSET = pardes.TAG_TEXT_INSET; const Builtin = pardes.Builtin; @@ -29,7 +27,6 @@ const Pardes = pardes.Pardes; pub const Drag = union(enum) { none, - border_v: struct { left_col: usize, cur_x: u16, corner: ?struct { col: usize, idx: usize } = null, cur_y: u16 = 0 }, border_h: struct { col: usize, top_idx: usize, cur_y: u16 }, move: struct { id: usize, cur_x: u16, cur_y: u16 }, /// `grab`: how far into the grip it was pressed, so the column's left @@ -58,7 +55,7 @@ pub const Drag = union(enum) { fn button(drag: Drag) ?Mouse.Button { return switch (drag) { .none => null, - .border_v, .border_h, .move, .column_move => config.select_button, + .border_h, .move, .column_move => config.select_button, .select => |selection| selection.button, }; } @@ -126,38 +123,6 @@ fn seamRowOf(p: *const Pardes, c: usize, k: usize) u16 { return r.y + r.h -| 1; } -pub const ChromeTarget = struct { col: u16, row: u16 }; - -/// The chrome a press at `col`, `row` takes: the tag rows; then, -/// on the cell, a pane's grip, a column's handle or a seam; then a cell -/// away, any of a pane's tag, a handle or a seam. -pub fn chromeTarget(p: *const Pardes, col: u16, row: u16) ?ChromeTarget { - const v = p.view(); - if (row < p.topBarHeight() + layout.columnBarHeight(p)) return .{ .col = col, .row = row }; - for ([_]u16{ 0, 1 }) |slack| { - for (p.panes, 0..) |slot, id| { - const pane = slot orelse continue; - const rect = v.rects[id]; - const tag = p.tagTop(pane, rect); - const edge = if (slack == 0) rect.x + config.GUTTER else rect.x + rect.w; - if (row >= tag and row < tag + pane.tag_rows and col >= rect.x and col < rect.x + rect.w and col < edge) - return .{ .col = col, .row = row }; - } - for (0..p.view().ncol -| 1) |column| { - const handle = v.col_x[column] + v.col_w[column] -| 1; - if (@max(col, handle) - @min(col, handle) == slack) return .{ .col = handle, .row = row }; - } - for (0..p.view().ncol) |column| { - if (col < v.col_x[column] or col >= v.col_x[column] + v.col_w[column]) continue; - for (0..p.view().cols[column].n -| 1) |index| { - const seam = seamRowOf(p, column, index); - if (@max(row, seam) - @min(row, seam) == slack) return .{ .col = col, .row = seam }; - } - } - } - return null; -} - pub fn paneAt(p: *const Pardes, col: u16, row: u16) ?usize { for (p.panes, 0..) |slot, id| { if (slot == null) continue; @@ -781,18 +746,6 @@ pub fn handleMouse(p: *Pardes, event: Mouse) void { return; } } - for (0..p.view().ncol -| 1) |c| { - if (mcol == v.col_x[c] + v.col_w[c] -| 1) { - const corner: @FieldType(@FieldType(Drag, "border_v"), "corner") = if (seamIdxAt(p, c, mrow)) |k| - .{ .col = c, .idx = k } - else if (seamIdxAt(p, c + 1, mrow)) |k| - .{ .col = c + 1, .idx = k } - else - null; - v.drag = .{ .border_v = .{ .left_col = c, .cur_x = mcol, .corner = corner, .cur_y = mrow } }; - return; - } - } // Two panes are resized on the rule between them, never on a // row of text; with no rule, by the grip, as acme moves a // window by its button. @@ -923,12 +876,6 @@ fn seamIdxAt(p: *const Pardes, c: usize, mrow: u16) ?usize { return null; } -fn clampBorderCol(lx: u16, lw: u16, rw: u16, mcol: u16) u16 { - const lo = lx + config.MINW; - const hi = lx +| lw +| rw -| config.MINW; - return if (lo <= hi) std.math.clamp(mcol, lo, hi) else mcol; -} - fn clampBorderRow(ay: u16, ah: u16, bh: u16, mrow: u16) u16 { const lo = ay + BOX_H - 1; const hi = ay +| ah +| bh -| (BOX_H + 1); @@ -938,20 +885,6 @@ fn clampBorderRow(ay: u16, ah: u16, bh: u16, mrow: u16) u16 { pub fn dragUpdate(p: *Pardes, mcol: u16, mrow: u16, body_hit: ?Mouse.BodyHit) void { const v = p.view(); switch (v.drag) { - .border_v => |*d| { - const c = d.left_col; - d.cur_x = if (c + 1 < v.ncol) - clampBorderCol(v.col_x[c], v.col_w[c], v.col_w[c + 1], mcol) - else - mcol; - if (d.corner) |k| if (k.idx + 1 < v.cols[k.col].n) { - const a = v.rects[v.cols[k.col].panes[k.idx]]; - const b = v.rects[v.cols[k.col].panes[k.idx + 1]]; - d.cur_y = clampBorderRow(a.y, a.h, b.h, mrow); - } else { - d.cur_y = mrow; - }; - }, .border_h => |*d| { const cc = d.col; const k = d.top_idx; @@ -1239,18 +1172,6 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { defer v.drag = .none; defer v.chord_hold = false; switch (v.drag) { - .border_v => |d| { - const c = d.left_col; - const old_seam = v.col_x[c] + v.col_w[c] -| 1; - // the handle is the left pane's LAST column (inclusive), so - // the new width includes it — a no-drag click changes nothing - if (c + 1 < v.ncol and d.cur_x != old_seam) - layout.setColumnPairWidth(p, c, (d.cur_x + 1) -| v.col_x[c]); - if (d.corner) |k| { - if (d.cur_y != seamRowOf(p, k.col, k.idx)) - layout.applyRowSplit(p, k.col, k.idx, d.cur_y); - } - }, .border_h => |d| if (d.cur_y != seamRowOf(p, d.col, d.top_idx)) layout.applyRowSplit(p, d.col, d.top_idx, d.cur_y), .column_move => |d| if (layout.columnBySerial(p, d.serial)) |column| switch (layout.columnDrop(p, column, d.cur_x, d.grab)) { @@ -1391,7 +1312,7 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { const test_metrics: pardes.RowMetrics = .{ .body_w = 10, .body_h = 20, .tagline_w = 6, .tagline_h = 12 }; -fn cornerFixture(gpa: std.mem.Allocator) !*Pardes { +fn twoColumns(gpa: std.mem.Allocator) !*Pardes { const p = try Pardes.init(gpa, .{ .cols = 100, .rows = 30, .shells = 3 }); p.update(.{ .resize = .{ .cols = 100, .rows = 30 } }); p.view().active = p.view().cols[1].panes[0]; @@ -1463,7 +1384,7 @@ fn layerCenter(layer: *const Layer, col: u16, comptime tag: bool) [2]f32 { } test "a pane's last row of text is no resize handle; the rule over the next pane is" { - const p = try cornerFixture(std.testing.allocator); + const p = try twoColumns(std.testing.allocator); defer p.deinit(); const seam = seamRowOf(p, 1, 0); const inside = p.view().col_x[1] + p.view().col_w[1] / 2; @@ -1473,8 +1394,22 @@ test "a pane's last row of text is no resize handle; the rule over the next pane try std.testing.expect(nudgeRightSeam(p, 2) == seam + 2); } +test "the line between two columns is no resize handle: a press there is a sweep in the pane" { + const p = try twoColumns(std.testing.allocator); + defer p.deinit(); + const line = p.view().col_x[0] + p.view().col_w[0] - 1; + const row = p.view().rects[p.view().cols[0].panes[0]].y + BOX_H + 1; + const weight = p.view().cols[0].weight; + p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = line, .row = row } }); + try std.testing.expect(p.view().drag == .select); + p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = line + 8, .row = row } }); + p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = line + 8, .row = row } }); + p.sync(); + try std.testing.expectEqual(weight, p.view().cols[0].weight); +} + test "a pane's grip dragged up or down its own column moves its top, down to the floor of the pane above" { - const p = try cornerFixture(std.testing.allocator); + const p = try twoColumns(std.testing.allocator); defer p.deinit(); const upper = p.view().cols[1].panes[0]; const lower = p.view().cols[1].panes[1]; @@ -1499,26 +1434,6 @@ test "a pane's grip dragged up or down its own column moves its top, down to the try std.testing.expectEqual(to, p.view().rects[lower].y); } -test "a press near chrome takes it: the tag rows, a column's handle or a seam on its cell or a cell away, a pane's tag; nothing in a body" { - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - // Column 0's two panes share its rows evenly; column 1's lower one is - // tall, its middle a body row. - const handle = p.view().col_x[0] + p.view().col_w[0] - 1; - const seam = seamRowOf(p, 0, 0); - const mid = p.view().col_x[0] + p.view().col_w[0] / 2; - const top = p.view().rects[p.view().cols[0].panes[0]].y; - const low = p.view().rects[p.view().cols[1].panes[1]]; - const body = low.y + low.h / 2; - try std.testing.expectEqual(ChromeTarget{ .col = 5, .row = 0 }, chromeTarget(p, 5, 0).?); - try std.testing.expectEqual(ChromeTarget{ .col = handle, .row = body }, chromeTarget(p, handle, body).?); - try std.testing.expectEqual(ChromeTarget{ .col = handle, .row = body }, chromeTarget(p, handle + 1, body).?); - try std.testing.expectEqual(ChromeTarget{ .col = mid, .row = seam }, chromeTarget(p, mid, seam).?); - try std.testing.expectEqual(ChromeTarget{ .col = mid, .row = seam }, chromeTarget(p, mid, seam - 1).?); - try std.testing.expectEqual(ChromeTarget{ .col = mid, .row = top }, chromeTarget(p, mid, top).?); - try std.testing.expect(chromeTarget(p, mid, seam - 3) == null); -} - test "plain left click clears explicit modal selection" { const gpa = std.testing.allocator; // Wide enough for the tag on one row: the body starts under it. @@ -1558,144 +1473,6 @@ test "a selection drag and its release leave the selection done" { try std.testing.expectEqual(.done, pane.sel[sel_slot].state); } -test "a corner drag's two axes clamp independently" { - // a 100-wide window split 50/50, and a 30-row column split 15/14 under the - // topbar: the shape windowops.snap drives - const lx: u16 = 0; - const lw: u16 = 50; - const rw: u16 = 50; - const ay: u16 = TOPBAR_H; - const ah: u16 = 15; - const bh: u16 = 14; - const row_lo: u16 = ay + BOX_H - 1; - const row_hi: u16 = ay + ah + bh - (BOX_H + 1); - - // each axis alone, at both walls - try std.testing.expectEqual(@as(u16, config.MINW), clampBorderCol(lx, lw, rw, 0)); - try std.testing.expectEqual(@as(u16, 100 - config.MINW), clampBorderCol(lx, lw, rw, 999)); - try std.testing.expectEqual(row_lo, clampBorderRow(ay, ah, bh, 0)); - try std.testing.expectEqual(row_hi, clampBorderRow(ay, ah, bh, 999)); - - // THE corner property: drag off the right edge while staying mid-height — - // x sits at its wall, y still tracks the mouse row exactly - try std.testing.expectEqual(@as(u16, 100 - config.MINW), clampBorderCol(lx, lw, rw, 999)); - try std.testing.expectEqual(@as(u16, 12), clampBorderRow(ay, ah, bh, 12)); - // and the mirror: pinned at the bottom, x still free - try std.testing.expectEqual(row_hi, clampBorderRow(ay, ah, bh, 999)); - try std.testing.expectEqual(@as(u16, 40), clampBorderCol(lx, lw, rw, 40)); - // both pinned at once is just both walls, not a stuck gesture - try std.testing.expectEqual(@as(u16, config.MINW), clampBorderCol(lx, lw, rw, 0)); - try std.testing.expectEqual(row_hi, clampBorderRow(ay, ah, bh, 999)); - - // degenerate pairs pass through untouched, each on its own terms: a pane - // pair with no room stays draggable even when the column pair has room - try std.testing.expectEqual(@as(u16, 7), clampBorderCol(0, 5, 5, 7)); - try std.testing.expectEqual(@as(u16, 40), clampBorderCol(lx, lw, rw, 40)); - try std.testing.expectEqual(@as(u16, 9), clampBorderRow(TOPBAR_H, 1, 0, 9)); -} - -test "a v-handle press at the RIGHT column's seam drags both boundaries" { - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - try std.testing.expectEqual(@as(usize, 2), p.view().cols[1].n); - - const handle = p.view().col_x[0] + p.view().col_w[0] - 1; - const right_seam = nudgeRightSeam(p, 3); - try std.testing.expect(right_seam != seamRowOf(p, 0, 0)); - - const w0 = p.view().cols[0].weight; - const v_left = p.panes[p.view().cols[0].panes[0]].?.vweight; - const v_right = p.panes[p.view().cols[1].panes[0]].?.vweight; - - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = right_seam } }); - try std.testing.expect(p.view().drag == .border_v); - const corner = p.view().drag.border_v.corner orelse return error.NoCorner; - try std.testing.expectEqual(@as(usize, 1), corner.col); - try std.testing.expectEqual(@as(usize, 0), corner.idx); - - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle + 8, .row = right_seam - 4 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle + 8, .row = right_seam - 4 } }); - p.sync(); - - // both halves committed: the column pair widened, and the RIGHT column's - // pane pair reweighted — while the left column's panes stayed put - try std.testing.expect(p.view().cols[0].weight > w0); - try std.testing.expect(p.panes[p.view().cols[1].panes[0]].?.vweight != v_right); - try std.testing.expectEqual(v_left, p.panes[p.view().cols[0].panes[0]].?.vweight); -} - -test "a tie row still moves the LEFT column's pane pair only" { - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - - // put column 1's seam exactly on column 0's, the row the eye reads as one - // line across the whole window - const left_seam = seamRowOf(p, 0, 0); - _ = nudgeRightSeam(p, @as(i32, left_seam) - @as(i32, seamRowOf(p, 1, 0))); - try std.testing.expectEqual(left_seam, seamRowOf(p, 1, 0)); - - const handle = p.view().col_x[0] + p.view().col_w[0] - 1; - const v_left = p.panes[p.view().cols[0].panes[0]].?.vweight; - const v_right = p.panes[p.view().cols[1].panes[0]].?.vweight; - - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = left_seam } }); - const corner = p.view().drag.border_v.corner orelse return error.NoCorner; - try std.testing.expectEqual(@as(usize, 0), corner.col); - - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle, .row = left_seam - 4 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle, .row = left_seam - 4 } }); - p.sync(); - try std.testing.expect(p.panes[p.view().cols[0].panes[0]].?.vweight != v_left); - try std.testing.expectEqual(v_right, p.panes[p.view().cols[1].panes[0]].?.vweight); -} - -test "a v-handle press at nobody's seam is still a plain edge drag" { - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - const right_seam = nudgeRightSeam(p, 3); - const left_seam = seamRowOf(p, 0, 0); - - const handle = p.view().col_x[0] + p.view().col_w[0] - 1; - var row: u16 = TOPBAR_H + 1; - while (row == left_seam or row == right_seam) row += 1; - - const w0 = p.view().cols[0].weight; - const v_left = p.panes[p.view().cols[0].panes[0]].?.vweight; - const v_right = p.panes[p.view().cols[1].panes[0]].?.vweight; - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = row } }); - try std.testing.expect(p.view().drag == .border_v); - try std.testing.expect(p.view().drag.border_v.corner == null); - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle + 8, .row = row + 5 } }); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle + 8, .row = row + 5 } }); - p.sync(); - // exactly ONE boundary moved - try std.testing.expect(p.view().cols[0].weight > w0); - try std.testing.expectEqual(v_left, p.panes[p.view().cols[0].panes[0]].?.vweight); - try std.testing.expectEqual(v_right, p.panes[p.view().cols[1].panes[0]].?.vweight); -} - -test "a RIGHT-column corner's two axes clamp independently" { - const p = try cornerFixture(std.testing.allocator); - defer p.deinit(); - const right_seam = nudgeRightSeam(p, 3); - const handle = p.view().col_x[0] + p.view().col_w[0] - 1; - p.update(.{ .mouse = .{ .button = .left, .kind = .press, .col = handle, .row = right_seam } }); - try std.testing.expectEqual(@as(usize, 1), (p.view().drag.border_v.corner orelse return error.NoCorner).col); - - // off the right edge at mid-height: x parks at its MINW wall, y is the mouse - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = 999, .row = right_seam } }); - try std.testing.expectEqual(@as(u16, 100 - config.MINW), p.view().drag.border_v.cur_x); - try std.testing.expectEqual(right_seam, p.view().drag.border_v.cur_y); - - // and the mirror: below the bottom at mid-width. y parks, x tracks again - p.update(.{ .mouse = .{ .button = .left, .kind = .drag, .col = handle, .row = 999 } }); - try std.testing.expectEqual(handle, p.view().drag.border_v.cur_x); - const a = p.view().rects[p.view().cols[1].panes[0]]; - const b = p.view().rects[p.view().cols[1].panes[1]]; - try std.testing.expectEqual(clampBorderRow(a.y, a.h, b.h, 999), p.view().drag.border_v.cur_y); - p.update(.{ .mouse = .{ .button = .left, .kind = .release, .col = handle, .row = 999 } }); -} - test "mouse thumb buttons navigate once and clear selection gestures" { const p = try Pardes.init(std.testing.allocator, .{ .cols = 60, .rows = 12 }); defer p.deinit(); diff --git a/src/ninep/ctl.zig b/src/ninep/ctl.zig index 2fa24173..c4947504 100644 --- a/src/ninep/ctl.zig +++ b/src/ninep/ctl.zig @@ -718,17 +718,7 @@ pub fn fillPager(p: *Pardes, serial: u32, held: *std.ArrayList(u8)) error{OutOfM panes.File.setContent(p, f, page.text); f.pager_spans = page.spans; f.saved_revision = f.revision; - // A diff paged (`git show`, difftui's patches): its hunks stacked in a - // +Diff in the +Pager's place, the +Pager closed. The keyboard stays - // where it was, as a page's. - if (f.pager_diff) { - const keyboard = p.view().active; - if (panes.Output.openDiff(p, id, f.path, f.content)) |hid| { - // ponytail: the text is gone with it; Diff on the +Diff says no such file. - p.removePane(id, hid) catch |err| p.reportError(id, "pager", err); - } else |_| {} - if (p.panes[keyboard] != null) p.view().active = keyboard; - } + if (f.pager_diff) @import("../hunks.zig").paged(p, id); } /// The editor's step: the text of /pager opens closed unread goes in. diff --git a/src/ninep/events.zig b/src/ninep/events.zig index 77a4e35f..dd9b488c 100644 --- a/src/ninep/events.zig +++ b/src/ninep/events.zig @@ -677,22 +677,21 @@ fn scanNumber(data: []const u8, i: *usize, overflow: *bool) ?u32 { /// What a click at `at` takes, as the mouse's does (exec.operandAt), /// for an empty range written back: the file name or word under it on its -/// line (look.expandedWord), else nothing; in a diff pane's body, for a -/// look alone (`for_look`, exec.operandAt), look.diffClick's answer, the -/// line's address or its code's words. +/// line (look.expandedWord), else nothing; in a body whose rows name +/// addresses, for a look alone (`for_look`, exec.operandAt), +/// look.rowAddressAt's answer, the row's address or its code's words. pub fn expandAt(p: *Pardes, pane: *Pane, whole: []const u8, at: usize, in_body: bool, for_look: bool) []const u8 { const start = if (std.mem.lastIndexOfScalar(u8, whole[0..at], '\n')) |nl| nl + 1 else 0; const end = std.mem.indexOfScalarPos(u8, whole, at, '\n') orelse whole.len; var word_from: usize = 0; - if (in_body and for_look) diff: { + if (in_body and for_look) row_address: { const row = std.mem.count(u8, whole[0..start], "\n"); - // Only when the served line is the one the diff reads there. - const lines = look.diffLines(p, pane) orelse break :diff; - if (row >= lines.len or !std.mem.eql(u8, std.mem.trimEnd(u8, lines[row], "\r"), std.mem.trimEnd(u8, whole[start..end], "\r"))) break :diff; var buf: [4096 + 32]u8 = undefined; - const click = look.diffClick(p, pane, row, at - start, &buf) orelse break :diff; - if (click.address) |address| return p.scratch.allocator().dupe(u8, address) catch ""; - word_from = click.word_from; + const got = look.rowAddressAt(p, pane, row, at - start, &buf) orelse break :row_address; + // Only when the served line is the one the address was read from. + if (!std.mem.eql(u8, std.mem.trimEnd(u8, got.line, "\r"), std.mem.trimEnd(u8, whole[start..end], "\r"))) break :row_address; + if (got.address) |address| return p.scratch.allocator().dupe(u8, address) catch ""; + word_from = got.word_from; } const line = whole[start..end]; if (at - start < word_from or word_from > line.len) return ""; diff --git a/src/ninep/pane.zig b/src/ninep/pane.zig index 13a15206..6c86053f 100644 --- a/src/ninep/pane.zig +++ b/src/ninep/pane.zig @@ -12,6 +12,7 @@ const modal = @import("../modal.zig"); const config = @import("../config.zig"); const fs = @import("../fs.zig"); const tree = @import("tree.zig"); +const locations = @import("../locations.zig"); const events = @import("events.zig"); const addressing = @import("addr.zig"); const ctl = @import("ctl.zig"); @@ -319,8 +320,8 @@ pub fn fileSize(p: *Pardes, id: usize, f: PaneFile) u64 { // A terminal's body reads its screen and history, as text. .body => if (pane.file == null and pane.isTerminal()) pardes.Term.scrollbackLen(pane.terminal) else if (kindText(p, pane)) |t| t.len else bodyOf(pane).len, // What addr selects, generated by each read: no length, as acme's - // data and xdata have none. - .data, .xdata => 0, + // data and xdata have none; and rows, made by each read. + .data, .xdata, .rows => 0, .tag => if (tagOf(p, pane)) |tag| tag.len else |_| 0, // a stat's length is a hint: none when the tag cannot be made .name => nameOf(p, pane).len + 1, .ctl => ctl: { @@ -396,6 +397,12 @@ pub fn read(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply .mark => readFlag(p, req, !pf.nomark), .scroll => readFlag(p, req, !pf.noscroll), .look, .exec, .tagexec => ctl.readResults(p, req), + .rows => rows: { + const f = fileOf(pane) orelse break :rows tree.window(p, req, ""); + var text: std.Io.Writer.Allocating = .init(p.scratch.allocator()); + locations.formatRows(f.location_rows, &text.writer) catch break :rows Reply.fail(req.tag, E.NOMEM); + break :rows tree.window(p, req, text.written()); + }, .event => events.readQueue(p, req, &pf.events), .pty_status => pty.readStatus(p, req, id, pane), .pty_data => pty.readData(p, req, pf), @@ -498,6 +505,7 @@ pub fn write(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply // A click in its tag: an event reader holding the pane hears it as // an `x` record (ctl.run), as acme's tag clicks are. .tagexec => ctl.command(p, req, pane.serial, true, true), + .rows => writeRows(p, req, pane), .event => events.writeEvent(p, req, id), .errors => if (appendErrors(p, id, req.data)) |took| .{ .tag = req.tag, .written = @intCast(took) } @@ -510,6 +518,36 @@ pub fn write(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply }; } +pub const e_rows_line = "invalid rows: a row is a line, ending in a newline"; +pub const e_rows_text = "invalid rows: a line is no row (the README's rows line says what one is)"; +pub const e_rows_fit = "invalid rows: more rows than the text has lines, or one past its line's end"; + +/// Rows, whole lines of them (a write through a mount is cut anywhere: the +/// rest of a line waits for the open's next write, tree.writeLines): at +/// offset 0 they replace the pane's, at a later one they follow those it +/// holds. Parsed (locations.parseRows) and handed to File.setRows, which +/// refuses what the text cannot hold. +fn writeRows(p: *Pardes, req: Req, pane: *Pane) Reply { + const f = fileOf(pane) orelse return Reply.fail(req.tag, E.PERM); + if (req.data.len == 0) return .{ .tag = req.tag, .written = 0 }; + if (req.data[req.data.len - 1] != '\n') return tree.failText(req.tag, E.INVAL, e_rows_line); + const arena = p.scratch.allocator(); + const written = locations.parseRows(arena, req.data) catch |err| return switch (err) { + error.OutOfMemory => Reply.fail(req.tag, E.NOMEM), + error.BadRows => tree.failText(req.tag, E.INVAL, e_rows_text), + }; + const kept = if (req.off == 0) 0 else f.location_rows.len; + const all = arena.alloc(locations.Row, kept + written.len) catch return Reply.fail(req.tag, E.NOMEM); + @memcpy(all[0..kept], f.location_rows[0..kept]); + @memcpy(all[kept..], written); + const rows = locations.cloneRows(p.gpa, all) catch return Reply.fail(req.tag, E.NOMEM); + panes.File.setRows(p, f, rows) catch { + locations.freeRows(p.gpa, rows); + return tree.failText(req.tag, E.INVAL, e_rows_fit); + }; + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; +} + /// spliceBody for a write of the open `handle`, in the undo step its open /// is making: it joins the step being made only when it is the same open's /// (or the step is anyone's, `joined_by` 0), another open's starting its @@ -981,6 +1019,8 @@ pub fn truncate(p: *Pardes, pane: *Pane, file: PaneFile) tree.Status { pf.limit = null; }, .dot => pf.dot_truncated = fileOf(pane) != null, + // `>` starts the rows over, as a write at 0 does. + .rows => if (fileOf(pane)) |f| panes.File.setRows(p, f, &.{}) catch unreachable, else => {}, } return .ok; @@ -1248,3 +1288,52 @@ test "index names a command's pane cmd, a shell's term" { const shell = try p.newShell(p.freeSlot().?, "/tmp"); try testing.expectEqualStrings("term", kindOf(shell)); } + +test "rows: a pane's rows read as lines, written whole or across writes, refused when its text cannot hold them" { + const gpa = testing.allocator; + const p = try withFile(gpa, "a.txt:3 one\n two\n"); + defer p.deinit(); + const rows = Node.of(serialOf(p), .rows); + try testing.expectEqualStrings("", rd(p, rows, 0, 4096).bytes); + const text = "m 3 0 0 0 0 7 8 3:0+3=keyword.add a.txt\ncd 0 0 0 0 0 0 0 - \n"; + try testing.expectEqual(Status.ok, wr(p, rows, text).reply.status); + try testing.expectEqualStrings(text, rd(p, rows, 0, 4096).bytes); + const f = &p.panes[0].?.file.?; + try testing.expectEqual(@as(usize, 2), f.location_rows.len); + try testing.expectEqualStrings("a.txt", f.location_rows[0].path); + try testing.expect(f.location_rows[1].declaration and f.location_rows[1].kind == .context); + // A write at 0 starts them over; one open's writes, cut mid-line, + // make one set of rows, its later writes following its first. + const h = call(p, .{ .tag = 1, .op = .open, .node = rows, .omode = 1 }).reply.handle; + try testing.expectEqual(Status.ok, call(p, .{ .tag = 2, .op = .write, .node = rows, .handle = h, .off = 0, .data = "m 3 0 0 0 0 7 8 - a.t" }).reply.status); + try testing.expectEqual(Status.ok, call(p, .{ .tag = 3, .op = .write, .node = rows, .handle = h, .off = 21, .data = "xt\np 4 0 0 0 0 0 0 - a.txt\n" }).reply.status); + _ = call(p, .{ .tag = 4, .op = .release, .node = rows, .handle = h }); + try testing.expectEqualStrings("m 3 0 0 0 0 7 8 - a.txt\np 4 0 0 0 0 0 0 - a.txt\n", rd(p, rows, 0, 4096).bytes); + // More rows than lines, an offset or styles past a line's end, a line + // that is no row: refused, the rows as they were. + for ([_][]const u8{ "m 1 0 0 0 0 0 0 - a\nm 1 0 0 0 0 0 0 - a\nm 1 0 0 0 0 0 0 - a\nm 1 0 0 0 0 0 0 - a\n", "m 1 0 0 0 0 12 0 - a\n", "m 1 0 0 0 0 0 8 9:0+1=add a\n", "q 1 0 0 0 0 0 0 - a\n", "m 1 0 0 0 0 0 0 - a" }) |bad| + try testing.expectEqual(Status.err, wr(p, rows, bad).reply.status); + try testing.expectEqual(@as(usize, 2), f.location_rows.len); + // `>` truncates: no rows. + _ = call(p, .{ .tag = 5, .op = .setattr, .node = rows, .truncate = true }); + try testing.expectEqualStrings("", rd(p, rows, 0, 4096).bytes); + // An edit drops them. + try testing.expectEqual(Status.ok, wr(p, rows, text).reply.status); + try testing.expectEqual(Status.ok, wr(p, Node.of(serialOf(p), .body), "more\n").reply.status); + try testing.expectEqual(@as(usize, 0), f.location_rows.len); +} + +test "rows: a +Search's rows read back as the addresses its text shows" { + const gpa = testing.allocator; + const p = try withFile(gpa, "x\n"); + defer p.deinit(); + try panes.Output.fillResults(p, 0, "/tmp", .search, "foo", try p.gpa.dupe(u8, "a.txt:1:1 foo\nb.txt:2:3 foo\n"), null); + const serial = for (p.panes) |slot| { + const pane = slot orelse continue; + const f = pane.file orelse continue; + if (f.output != null and f.location_rows.len > 0) break pane.serial; + } else return error.NoSearch; + const text = rd(p, Node.of(serial, .rows), 0, 4096).bytes; + try testing.expect(std.mem.indexOf(u8, text, "m 1 1 ") == 0); + try testing.expect(std.mem.indexOf(u8, text, " a.txt\n") != null and std.mem.indexOf(u8, text, "\nm 2 3 ") != null and std.mem.endsWith(u8, text, " b.txt\n")); +} diff --git a/src/ninep/pty.zig b/src/ninep/pty.zig index 40ae179c..6e7fe33e 100644 --- a/src/ninep/pty.zig +++ b/src/ninep/pty.zig @@ -507,7 +507,7 @@ test "a pane that is not a terminal has no pty/ at all" { var buf: [32]th.Dirent = undefined; const files = th.dirents(rdir(p, dir, 0).bytes, &buf); - try testing.expectEqual(@as(usize, 18), files.len); + try testing.expectEqual(@as(usize, 19), files.len); try testing.expect(th.nameAt(files, "pty") == null); try testing.expectEqual(E.NOENT, look_up(p, dir, "pty_ctl").errno()); @@ -528,7 +528,7 @@ test "a terminal pane's pty/ holds exactly ctl, status and data" { var buf: [32]th.Dirent = undefined; const files = th.dirents(rdir(p, dir, 0).bytes, &buf); - try testing.expectEqual(@as(usize, 19), files.len); + try testing.expectEqual(@as(usize, 20), files.len); try testing.expect(th.nameAt(files, "pty").?.dir); const inside = th.dirents(rdir(p, Node.of(serial, .pty), 0).bytes, &buf); diff --git a/src/ninep/tree.zig b/src/ninep/tree.zig index bca89466..8902f11e 100644 --- a/src/ninep/tree.zig +++ b/src/ninep/tree.zig @@ -25,6 +25,7 @@ pub const sources = @import("sources.zig"); pub const screen = @import("screen.zig"); const daemon = @import("../daemon.zig"); const panes = @import("../panes.zig"); +const Plumb = @import("../Plumb.zig"); const Pardes = pardes.Pardes; const Pane = pardes.Pane; @@ -99,7 +100,7 @@ fn truncates(req: Req) bool { return switch (Node.target(req.node) orelse return false) { .pane => true, .col => |c| c.file == .tag, - .top => |f| f == .tag, + .top => |f| f == .tag or f == .rules, }; } @@ -151,6 +152,10 @@ pub const Open = struct { /// text after that line held in `pending` until its read puts it /// in (ctl.fillPager), or its close hands it to the editor's step. pager: u32, + /// An open writing plumb/rules or plumb/send: `pending` holds what + /// is not whole yet (rule sets with no blank line after them, a + /// message short of its data). + plumb, } = .{ .snapshot = null }, /// What a write to a file of command lines left unfinished: a last line /// with no newline yet, or an Edit block still open. A write through a @@ -207,7 +212,7 @@ pub const Open = struct { gpa.free(run.line); }, .frozen => |bytes| gpa.free(bytes), - .event, .pty_data, .ctl, .lines, .writes, .pager => {}, + .event, .pty_data, .ctl, .lines, .writes, .pager, .plumb => {}, } o.pending.deinit(gpa); if (o.replay) |r| gpa.free(r.bytes); @@ -269,6 +274,13 @@ pub const TopFile = enum(u5) { /// the addons refused, a line each: `<kind> <version> <abi> /// static|loaded|refused: why [path]`. addons, + /// The plumber's (Plumb.zig, Plan 9's plumber(4)): `rules` and `send`. + plumb, + /// plumb/rules: the rules in force, plumb(6)'s; a write adds rule + /// sets, a `>` replaces them. + rules, + /// plumb/send: a write is a message, plumb(6)'s six lines and data. + send, pub fn fileName(f: TopFile) []const u8 { return if (f == .root) "/" else @tagName(f); @@ -276,15 +288,15 @@ pub const TopFile = enum(u5) { pub fn mode(f: TopFile) u16 { return switch (f) { - .root, .pane, .col => 0o755, - .look, .exec, .log, .focus, .ctl, .tag, .tagexec, .pager => 0o666, + .root, .pane, .col, .plumb => 0o755, + .look, .exec, .log, .focus, .ctl, .tag, .tagexec, .pager, .rules => 0o666, .README, .index, .status, .screen, .listeners, .new, .commands, .layout, .recent, .dumps, .sessions, .addons => 0o444, - .kbdin, .mousein => 0o222, + .kbdin, .mousein, .send => 0o222, }; } pub fn dir(f: TopFile) bool { - return f == .root or f == .pane or f == .col; + return f == .root or f == .pane or f == .col or f == .plumb; } }; @@ -313,6 +325,9 @@ pub const PaneFile = enum(u5) { /// A word run as a click in the pane's tag, as /tagexec is in the /// workspace's and col/<n>/exec in a column's. tagexec, + /// A line a body row: where it points and how it is coloured + /// (locations.formatRows), a results pane's; written, the pane's. + rows, pty, pty_ctl, pty_status, @@ -658,7 +673,7 @@ fn topSize(p: *Pardes, f: TopFile) u64 { // frame, /pane/new until an open has a pane to name, and the index, // layout, recent list and listeners, which a stat would otherwise // have to build to count. - .root, .pane, .col, .screen, .new, .layout, .index, .recent, .dumps, .addons, .listeners, .sessions, .kbdin, .mousein => 0, + .root, .pane, .col, .screen, .new, .layout, .index, .recent, .dumps, .addons, .listeners, .sessions, .kbdin, .mousein, .plumb, .rules, .send => 0, .tag => cols.headerText(p, null).?.len, .README => fs.help.len, .status => if (ctl.statusText(p)) |text| text.len else |_| 0, @@ -697,8 +712,9 @@ fn lookup(p: *Pardes, req: Req, target: Target) Reply { .top => |f| switch (f) { .root => root: { if (std.mem.eql(u8, name, "os")) return fs.osHandle(p, .{ .tag = req.tag, .op = .getattr, .node = fs.os_root }); - // `new` is reached in /pane, where the panes it makes are. - if (std.meta.stringToEnum(TopFile, name)) |t| if (t != .root and t != .new) break :root @backingInt(t); + // `new` is reached in /pane, where the panes it makes are, + // `rules` and `send` in /plumb. + if (std.meta.stringToEnum(TopFile, name)) |t| if (t != .root and t != .new and t != .rules and t != .send) break :root @backingInt(t); if (sources.node(name)) |n| return sources.handle(p, .{ .tag = req.tag, .op = .getattr, .node = n }); return Reply.fail(req.tag, E.NOENT); }, @@ -712,6 +728,7 @@ fn lookup(p: *Pardes, req: Req, target: Target) Reply { if (serial == 0) return Reply.fail(req.tag, E.NOENT); break :dir if (f == .pane) Node.of(serial, .dir) else Node.ofCol(serial, .dir); }, + .plumb => if (std.mem.eql(u8, name, "rules")) @backingInt(TopFile.rules) else if (std.mem.eql(u8, name, "send")) @backingInt(TopFile.send) else return Reply.fail(req.tag, E.NOENT), else => return Reply.fail(req.tag, E.NOTDIR), }, .col => |c| col: { @@ -752,7 +769,7 @@ fn stageDir(p: *Pardes, out: *std.ArrayList(u8), target: Target, off: u64) error .root => { // The guide, then what describes the session, then the // files that act, then the directories. - inline for (.{ TopFile.README, TopFile.index, TopFile.status, TopFile.focus, TopFile.ctl, TopFile.commands, TopFile.recent, TopFile.dumps, TopFile.addons, TopFile.look, TopFile.exec, TopFile.pager, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.sessions, TopFile.layout, TopFile.tag, TopFile.tagexec, TopFile.kbdin, TopFile.mousein, TopFile.pane, TopFile.col }) |t| { + inline for (.{ TopFile.README, TopFile.index, TopFile.status, TopFile.focus, TopFile.ctl, TopFile.commands, TopFile.recent, TopFile.dumps, TopFile.addons, TopFile.look, TopFile.exec, TopFile.pager, TopFile.log, TopFile.screen, TopFile.listeners, TopFile.sessions, TopFile.layout, TopFile.tag, TopFile.tagexec, TopFile.kbdin, TopFile.mousein, TopFile.plumb, TopFile.pane, TopFile.col }) |t| { if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, @backingInt(t), t.dir(), t.fileName()); } if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, fs.os_root, true, "os"); @@ -773,6 +790,9 @@ fn stageDir(p: *Pardes, out: *std.ArrayList(u8), target: Target, off: u64) error try stageDirent(out, p.gpa, Node.of(serial, .dir), true, name); } }, + .plumb => inline for (.{ TopFile.rules, TopFile.send }) |t| { + if (skip > 0) skip -= 1 else try stageDirent(out, p.gpa, @backingInt(t), false, t.fileName()); + }, .col => for (0..p.view().ncol) |c| { if (skip > 0) { skip -= 1; @@ -842,6 +862,11 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { .index, .layout, .recent, .dumps, .addons, .commands, .status, .listeners, .sessions => .{ .frozen = &.{} }, // The root's ctl opened only to read: its settings, frozen. .ctl => if (linesOpen(target, req)) .lines else .{ .frozen = &.{} }, + // One writer of the rules at a time, as plumber(4)'s. + .rules, .send => if (req.omode & 3 == 0) return .{ .tag = req.tag } else plumb: { + if (f == .rules) for (p.fs.opens) |o| if (o.node == req.node and o.what == .plumb) return failText(req.tag, E.BUSY, e_in_use); + break :plumb .plumb; + }, else => if (linesOpen(target, req)) .lines else return .{ .tag = req.tag }, }, .col => |c| if (layout.columnBySerial(p, c.serial) == null) @@ -904,7 +929,7 @@ fn open(p: *Pardes, req: Req, target: Target) Reply { pn.fs.event_reader = pn.fs.event_reader or reader; }, .pty_data => pane_of.?.fs.pty_reader = true, - .run, .ctl, .lines, .writes, .pager => {}, + .run, .ctl, .lines, .writes, .pager, .plumb => {}, } return .{ .tag = req.tag, .handle = @intCast(i + 1) }; } @@ -967,6 +992,9 @@ fn releaseHandle(p: *Pardes, req: Req) void { if (t == .col and t.col.file == .tag) cols.released(p, t.col.serial); if (t == .top and t.top == .tag) cols.released(p, null); const o = openOf(p, req) orelse return; + // A message short of its data is dropped with its open, as plumber(4) + // drops a fid's writebuf; rule text left goes in at the editor's step. + if (o.what == .plumb and req.node == @backingInt(TopFile.send)) o.pending.clearRetainingCapacity(); // A /pager open's text, not read for, goes in at the editor's next // step (ctl.fillClosedPagers): this close need not wait for quiet. if (o.what == .pager and o.pending.items.len > 0) { @@ -999,7 +1027,7 @@ fn releaseHandle(p: *Pardes, req: Req) void { .ctl => if (pn.fs.lock == req.handle) { pn.fs.lock = null; }, - .snapshot, .log, .lines, .writes, .frozen, .pager => {}, + .snapshot, .log, .lines, .writes, .frozen, .pager, .plumb => {}, }; o.deinit(p.gpa); } @@ -1017,7 +1045,7 @@ fn setattr(p: *Pardes, req: Req, target: Target) Reply { if (pane.truncate(p, p.panes[id].?, t.file) != .ok) return Reply.fail(req.tag, E.NOMEM); }, .col => |c| if (c.file == .tag and cols.truncate(p, c.serial) != .ok) return Reply.fail(req.tag, E.NOENT), - .top => |f| if (f == .tag and cols.truncate(p, null) != .ok) return Reply.fail(req.tag, E.NOMEM), + .top => |f| if (f == .tag and cols.truncate(p, null) != .ok) return Reply.fail(req.tag, E.NOMEM) else if (f == .rules) Plumb.clear(p), }; return .{ .tag = req.tag, .attr = attrOf(p, target) orelse return Reply.fail(req.tag, E.NOENT) }; } @@ -1055,8 +1083,9 @@ fn read(p: *Pardes, req: Req, target: Target) Reply { fn readFile(p: *Pardes, req: Req, target: Target) Reply { switch (target) { .top => |f| return switch (f) { - .kbdin, .mousein => Reply.fail(req.tag, E.PERM), + .kbdin, .mousein, .send => Reply.fail(req.tag, E.PERM), .README => window(p, req, fs.help), + .rules => window(p, req, Plumb.inForce(p)), .index => index: { const out = p.fs.stage(p.gpa); var last: u32 = 0; @@ -1128,7 +1157,7 @@ fn readFile(p: *Pardes, req: Req, target: Target) Reply { break :serial Reply.fail(req.tag, E.NOMEM); break :serial stagedReply(p, req); }, - .root, .pane, .col => Reply.fail(req.tag, E.PERM), + .root, .pane, .col, .plumb => Reply.fail(req.tag, E.PERM), }, .pane => |t| { // A run's answer outlives the pane it ran in. @@ -1163,7 +1192,7 @@ fn linesFile(target: Target) bool { .col => |c| c.file == .ctl or c.file == .exec, // `name` too: one name, however its writes cut it, applied once // its newline comes, or with its write when that is whole. - .pane => |t| t.file == .look or t.file == .exec or t.file == .ctl or t.file == .tagexec or t.file == .name, + .pane => |t| t.file == .look or t.file == .exec or t.file == .ctl or t.file == .tagexec or t.file == .name or t.file == .rows, }; } @@ -1326,6 +1355,9 @@ fn writeLines(p: *Pardes, req: Req, target: Target) Reply { o.pending.shrinkRetainingCapacity(rest); var w = req; w.data = whole; + // At the offset its first byte was written at, an earlier write's + // held line included (a rows write at 0 starts the rows over). + w.off = (req.off + (req.data.len - data.len)) -| (end + rest - data.len); // The command pane this open was answered holds no lease against its // own next command (exec.leased): that one may run there again. if (resultsFile(target)) o.results.len = 0; @@ -1350,6 +1382,8 @@ fn writeNow(p: *Pardes, req: Req, target: Target) Reply { .pager => ctl.writePager(p, req), .tag => cols.write(p, req, null), .tagexec => cols.writeExec(p, req, null), + .rules => writeRules(p, req), + .send => writeSend(p, req), else => Reply.fail(req.tag, E.PERM), }, .pane => |t| { @@ -1367,6 +1401,60 @@ fn writeNow(p: *Pardes, req: Req, target: Target) Reply { } } +/// plumb/rules: rule text added to the rules in force a rule set at a time, +/// as each is whole (a blank line after it, rules.c's morerules), the rest +/// at the open's close; a refusal is the write's, in plumb(6)'s words, the +/// rules as they were and the text it held dropped. +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; + 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})); + } + 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]); + 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..]); + o.pending.shrinkRetainingCapacity(rest); + } + return if (why) |w| failText(req.tag, E.INVAL, w) else done; +} + +/// plumb/send: a message, its writes put together until its data is all +/// there (plumber(4)), then matched and sent: the write is answered when it +/// has gone where the rules say, or with why not, in Plan 9's words. +fn writeSend(p: *Pardes, req: Req) Reply { + const o = openOf(p, req); + const held = if (o) |op| op.pending.items.len > 0 else false; + if (held) o.?.pending.appendSlice(p.gpa, req.data) catch return Reply.fail(req.tag, E.NOMEM); + defer if (o) |op| if (op.pending.items.len > pending_cap) op.pending.clearRetainingCapacity(); + switch (Plumb.unpack(if (held) o.?.pending.items else req.data)) { + .bad => { + if (o) |op| op.pending.clearRetainingCapacity(); + return failText(req.tag, E.INVAL, Plumb.e_bad_msg); + }, + .more => |n| { + const op = o orelse return failText(req.tag, E.INVAL, Plumb.e_bad_msg); + if (op.pending.items.len + n > pending_cap) { + op.pending.clearRetainingCapacity(); + return failText(req.tag, E.INVAL, Plumb.e_bad_msg ++ ": over 1 MiB"); + } + if (!held) op.pending.appendSlice(p.gpa, req.data) catch return Reply.fail(req.tag, E.NOMEM); + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; + }, + .msg => |m| { + defer if (o) |op| op.pending.clearRetainingCapacity(); + if (Plumb.send(p, null, m)) |why| return failText(req.tag, E.IO, why); + return .{ .tag = req.tag, .written = @intCast(req.data.len) }; + }, + } +} + // ---- tests ---- const testing = std.testing; @@ -1566,13 +1654,23 @@ test "readdir lists the root and a pane directory without creating anything" { @memcpy(top_bytes[0..top_reply.bytes.len], top_reply.bytes); const top = th.dirents(top_bytes[0..top_reply.bytes.len], &buf); try testing.expect(top.len >= 10); - for ([_][]const u8{ "README", "index", "status", "focus", "ctl", "commands", "recent", "dumps", "addons", "look", "exec", "pager", "log", "screen", "listeners", "sessions", "layout", "tag", "tagexec", "kbdin", "mousein", "pane", "col", "os" }, 0..) |name, i| { + for ([_][]const u8{ "README", "index", "status", "focus", "ctl", "commands", "recent", "dumps", "addons", "look", "exec", "pager", "log", "screen", "listeners", "sessions", "layout", "tag", "tagexec", "kbdin", "mousein", "plumb", "pane", "col", "os" }, 0..) |name, i| { try testing.expectEqualStrings(name, top[i].name); try testing.expectEqual(i >= 21, top[i].dir); } - try testing.expectEqual(@backingInt(TopFile.pane), top[21].node); - try testing.expectEqual(@backingInt(TopFile.col), top[22].node); - try testing.expectEqual(fs.os_root, top[23].node); + try testing.expectEqual(@backingInt(TopFile.plumb), top[21].node); + try testing.expectEqual(@backingInt(TopFile.pane), top[22].node); + try testing.expectEqual(@backingInt(TopFile.col), top[23].node); + try testing.expectEqual(fs.os_root, top[24].node); + // The plumber's directory: its rules, then send. + const plumb_reply = rdir(p, @backingInt(TopFile.plumb), 0); + var plumb_bytes: [256]u8 = undefined; + @memcpy(plumb_bytes[0..plumb_reply.bytes.len], plumb_reply.bytes); + var plumb_buf: [4]th.Dirent = undefined; + const plumb = th.dirents(plumb_bytes[0..plumb_reply.bytes.len], &plumb_buf); + try testing.expectEqual(@as(usize, 2), plumb.len); + try testing.expectEqualStrings("rules", plumb[0].name); + try testing.expectEqualStrings("send", plumb[1].name); var idbuf: [16]u8 = undefined; try testing.expect(th.nameAt(top, try std.fmt.bufPrint(&idbuf, "{d}", .{serial})) == null); try testing.expect(th.nameAt(top, "self") == null); @@ -1611,10 +1709,10 @@ test "readdir lists the root and a pane directory without creating anything" { const dir = rdir(p, Node.of(serial, .dir), 0); const files = th.dirents(dir.bytes, &buf); - try testing.expectEqual(@as(usize, 18), files.len); + try testing.expectEqual(@as(usize, 19), files.len); for ([_][]const u8{ - "name", "body", "tag", "ctl", "addr", "dot", "limit", "data", "xdata", - "sel", "dirty", "mark", "scroll", "errors", "event", "look", "exec", "tagexec", + "name", "body", "tag", "ctl", "addr", "dot", "limit", "data", "xdata", "sel", + "dirty", "mark", "scroll", "errors", "event", "look", "exec", "tagexec", "rows", }, 0..) |name, i| try testing.expectEqualStrings(name, files[i].name); try testing.expect(th.nameAt(files, ".") == null); diff --git a/src/panes.zig b/src/panes.zig index 77246653..bb026c30 100644 --- a/src/panes.zig +++ b/src/panes.zig @@ -176,7 +176,7 @@ pub const Pane = struct { /// be printing to it, and a reuse would hang it up. command_pty: bool = false, /// Its child pages as a terminal's does (`pardes -`, a +Pager), not - /// through cat: Look's `git show` of a commit (look.lookCommit). + /// through cat: Look's `git show` of a commit (hunks.lookedAtCommit). command_pages: bool = false, /// The shell a terminal runs when it is not the configured one (`Term /// fish`), owned. diff --git a/src/pardes.zig b/src/pardes.zig index 2b956882..86530157 100644 --- a/src/pardes.zig +++ b/src/pardes.zig @@ -383,6 +383,7 @@ test { _ = @import("Addon.zig"); _ = @import("rollback.zig"); _ = @import("Core.zig"); + _ = @import("Plumb.zig"); _ = @import("lsp/Ask.zig"); _ = @import("lsp/lsp_client.zig"); _ = @import("Jump.zig"); diff --git a/src/plumbing b/src/plumbing new file mode 100644 index 00000000..74c1f306 --- /dev/null +++ b/src/plumbing @@ -0,0 +1,23 @@ +# pardes's plumbing rules, in plumb(6)'s language: a plumbing file of +# your own names this one as `include basic`. A message (plumb/send) is +# matched against the rule sets in order; the first whose patterns all +# 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. + +# urls go to the web browser (the host's: xdg-open, open on macOS) +type is text +data matches 'https?://.*' +plumb to web + +# 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 +type is text +arg isdir $data +plumb to edit + +type is text +arg isfile $data +plumb to edit diff --git a/src/regexp.zig b/src/regexp.zig index 7bcbceff..87fc51d6 100644 --- a/src/regexp.zig +++ b/src/regexp.zig @@ -595,6 +595,14 @@ test "a \\x without two hex digits is refused, not handed to mvzr to panic on" { try std.testing.expectEqual(@as(usize, 1), (try rx.find("xA", 0, 1, 2)).?.start); } +test "a class's range may end at \\xff: UTF-8's high bytes as one class" { + var rx = try Regex.compile("[a-z\\x80-\\xff]+"); + const text = "-- café --"; + const m = (try rx.find(text, 0, text.len, text.len)).?; + try std.testing.expectEqualStrings("café", text[m.start..m.end]); + _ = try Regex.compile("[\\xff-\\xff]"); +} + test "a repeat inside a group gives back to what follows the group" { const Case = struct { pat: []const u8, text: []const u8, start: usize, end: usize }; for ([_]Case{ diff --git a/src/surface.zig b/src/surface.zig index a5dbea8e..b832222f 100644 --- a/src/surface.zig +++ b/src/surface.zig @@ -205,8 +205,6 @@ pub const Region = struct { /// A column below the workspace tag, its bar and panes: its left /// edge is the spine a pixel shell rules down it. column, - /// A drag's guide or a seam's hover hint, drawn over the panes. - guide, /// The debug stats box, drawn over the panes. debug, }; @@ -244,15 +242,9 @@ pub const Region = struct { /// it shows, in pixels. Its placements are laid at the whole pixel; a /// pixel frontend draws them the fraction higher. scroll_px: f64 = 0, - /// Cells the column-move rail takes off the right edge while it runs - /// there: layers and pixel shells stop short of them, the grid does not. - clip: u16 = 0, }; -/// Guides a frame can draw: a run of a column-move rail per pane it skips -/// the tags of, and a handful of border and hover dashes. -pub const MAX_GUIDES = MAX_PANES + 4; -pub const MAX_REGIONS = 1 + MAX_PANES * (4 + panes.Pane.Notices.max) + pardes.MAX_COLS * 3 + 1 + MAX_GUIDES + 1; +pub const MAX_REGIONS = 1 + MAX_PANES * (4 + panes.Pane.Notices.max) + pardes.MAX_COLS * 3 + 1 + 1; /// The colours a pixel shell draws its chrome in (rules, rails, grips, the /// tag underlay), resolved by the core each frame, so a frontend attached @@ -472,14 +464,6 @@ pub const Surface = struct { while (xx < x + w) : (xx += 1) s.at(xx, yy).* = .{}; } } - - /// swap ONLY the glyph, keeping the cell's colors — the resize-handle hint - pub fn overlayDash(s: *Surface, x: u16, y: u16, glyph: []const u8) void { - const c = s.at(x, y); - @memcpy(c.text[0..glyph.len], glyph); - c.len = @intCast(glyph.len); - c.default = false; - } }; test "cell visual equality ignores dead grapheme tail bytes" { diff --git a/src/syntax.zig b/src/syntax.zig index 2526e113..70399bf7 100644 --- a/src/syntax.zig +++ b/src/syntax.zig @@ -22,7 +22,7 @@ const ts_queries = if (enabled) @import("ts_queries") else struct {}; const LanguageFn = *const fn () callconv(.c) *const ts.Language; -pub const Syn = enum(u8) { none, keyword, string, number, comment }; +pub const Syn = grammar_manifest.Syn; /// A query compiled when first asked for: "" for none, null when it fails. const Lazy = struct { src: []const u8 = "", query: ?*ts.Query = null, failed: bool = false }; @@ -55,81 +55,6 @@ fn specCount() comptime_int { } return count; } -const typst_supplement = - \\ - \\(call item: (ident) @keyword) - \\(call item: (field field: (ident) @keyword)) - \\"#" @keyword - \\ -; - -fn querySrc(comptime g: grammar_manifest.Grammar) []const u8 { - const base = @field(ts_queries, g.name ++ "_highlights"); - const source = if (comptime std.mem.eql(u8, g.name, "typst")) base ++ typst_supplement else base; - return comptime colorQuery(source); -} - -fn colorQuery(comptime source: []const u8) []const u8 { - @setEvalBranchQuota(2_000_000); - var result: [source.len]u8 = undefined; - var written: usize = 0; - var at: usize = 0; - while (at < source.len) { - while (at < source.len) { - if (std.ascii.isWhitespace(source[at])) { - at += 1; - } else if (source[at] == ';') { - while (at < source.len and source[at] != '\n') at += 1; - } else break; - } - const begin = at; - var depth: usize = 0; - var colored = false; - var complete = false; - while (at < source.len) { - const byte = source[at]; - if (complete and (byte == '(' or byte == '[' or byte == '"')) break; - if (byte == ';') { - while (at < source.len and source[at] != '\n') at += 1; - continue; - } - if (byte == '"') { - at += 1; - while (at < source.len) : (at += 1) { - if (source[at] == '\\') { - at += 1; - } else if (source[at] == '"') { - at += 1; - break; - } - } - if (depth == 0) complete = true; - continue; - } - if (byte == '(' or byte == '[') depth += 1; - if (byte == ')' or byte == ']') { - depth -= 1; - if (depth == 0) complete = true; - } - if (byte == '@') { - const name = at + 1; - at = name; - while (at < source.len and (std.ascii.isAlphanumeric(source[at]) or - source[at] == '_' or source[at] == '.' or source[at] == '-')) at += 1; - colored = colored or synFor(source[name..at]) != .none; - continue; - } - at += 1; - } - if (colored) { - @memcpy(result[written..][0 .. at - begin], source[begin..at]); - written += at - begin; - } - } - const filtered = result[0..written].*; - return &filtered; -} - fn initSpecs() [specCount()]Spec { var out: [specCount()]Spec = undefined; var i = 0; @@ -139,7 +64,7 @@ fn initSpecs() [specCount()]Spec { .name = g.name, .exts = g.exts, .language = @extern(LanguageFn, .{ .name = "tree_sitter_" ++ g.name }), - .query_src = querySrc(g), + .query_src = @field(ts_queries, g.name ++ "_highlights"), .objects = .{ .src = @field(ts_queries, g.name ++ "_textobjects") }, .indents = .{ .src = @field(ts_queries, g.name ++ "_indents") }, }; @@ -219,7 +144,7 @@ fn ensure(spec: *Spec) !Selected { const capture_styles = spec.capture_styles[0..query.captureCount()]; for (capture_styles, 0..) |*style, id| { const name = query.captureNameForId(@intCast(id)) orelse ""; - style.* = @backingInt(synFor(name)); + style.* = @backingInt(grammar_manifest.synFor(name)); if (style.* == 0) query.disableCapture(name); } const parser = ts.Parser.create(); @@ -260,34 +185,6 @@ fn runQuery(styles: []u8, sel: Selected, tree: *ts.Tree, base: usize) void { } } -fn synFor(name: []const u8) Syn { - for ([_]struct { []const u8, Syn }{ - .{ "comment", .comment }, - .{ "string", .string }, - .{ "character", .string }, - .{ "number", .number }, - .{ "numeric", .number }, - .{ "float", .number }, - .{ "boolean", .number }, - .{ "keyword", .keyword }, - .{ "include", .keyword }, - .{ "conditional", .keyword }, - .{ "repeat", .keyword }, - .{ "title", .keyword }, - .{ "uri", .string }, - .{ "reference", .number }, - .{ "heading", .keyword }, - .{ "strong", .comment }, - .{ "bold", .comment }, - .{ "emphasis", .number }, - .{ "italic", .number }, - .{ "literal", .string }, - .{ "raw", .string }, - }) |m| { - if (std.mem.indexOf(u8, name, m[0]) != null) return m[1]; - } - return .none; -} pub fn highlightFileRange(gpa: std.mem.Allocator, path: []const u8, content: []const u8, start_raw: usize, end_raw: usize) ![]u8 { const zone = tracy.zone(@src(), "highlightFileRange"); defer zone.end(); @@ -1036,16 +933,17 @@ fn childOfKind(node: ts.Node, kind: []const u8) ?ts.Node { return null; } -/// A diff line's style byte carries whether the line was added or removed -/// over its syntax style (the low bits), so the painter can tint its row -/// and mark its prefix; Diff marks the words a changed line changed -/// (hunks.zig), drawn on a stronger tint. -pub const diff_added: u8 = 0x80; -pub const diff_removed: u8 = 0x40; -pub const diff_emph: u8 = 0x20; -/// A +Diff line added or removed whole, paired with no line it changed: -/// its row takes a faint tint, on its marker's byte. -pub const diff_whole: u8 = 0x10; +/// A style byte: a Syn in its low bits (syn_bits), and over them the +/// grounds a theme resolves (colors.Grounds): `ground_add` or `ground_del`, +/// a row added or removed (its hue); `ground_emph`, the stronger ground; +/// `ground_line`, the faint one. A row's first byte says its row's ground: +/// emph the stronger to the pane's edge, line the faint one, neither none +/// (only its marker in the hue). Any later byte's emph is its own cell's +/// ground: the words a changed line changed (hunks.zig). +pub const ground_add: u8 = 0x80; +pub const ground_del: u8 = 0x40; +pub const ground_emph: u8 = 0x20; +pub const ground_line: u8 = 0x10; pub const syn_bits: u8 = 0x0f; /// A file section's hunks are parsed together, each side as one text, in @@ -1070,7 +968,8 @@ var diff_clock: u64 = 0; /// the file its section names. A hunk's old side (context and removed /// lines) and new side (context and added lines) are each parsed whole, so /// a string or comment that spans lines colours as it does in the file. -/// Added and removed lines carry `diff_added`/`diff_removed`. A file in no +/// Added and removed lines carry `ground_add`/`ground_del`, the first byte +/// the strong row ground too (`ground_emph`). A file in no /// language pardes knows keeps the plain colours: added lines as strings, /// removed ones as numbers. pub fn highlightDiff(gpa: std.mem.Allocator, content: []const u8, start_raw: usize, end_raw: usize) ![]u8 { @@ -1185,13 +1084,14 @@ fn paintDiffPiece(gpa: std.mem.Allocator, window: DiffWindow, bytes: []const u8, for (kinds) |kind| { const line = lines.next() orelse break; const style: u8 = switch (kind) { - .added => @backingInt(Syn.string) | diff_added, - .removed => @backingInt(Syn.number) | diff_removed, + .added => @backingInt(Syn.string) | ground_add, + .removed => @backingInt(Syn.number) | ground_del, .no_newline => @backingInt(Syn.comment), .hunk => @backingInt(Syn.keyword), else => 0, }; if (style != 0) window.fill(at + offset, line.len, style); + if (style & (ground_add | ground_del) != 0 and line.len > 0) window.fill(at + offset, 1, style | ground_emph); offset += line.len + 1; } } @@ -1273,13 +1173,14 @@ fn paintHunk(gpa: std.mem.Allocator, out: []u8, bytes: []const u8, kinds: []cons if (kind == .context or kind == .removed) old_at += code_len + 1; if (kind == .context or kind == .added) new_at += code_len + 1; const flag: u8 = switch (kind) { - .added => diff_added, - .removed => diff_removed, + .added => ground_add, + .removed => ground_del, else => 0, }; if (flag != 0) for (out[offset..][0..line.len]) |*b| { b.* |= flag; }; + if (flag != 0 and line.len > 0) out[offset] |= ground_emph; } } @@ -1680,9 +1581,12 @@ test "syntax highlightDiff colors unified diff lines by prefix" { // A file in no known language: each line in one colour, and tinted. try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "-old line", 0)); try std.testing.expectEqual(Syn.string, diffSynAt(styles, diff_text, "+new line", 0)); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "-old line").?] & diff_removed != 0); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "+new line").? + 4] & diff_added != 0); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, " context").?] & (diff_added | diff_removed) == 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "-old line").?] & ground_del != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "+new line").? + 4] & ground_add != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, " context").?] & (ground_add | ground_del) == 0); + // The row's ground on its first byte: the strong one, its other bytes none. + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "-old line").?] & ground_emph != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "+new line").? + 4] & (ground_emph | ground_line) == 0); } test "syntax a Zig hunk is coloured as Zig, each side parsed whole" { @@ -1714,9 +1618,9 @@ test "syntax a Zig hunk is coloured as Zig, each side parsed whole" { try std.testing.expectEqual(Syn.string, diffSynAt(styles, diff_text, "new words defer", 10)); // The prefix is no code: it carries the tint alone. const added = std.mem.indexOf(u8, diff_text, "+ side").?; - try std.testing.expectEqual(diff_added, styles[added]); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "42").?] & diff_added != 0); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "7,").?] & diff_removed != 0); + try std.testing.expectEqual(ground_add | ground_emph, styles[added]); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "42").?] & ground_add != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "7,").?] & ground_del != 0); try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "index 111", 0)); // A window in the middle is coloured as the whole is. @@ -1763,7 +1667,7 @@ test "syntax a deleted file's lines are coloured in its language" { defer std.testing.allocator.free(styles); try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "enum", 0)); try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "// the end", 3)); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "enum").?] & diff_removed != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "enum").?] & ground_del != 0); try std.testing.expectEqual(Syn.comment, diffSynAt(styles, diff_text, "deleted file", 0)); } @@ -1812,9 +1716,9 @@ test "syntax git diff output in a command pane is told and coloured by its rows" try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, text, "fn main", 0)); try std.testing.expectEqual(Syn.number, diffSynAt(styles, text, "42", 0)); // The wrapped row stays an added line, and inside the comment. - try std.testing.expect(styles[std.mem.indexOf(u8, text, "wrapped rest").?] & diff_added != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, text, "wrapped rest").?] & ground_add != 0); try std.testing.expectEqual(Syn.comment, diffSynAt(styles, text, "wrapped rest", 0)); - try std.testing.expect(styles[std.mem.indexOf(u8, text, "return").?] & diff_removed != 0); + try std.testing.expect(styles[std.mem.indexOf(u8, text, "return").?] & ground_del != 0); } test "syntax a section's small hunks share one parse" { @@ -1836,7 +1740,7 @@ test "syntax a section's small hunks share one parse" { try std.testing.expectEqual(@as(usize, 2), cached); // x.zig's three hunks, and y.zig's try std.testing.expectEqual(Syn.keyword, diffSynAt(styles, diff_text, "@@ -10", 0)); try std.testing.expectEqual(Syn.number, diffSynAt(styles, diff_text, "2;\n@@ -20", 0)); - try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "@@ -10").?] & (diff_added | diff_removed) == 0); + try std.testing.expect(styles[std.mem.indexOf(u8, diff_text, "@@ -10").?] & (ground_add | ground_del) == 0); } test "syntax a hunk painted once is kept, and a long one is parsed in pieces" { @@ -1909,8 +1813,7 @@ test "syntax query filtering preserves upstream colors" { inline for (grammar_manifest.all) |grammar| { if (comptime grammarSelected(grammar)) { const selected = (try forLang(grammar.name)).?; - const raw_source = @field(ts_queries, grammar.name ++ "_highlights") ++ - (if (comptime std.mem.eql(u8, grammar.name, "typst")) typst_supplement else ""); + const raw_source = @field(ts_queries, grammar.name ++ "_highlights_unfiltered"); var error_offset: u32 = 0; const raw_query = try ts.Query.create(selected.lang, raw_source, &error_offset); defer raw_query.destroy(); @@ -1918,7 +1821,7 @@ test "syntax query filtering preserves upstream colors" { reference.query = raw_query; reference.capture_styles = try std.testing.allocator.alloc(u8, raw_query.captureCount()); defer std.testing.allocator.free(reference.capture_styles); - for (reference.capture_styles, 0..) |*style, id| style.* = @backingInt(synFor(raw_query.captureNameForId(@intCast(id)) orelse "")); + for (reference.capture_styles, 0..) |*style, id| style.* = @backingInt(grammar_manifest.synFor(raw_query.captureNameForId(@intCast(id)) orelse "")); const tree = selected.parser.parseString(source, null) orelse return error.ParseFailed; defer tree.destroy(); var expected: [source.len]u8 = @splat(0); |
