From ed0103e9738e3cf5a7c7a91aec5adf0be2fc409a Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 05:30:58 -0300 Subject: library: a patch row's text is its line without its end, said and tested: hunks.format trims a diff line's `\r` before its `\n` (and diff.Walk.step, and each of a source's lines, so the two compare) on purpose, and nothing a consumer reads said so (toilet saw a CRLF file's rows without their `\r`); the Patch doc comment, lib_syntax's, abi/wasm.zig's record and docs/typ/building.typ (the patch view, the record's text) say it now; test/consumer: a CRLF diff stacks to the LF diff's rows with no file, and with a CRLF main.c handed in its lines still match the diff's (its declaration found above `main.c:3 *`); no code changes Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- docs/typ/building.typ | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'docs/typ') diff --git a/docs/typ/building.typ b/docs/typ/building.typ index f2b3289f..69468042 100644 --- a/docs/typ/building.typ +++ b/docs/typ/building.typ @@ -184,7 +184,10 @@ nothing of the editor: each hunk under its `path:line`, what it stands in above it, its lines behind their markers on their grounds, and the words a changed line changed emphasised (delta's way). It returns a `Patch`, its text and a `PatchRow` for each of its lines (row _i_ is line _i_), all in -the arena it is handed: +the arena it is handed. A row's text is its line without its end, the +`\n` and a `\r` before it: a CRLF diff's rows have no `\r` (a reader that +must show one reads it off the diff), and a file handed in as `source` is +compared line by line the same way, so a CRLF file matches its diff. #pairs( [`kind`], [`other` (a mailed patch's headers, message, diffstat), `meta` (a section's own words: a mode, a rename, `Binary files ... differ`), `hunk` (its label, a star a declaration it stands in), `declaration` (what it stands in: a declaration's `path:line` and header lines from the file, or git's own words after the `@@`), `context`, `added`, `removed`], @@ -242,7 +245,7 @@ and a row's record: [0 `kind`], [0 other, 1 meta, 2 hunk, 3 declaration (git's words after the `@@`), 4 context, 5 added, 6 removed], [4 `old`, 8 `new`], [its numbers in the old and the new file, from 1; 0 where it has none], [12 `code_start`], [where its code starts in its text: after a hunk label's `path:line` and stars], - [16 `text_offset`, 20 `text_len`], [its text, without its newline, in the header's `text`], + [16 `text_offset`, 20 `text_len`], [its text, without its line end (the `\n`, and a `\r` before it), in the header's `text`], [24 `path_offset`, 28 `path_len`], [its section's path, in the header's `text` too], [32 `flags`], [bit 0: the diff has `\ No newline at end of file` after it], ) -- cgit v1.3 From bf16b1c2b461f4d7db17efb6de912799a5bf78ac Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 05:49:06 -0300 Subject: library: a language's browser module formats one file's diff with that file's text: `patchFile(text, len, file, file_len)` beside `highlight` (xit writes its `@@` with nothing after it, so a hunk had no context at all; toilet has the file's blob), the same header and records as `patch`, with the declaration rows formatPatch stacks when it has a source (kind 3, as git's words are: a declaration's `path:line` row, its code_start its whole length, then its header's lines); the text is the first section's file, new or old (formatPatch finds each hunk on either side and numbers the labels as that side; tested both), a hunk the text does not hold and the diff's other files stack as with no text (tested: the same rows as `patch`); only abi/wasm.zig (the export, a `Given` source answering for the first path asked, `start` shared with highlight), build.zig (the export's name, the option named `language`) and the docs: formatPatch is unchanged; +7,031 bytes on rust's module (1,290,182 -> 1,297,213; about 7 KB on each language's), 18 ms against patch's 4 for a 28-hunk diff of a 1,100-line Zig file under node (the file's parse); test/consumer's node run calls it on a bare-`@@` rust diff with the new text, the old, another text and a second file Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- abi/wasm.zig | 53 +++++++++++++++++++++++++++++++++++++++++++------- build.zig | 6 +++--- docs/typ/building.typ | 20 +++++++++++++++++-- test/consumer/wasm.mjs | 38 ++++++++++++++++++++++++++++++++++++ 4 files changed, 105 insertions(+), 12 deletions(-) (limited to 'docs/typ') diff --git a/abi/wasm.zig b/abi/wasm.zig index 0c67e0da..88dc8d90 100644 --- a/abi/wasm.zig +++ b/abi/wasm.zig @@ -14,7 +14,11 @@ //! - `patch(text, len)`: the diff `text` stacked as pardes's patch view //! shows it (`formatPatch`, with no file and no colours): a `Header`, its //! rows' text, a style byte for each byte of it, and a `Record` a row. -//! The module's until the next `patch`. +//! The module's until the next `patch` or `patchFile`. +//! - `patchFile(text, len, file, file_len)` (a module with a language): +//! `patch` with the text of the file the diff's first section names (its +//! new text or its old), so a hunk gets the declarations it sits in from +//! the file's own parse; the diff's other files stack as with none. //! //! Each returns null (0) when its memory runs out. const std = @import("std"); @@ -35,8 +39,12 @@ pub const panic = std.debug.FullPanic(struct { }.write); comptime { - // A module with no language has no highlighter, and so no tree-sitter. - if (options.highlight) @export(&highlight, .{ .name = "highlight" }); + // A module with no language has no highlighter and no parse of a file, + // and so no tree-sitter. + if (options.language) { + @export(&highlight, .{ .name = "highlight" }); + @export(&patchFile, .{ .name = "patchFile" }); + } } export fn reserve(len: usize) ?[*]u8 { @@ -50,9 +58,13 @@ export fn release(ptr: [*]u8, len: usize) void { var started = false; var styles: []u8 = &.{}; -fn highlight(path: [*]const u8, path_len: usize, text: [*]const u8, len: usize) callconv(.c) ?[*]u8 { +fn start() void { if (!started) ps.start(gpa); started = true; +} + +fn highlight(path: [*]const u8, path_len: usize, text: [*]const u8, len: usize) callconv(.c) ?[*]u8 { + start(); gpa.free(styles); styles = ps.highlightFileRange(gpa, path[0..path_len], text[0..len], 0, len) catch &.{}; // A path in no language this module has, or an empty text: all plain. @@ -101,11 +113,38 @@ var arena_state: std.heap.ArenaAllocator = .init(gpa); export fn patch(text: [*]const u8, len: usize) ?*const Header { _ = arena_state.reset(.retain_capacity); - return stack(arena_state.allocator(), text[0..len]) catch null; + return stack(&.{ .arena = arena_state.allocator() }, text[0..len]) catch null; +} + +fn patchFile(text: [*]const u8, len: usize, file: [*]const u8, file_len: usize) callconv(.c) ?*const Header { + start(); + _ = arena_state.reset(.retain_capacity); + var given: Given = .{ .bytes = file[0..file_len] }; + return stack(&.{ + .arena = arena_state.allocator(), + .source = Given.source, + .declarations = ps.PatchCtx.parsed, + .host = &given, + }, text[0..len]) catch null; } -fn stack(arena: std.mem.Allocator, diff: []const u8) !*const Header { - const p = try ps.formatPatch(&.{ .arena = arena }, "", diff); +/// The one file `patchFile` is handed: the first section's. A text the +/// hunk is not in is no source (`formatPatch` looks for the hunk's lines). +const Given = struct { + bytes: []const u8, + path: ?[]const u8 = null, + + fn source(ctx: *const ps.PatchCtx, _: []const u8, path: []const u8) ?ps.PatchSource { + const given: *Given = @ptrCast(@alignCast(ctx.host)); + const first = given.path orelse path; + given.path = first; + return if (std.mem.eql(u8, path, first)) .{ .path = path, .bytes = given.bytes } else null; + } +}; + +fn stack(ctx: *const ps.PatchCtx, diff: []const u8) !*const Header { + const arena = ctx.arena; + const p = try ps.formatPatch(ctx, "", diff); // The text, then each row's path where it changes from the row before. var text: std.ArrayList(u8) = .empty; try text.appendSlice(arena, p.text); diff --git a/build.zig b/build.zig index 69ada42f..add0aaf7 100644 --- a/build.zig +++ b/build.zig @@ -415,7 +415,7 @@ pub fn build(b: *std.Build) void { /// pardes's highlighter; or, with no language, the patch view alone, with /// no tree-sitter in it. Its exports are abi/wasm.zig's (`memory`, /// `_initialize`, `reserve`, `release`, `patch`, and with a language -/// `highlight`), the same in every module; docs/typ/building.typ has their +/// `highlight` and `patchFile`), the same in every module; docs/typ/building.typ has their /// layouts and the WASI imports a page stubs. The package's dependency on /// pardes is named "pardes". A name the manifest does not have fails the /// configure, as `.languages` does. @@ -429,7 +429,7 @@ pub fn wasmModule(b: *std.Build, options: struct { else b.dependency("pardes", .{ .target = target, .optimize = options.optimize, .grammars = .none }); const exports = b.addOptions(); - exports.addOption(bool, "highlight", options.language != null); + exports.addOption(bool, "language", options.language != null); const module = b.addExecutable(.{ .name = b.fmt("pardes-{s}", .{options.language orelse "patch"}), .root_module = b.createModule(.{ @@ -445,7 +445,7 @@ pub fn wasmModule(b: *std.Build, options: struct { module.entry = .disabled; module.wasi_exec_model = .reactor; // Its own functions alone: tree-sitter's and libc's stay inside. - module.root_module.export_symbol_names = if (options.language != null) &.{ "reserve", "release", "patch", "highlight" } else &.{ "reserve", "release", "patch" }; + module.root_module.export_symbol_names = if (options.language != null) &.{ "reserve", "release", "patch", "highlight", "patchFile" } else &.{ "reserve", "release", "patch" }; return module; } diff --git a/docs/typ/building.typ b/docs/typ/building.typ index 69468042..9a0bab44 100644 --- a/docs/typ/building.typ +++ b/docs/typ/building.typ @@ -226,9 +226,25 @@ manifest does not have fails the configure. The module is [`memory`, `_initialize`], [its memory, and what a reactor runs once before any other call], [`reserve(len)`, `release(ptr, len)`], [`len` bytes for the page to write an argument into (at least one, so `reserve(0)` is a pointer too), and their return], [`highlight(path, path_len, text, len)`], [(a module with a language) a style byte for each byte of `text`: 0 none, 1 keyword, 2 string, 3 number, 4 comment, as pardes colours the file `path` names by its extension; all 0 for a path of another language. The module's until the next `highlight`], - [`patch(text, len)`], [the diff `text` stacked as the patch view shows it, with no file and no colours: a pointer to a header. The module's until the next `patch`], + [`patch(text, len)`], [the diff `text` stacked as the patch view shows it, with no file and no colours: a pointer to a header. The module's until the next `patch` or `patchFile`], + [`patchFile(text, len, file, file_len)`], [(a module with a language) `patch` with `file`, the text of the file the diff's first section names, the new one's or the old one's: each hunk is found in it and stacks under the declarations it sits in, from the file's parse (`declaration` rows), as the editor's +Diff does; a hunk the text does not hold, and the diff's other files, stack as with no file. The same header and records as `patch`], ) +xit writes its hunks' `@@` with nothing after it; with the file's text a +hunk still gets what it sits in. A page holding a commit's diff of +`src/lib.rs` and the file's new text calls (`put` copies bytes into a +`reserve`d buffer and gives the pointer and length): + +``` +const [d, dn] = put(diffBytes), [f, fn] = put(fileBytes); +const header = rust.exports.patchFile(d, dn, f, fn); // as patch's +``` + +and reads the rows as it reads `patch`'s. With the new text the labels and +declarations are numbered as the new file is; with the old text, as the +old one. Its cost is the file's parse: 18 ms against `patch`'s 4 for a +28-hunk diff of a 1,100-line Zig file, under node. + Each returns 0 when its memory runs out. Pointers and lengths are wasm32's: unsigned 32-bit; in memory they are little-endian. `patch`'s header is five u32, 20 bytes: @@ -242,7 +258,7 @@ header is five u32, 20 bytes: and a row's record: #pairs( - [0 `kind`], [0 other, 1 meta, 2 hunk, 3 declaration (git's words after the `@@`), 4 context, 5 added, 6 removed], + [0 `kind`], [0 other, 1 meta, 2 hunk, 3 declaration (git's words after the `@@`; with `patchFile`, a declaration's `path:line`, whose `code_start` is its whole length, and its header's lines), 4 context, 5 added, 6 removed], [4 `old`, 8 `new`], [its numbers in the old and the new file, from 1; 0 where it has none], [12 `code_start`], [where its code starts in its text: after a hunk label's `path:line` and stars], [16 `text_offset`, 20 `text_len`], [its text, without its line end (the `\n`, and a `\r` before it), in the header's `text`], diff --git a/test/consumer/wasm.mjs b/test/consumer/wasm.mjs index 9e76af0f..97b0ba6b 100644 --- a/test/consumer/wasm.mjs +++ b/test/consumer/wasm.mjs @@ -56,6 +56,20 @@ function patch(m, diff) { const [p, n] = put(m, diff); const h = m.ex.patch(p, n); m.ex.release(p, n); + return read(m, h); +} + +// patchFile: the same, with the text of the file the diff's first section names +function patchFile(m, diff, text) { + const [p, n] = put(m, diff); + const [t, tn] = put(m, text); + const h = m.ex.patchFile(p, n, t, tn); + m.ex.release(p, n); + m.ex.release(t, tn); + return read(m, h); +} + +function read(m, h) { const v = new DataView(m.mem()); const [text, textLen, styles, rows, count] = [0, 4, 8, 12, 16].map((o) => v.getUint32(h + o, true)); const bytes = new Uint8Array(m.mem(), text); @@ -109,5 +123,29 @@ for (const file of process.argv.slice(2)) { expect(`${file} highlight another language`, [...new Uint8Array(m.mem(), other, tn)].every((b) => b === 0), true); } } +// patchFile (a module with a language): xit's bare `@@`, and the file's +// text: the declaration the hunk sits in, from the file's own parse +const oldRs = "fn total(items: &[u32]) -> u32 {\n let mut sum = 0;\n let mut n = 0;\n for i in items { sum += i; }\n n += 1;\n sum\n}\n"; +const newRs = "// sums\n" + oldRs.replace("sum += i;", "sum += *i;"); +const bare = "diff --git a/src/lib.rs b/src/lib.rs\n--- a/src/lib.rs\n+++ b/src/lib.rs\n@@ -0,0 +1 @@\n+// sums\n@@ -3,3 +4,3 @@\n let mut n = 0;\n- for i in items { sum += i; }\n+ for i in items { sum += *i; }\n n += 1;\n"; +const more = bare + "diff --git a/src/b.rs b/src/b.rs\n--- a/src/b.rs\n+++ b/src/b.rs\n@@ -3,3 +4,3 @@\n let mut n = 0;\n- for i in items { sum += i; }\n+ for i in items { sum += *i; }\n n += 1;\n"; +const language = process.argv.slice(2).map(load).find((m) => m.ex.highlight); +if (language) { + const lines = (p) => p.rows.map((r) => [r.kind, r.text]); + const plain = lines(patch(language, bare)); + // the new file's text: its numbers + expect("patchFile new text", lines(patchFile(language, bare, newRs)), [ + ["hunk", "src/lib.rs:1"], ["added", "+// sums"], + ["declaration", "src/lib.rs:2"], ["declaration", " fn total(items: &[u32]) -> u32 {"], + ["hunk", "src/lib.rs:5 *"], ["context", " let mut n = 0;"], ["removed", "- for i in items { sum += i; }"], ["added", "+ for i in items { sum += *i; }"], ["context", " n += 1;"], + ]); + // the old file's: found on its side, and numbered so + expect("patchFile old text", lines(patchFile(language, bare, oldRs)).slice(2, 5), [["declaration", "src/lib.rs:1"], ["declaration", " fn total(items: &[u32]) -> u32 {"], ["hunk", "src/lib.rs:4 *"]]); + // a text the diff is not of: the rows as with none + expect("patchFile another text", lines(patchFile(language, bare, "nothing like it\n")), plain); + // a second file: as with no text + const two = lines(patchFile(language, more, newRs)); + expect("patchFile second file", two.slice(9), lines(patch(language, more)).slice(plain.length)); +} if (failed) process.exit(1); console.log("wasm: the modules run"); -- cgit v1.3 From 2d25d58f8132c54ca0f853899d6b525c4ae892e4 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 01:37:10 -0300 Subject: layers: the source view's painters a seam with nothing to see but one word: File.Layers (core/File.zig, beside recolorSyntax), a pane's field that each view keeps its own (views.zig pane_fields), says which painters a file's body wears and writes down their order and places (1 the ink, tree-sitter's colour a code cell; 2 the patch, a diff's grounds, marker and changed words; next, ruled and not built: changes, a lane after the line number, green and red grounds, a changed line's words, ghost rows; churn, a heat lane and a strip by the scroll thumb), both still painted in recolorSyntax's one walk; Syntax (a tag word, SPC t h: SPC t s is the pdf addon's PdfSections, a ctl line) turns the ink off in this view and on again; the ink off is no style byte read at all (a test a cell, as a branch or a mask, cost the frame 0.1 to 0.5% of its instructions, 0.15 to 0.47% on the long line; a walk specialised at comptime for each state cost 0.5 to 3.4%: the gate measured all three), so in a patch Syntax takes its grounds too; File.zig's test draws a .zig text's first row with the ink, without it, in a second view that keeps its own, and with it again; tui core-test 876/1034 (158 skipped); the tip's gate: frames 77/77, the 121 counts within 0.1% of tree3 (largest +0.026%), perfab -0.013% Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/File.zig | 82 +++++++++++++++++++++++++++++++++++++++++++++- core/builtins.zig | 9 +++++ core/config.zig | 1 + core/panes.zig | 2 ++ core/views.zig | 3 +- docs/typ/builtins-gui.json | 1 + docs/typ/builtins-tui.json | 1 + docs/typ/guide.typ | 3 ++ 8 files changed, 100 insertions(+), 2 deletions(-) (limited to 'docs/typ') diff --git a/core/File.zig b/core/File.zig index 8a8c05de..813e172f 100644 --- a/core/File.zig +++ b/core/File.zig @@ -1847,6 +1847,27 @@ fn fillBody(tab: u16, dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_w return written; } +/// The layers a file's body wears in a view (`Pane.layers`, each view its +/// own: views.zig). Not Layer.zig's band of cells: these are the painters +/// over a body's text, in this order, each in its own place: +/// +/// 1. ink: each code cell's colour, from tree-sitter (syntax.zig's +/// highlightFileRange): on until `Syntax` turns it off; +/// 2. patch: a diff's or a patch's grounds, a `+`/`-` row's ground and +/// marker and the words a changed line changed (syntax.zig's +/// highlightDiff): always, in a diff (its style bytes are the ink's +/// too: `Syntax` off takes both). +/// +/// Both are painted in recolorSyntax's one walk over the cells, each where +/// it says (one walk per painter cost a frame a sixth more). Ruled, not +/// built (PARDES.md "Changes on the source view"): 3. changes: a lane after +/// the line number, a line added whole green across it, a changed line's +/// words tinted, ghost rows for what the shown revision has not; 4. churn: +/// a heat lane after the number and a strip by the scroll thumb. +pub const Layers = struct { + ink: bool = true, +}; + pub const SynStyle = struct { fg: [3]u8, bold: bool }; pub fn synStyle(p: *Pardes, sy: syntax.Syn) ?SynStyle { @@ -1856,7 +1877,10 @@ pub fn synStyle(p: *Pardes, sy: syntax.Syn) ?SynStyle { /// syntax colors: recolor each content cell from its tree-sitter style byte; /// content starts after the lineno gutter pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void { - const highlights = if (f.mini) |mini| mini.colors else f.highlights; + // The ink off (`Syntax`): no style byte is read, so a cell asks + // nothing of it (a test a cell cost a frame 0.1 to 0.5%). A patch's + // grounds are bytes of the same painter's: they go with it. + const highlights: []const u8 = if (!pane.layers.ink) &.{} else if (f.mini) |mini| mini.colors else f.highlights; const highlight_start = if (f.mini != null) 0 else f.highlight_start; const spans = f.pager_spans; if (highlights.len == 0 and f.output == null and spans.len == 0) return; @@ -1911,6 +1935,7 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. grounds = .of(p.theme()); break :ground grounds.?; }).forStyle(lead); + // 2, the patch: the row's ground. if (tint) |t| if (prefix_width < tw) { 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); @@ -1950,6 +1975,7 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. if (idx >= highlight_start) { const hidx = idx - highlight_start; if (hidx < highlights.len) { + // 1, the ink; a patch row's marker is 2's. if (if (tint != null and hs + c == 0) SynStyle{ .fg = tint.?.ink, .bold = true } else @@ -1963,6 +1989,7 @@ pub fn recolorSyntax(p: *Pardes, s: *Surface, pane: *Pane, f: *State, r: pardes. cell.style.bold = ss.bold; } } + // 2, the patch: a changed word's ground. 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) @@ -2525,3 +2552,56 @@ test "context cache frees each allocation with its original allocator" { try std.testing.expect(cache.allocator == null); try std.testing.expectEqual(@as(usize, 0), cache.declarations.len); } + +/// The inks of row `row`'s first `n` text cells of pane `id` as `s` draws them. +fn rowInks(s: *pardes.Surface, pane: *const Pane, id: usize, row: u16, out: []pardes.Color) void { + const body = s.region(.body, id).?.rect; + const y: usize = body.y + row; + for (out, 0..) |*ink, i| { + const cell = s.cells[y * s.cols + body.x + gutterWidth(pane) + i]; + ink.* = cell.style.fg; + } +} + +test "Syntax takes a text's ink off in this view and puts it back, and another view keeps its own" { + if (!syntax.supportsPath("/test.zig")) return error.SkipZigTest; + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 12 }); + defer p.deinit(); + const pane = try p.setTestFile("pub const x = 1;\n"); + gpa.free(pane.file.?.path); + pane.file.?.path = try gpa.dupe(u8, "/test.zig"); + pane.file.?.syntax_dirty = true; + const id = p.view().active; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const plain: pardes.Color = if (p.theme().fg) |c| .{ .rgb = c } else .default; + var inks: [16]pardes.Color = undefined; + const Frame = struct { + fn take(q: *Pardes, a: *std.heap.ArenaAllocator, shown: *const Pane, at: usize, out: []pardes.Color) !void { + q.sync(); + _ = a.reset(.retain_capacity); + rowInks(try q.render(a.allocator()), shown, at, 0, out); + } + fn colored(out: []const pardes.Color, fg: pardes.Color) bool { + for (out) |c| if (!std.meta.eql(c, fg)) return true; + return false; + } + }; + try Frame.take(p, &arena, pane, id, &inks); + try std.testing.expect(Frame.colored(&inks, plain)); + const other = p.openView().?; + p.update(.{ .command = "Syntax" }); + try std.testing.expect(!pane.layers.ink); + try Frame.take(p, &arena, pane, id, &inks); + try std.testing.expect(!Frame.colored(&inks, plain)); + // The other view's text keeps its ink; this one's stays off. + p.toView(other); + try Frame.take(p, &arena, pane, id, &inks); + try std.testing.expect(Frame.colored(&inks, plain)); + p.toView(.at(0)); + try std.testing.expect(!pane.layers.ink); + p.update(.{ .command = "Syntax" }); + try Frame.take(p, &arena, pane, id, &inks); + try std.testing.expect(Frame.colored(&inks, plain)); +} diff --git a/core/builtins.zig b/core/builtins.zig index 7ad70e7c..b516d543 100644 --- a/core/builtins.zig +++ b/core/builtins.zig @@ -1060,6 +1060,15 @@ pub const Filter = struct { } }; +/// Turn a text's syntax colours off in this view, or on again. +/// The ink layer (File.Layers). +pub const Syntax = struct { + pub fn run(c: Ctx) void { + if (c.pane.file == null) return c.p.reportFailure(c.id, "Syntax: only a text pane has it"); + c.pane.layers.ink = !c.pane.layers.ink; + } +}; + /// Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text. `Diff ` stacks that diff's, `Diff ` git show's. /// The diff viewer's one registration: its word and traits here, all else /// its own (hunks.zig). diff --git a/core/config.zig b/core/config.zig index f43604ad..998063cc 100644 --- a/core/config.zig +++ b/core/config.zig @@ -121,6 +121,7 @@ pub const leader_path = paths: { .Msg = null, .Verbose = null, .Wrap = "tw", + .Syntax = "th", .NextColor = "tn", .Themes = "tt", .Theme = null, diff --git a/core/panes.zig b/core/panes.zig index 174af241..e8f35de8 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -318,6 +318,8 @@ pub const Pane = struct { /// step's `sync` (normal.halfPageMove's scroll), and a core loaded from a /// dump has had none (Replica.initDump). view: SessionView = .{}, + /// The painters a file's body wears in this view (File.Layers). + layers: File.Layers = .{}, sel: [3]Sel = @splat(.{}), pointer_selections: [3]?PointerSelection = @splat(null), next_pointer_selection: u64 = 0, diff --git a/core/views.zig b/core/views.zig index 89dcb454..7230909a 100644 --- a/core/views.zig +++ b/core/views.zig @@ -33,7 +33,7 @@ pub const max = 4; /// A pane's fields that are each view's own: where it is in the view's /// layout, which of its texts has the keyboard, how far it is scrolled, and /// what the view's step measured of it (its tag's rows, its bands). -const pane_fields = [_][:0]const u8{ "focus", "vweight", "collapsed", "docked_to", "hscroll", "tag_scroll", "tag_top", "tag_rows", "view", "notices", "pan", "follow_scroll" }; +const pane_fields = [_][:0]const u8{ "focus", "vweight", "collapsed", "docked_to", "hscroll", "tag_scroll", "tag_top", "tag_rows", "view", "layers", "notices", "pan", "follow_scroll" }; /// The body's: its cursor, selections and mode. Its undo stays the pane's. const body_fields = [_][:0]const u8{ "mode", "cur_pinned", "cur_row", "cur_col", "vsel", "sels", "nsel", "select", "sticky_col", "restore_cursor", "last_edit", "reg_wait", "normal", "find_op", "find_ch" }; @@ -49,6 +49,7 @@ pub const PaneView = struct { tag_top: u16 = 0, tag_rows: u16 = 1, view: Pane.SessionView = .{}, + layers: File.Layers = .{}, notices: Pane.Notices = .{}, pan: u16 = 0, follow_scroll: usize = 0, diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index 34a46fa6..16a1aac8 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -92,6 +92,7 @@ {"name": "Subtypes", "leader": "SPC l T", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the subtypes of the type under the cursor."}, {"name": "Supertypes", "leader": "SPC l t", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the supertypes of the type under the cursor."}, {"name": "Symbols", "leader": "SPC l s", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the file's symbols from the language server."}, + {"name": "Syntax", "leader": "SPC t h", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Turn a text's syntax colours off in this view, or on again."}, {"name": "Tab", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "A tab's width in cells, 1 through 16, in every pane; bare, it says the width."}, {"name": "TaglineSize", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Scale the tag font, a percentage."}, {"name": "Term", "leader": "SPC n t", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "A shell in the calling pane's directory, raw from the first frame."}, diff --git a/docs/typ/builtins-tui.json b/docs/typ/builtins-tui.json index 5919a77a..39f762f2 100644 --- a/docs/typ/builtins-tui.json +++ b/docs/typ/builtins-tui.json @@ -87,6 +87,7 @@ {"name": "Subtypes", "leader": "SPC l T", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the subtypes of the type under the cursor."}, {"name": "Supertypes", "leader": "SPC l t", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the supertypes of the type under the cursor."}, {"name": "Symbols", "leader": "SPC l s", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the file's symbols from the language server."}, + {"name": "Syntax", "leader": "SPC t h", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Turn a text's syntax colours off in this view, or on again."}, {"name": "Tab", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "A tab's width in cells, 1 through 16, in every pane; bare, it says the width."}, {"name": "Term", "leader": "SPC n t", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "A shell in the calling pane's directory, raw from the first frame."}, {"name": "Theme", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Switch to the named theme."}, diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index 3dd8107c..127b22a9 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -283,6 +283,9 @@ or one above it. #word("Diff") on a `+Diff` shows the diff itself as text (a paged one's `+Pager` is closed once stacked), and on the text stacks it again. +#word("Syntax") (#key("SPC t h")) turns a text's syntax colours off in +this view, and on again. + = Call hierarchy Put the cursor on a function and run #word("Callstack") (#key("g c") or #key("SPC l b")). -- cgit v1.3 From f9ff1acdf7cebf417a3c74d53f8e2d67cfbdbcc2 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 02:03:46 -0300 Subject: layers: a file at a revision: the address path@rev and path@rev:line, resolved by a Look anywhere (a file really named so wins; the path must be a file), and At in a file's pane, open the file as jj has it at that revision in a pane named path@rev, coloured as its file (File.langPath), read-only (File.edit refuses a key's splice, edit.zig a whole text's; a bare Save says so); At in such a pane turns it to another revision in its place, bare it goes back to the file; what jj says is the session machine's: core/jj.zig runs it as a site of the step's tape (Site.jj: jj --ignore-working-copy file show, in the file's directory, the name a literal fileset), on an io of its own (the tape's spawns nothing: its allocator fails), its answer recorded, a replica replaying it and never running jj; jj's refusals in its words (At: Revision `x` doesn't exist, No such path, no jj); tests in a jj repository made in the test's directory: At's open, the read-only edits, the Look at a line, the turn in place, the refusals, and a client that replays the open of path@rev:2 ends with the session's digest; tui core-test 879/1037 (158 skipped); the tip gated whole: core-test 880/1038, shell-test 1080/1083, pane-test 183/184, behaviour-test 275/275 and --replay, process-test 0 of 145 failed, term 17/17, kitty 45/45, addons 5/5, consumer-test, both soaks diverged 0, unequal 0, unlisted 0, corpus through a client 22 scenes, daemon.py far, games, window-clients, clients x5, relink, launch, pair, gui, and --clients x2 on ReleaseSafe, macOS and FreeBSD cross-builds; daemon.py plain on ReleaseSafe times out at pair rows as main itself does (2 of 2 on main) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/File.zig | 13 +- core/Output.zig | 5 +- core/builtins.zig | 11 ++ core/config.zig | 1 + core/edit.zig | 2 + core/jj.zig | 337 +++++++++++++++++++++++++++++++++++++++++++++ core/look.zig | 2 + core/panes.zig | 2 +- core/root.zig | 1 + core/tape.zig | 3 + docs/typ/builtins-gui.json | 1 + docs/typ/builtins-tui.json | 1 + docs/typ/guide.typ | 10 ++ 13 files changed, 385 insertions(+), 4 deletions(-) create mode 100644 core/jj.zig (limited to 'docs/typ') diff --git a/core/File.zig b/core/File.zig index 813e172f..01aaeec8 100644 --- a/core/File.zig +++ b/core/File.zig @@ -697,6 +697,9 @@ const swap_min = 64 << 10; /// a new buffer in and gives the old to the journal whole (a swap); an /// undo's swap back hands the buffer it replaces to `kept`. fn edit(p: *Pardes, f: *State, off: usize, len: usize, bytes_in: []const u8, whole: ?[]u8, journaled: bool, kept: ?*[]u8) bool { + // A file at a revision is read-only (jj.zig): a key's splice changes + // nothing (a whole text is the editor's to refuse, edit.zig). + if (whole == null) if (f.output) |o| if (o.from == .revision) return false; const old_len = f.content.len; const new_len = old_len - len + bytes_in.len; const span: Span = .{ .head = off, .tail = old_len - off - len }; @@ -1607,7 +1610,7 @@ pub fn refreshHighlights(p: *Pardes) void { syntax.highlightLocationRows(p.tree_sitter_gpa, f.content, f.location_rows) else syntax.highlightLocations(p.tree_sitter_gpa, f.content, start, end), - else => syntax.highlightFileRange(p.tree_sitter_gpa, f.path, f.content, start, end), + else => syntax.highlightFileRange(p.tree_sitter_gpa, langPath(f), f.content, start, end), }) catch { f.syntax_dirty = false; continue; @@ -1641,7 +1644,13 @@ fn paintAhead(p: *Pardes, pane: *Pane, f: *State) void { const end = @max(start, lineStart(p.gpa, f, f.scroll + (if (seen.dir > 0) 4 * rows else rows) + SYNTAX_CONTEXT_AFTER_ROWS)); // Painted already, as far as that goes. if (f.highlights.len > 0 and start >= f.highlight_start and end <= f.highlight_start + f.highlights.len) return; - Stream.paintAhead(p, pane.serial, f.revision, f.path, f.content, start, end); + Stream.paintAhead(p, pane.serial, f.revision, langPath(f), f.content, start, end); +} + +/// The path a text's language is known by: a file at a revision's +/// (jj.zig) without its `@rev`. +pub fn langPath(f: *const State) []const u8 { + return if (@import("jj.zig").of(f)) |r| r.path else f.path; } pub fn supportsContext(pane: *const Pane) bool { diff --git a/core/Output.zig b/core/Output.zig index c7bfde14..09ec2a51 100644 --- a/core/Output.zig +++ b/core/Output.zig @@ -38,6 +38,8 @@ pub const Origin = union(enum) { /// A query pane's +Preview (Query.zig): a file's text shown, not yet /// its pane; Enter promotes it to one where it stands. preview, + /// A file at a revision (jj.zig), its arg the revision. + revision, }; /// An output's argument is typed in the bounded one-line tag storage. @@ -163,6 +165,7 @@ pub fn traits(o: Origin) Traits { .kind => .{ .name = "", .steps = true, .locations = true }, .unsaved => .{ .name = config.unsaved_buffer, .doc = true }, .preview => .{ .name = config.preview_buffer, .doc = true }, + .revision => .{ .name = "", .doc = true }, // Named for its directory, not a `+` name in it. .dir => .{ .name = "", .doc = true }, .cmd => |b| builtins.registry.outputTraits(b) orelse unreachable, @@ -264,7 +267,7 @@ fn sortResults(arena: std.mem.Allocator, from: Origin, content: []u8, anchor: ?u => {}, else => return anchor, }, - .errors, .kind, .unsaved, .dir, .preview => return anchor, + .errors, .kind, .unsaved, .dir, .preview, .revision => return anchor, } if (content.len == 0) return anchor; const trailing_newline = content[content.len - 1] == '\n'; diff --git a/core/builtins.zig b/core/builtins.zig index b516d543..18b49a41 100644 --- a/core/builtins.zig +++ b/core/builtins.zig @@ -983,6 +983,11 @@ pub const Save = struct { }; const path = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); if (path.len > 0) return exec.saveTo(c.p, c.id, path); + // A file at a revision (jj.zig) is read-only: written elsewhere only. + if (c.pane.file) |*file| if (@import("jj.zig").of(file) != null) { + var said: pardes.Kind.Buf(limits.host_path_cap + 64) = .{}; + return c.p.reportFailure(c.id, said.print("Save: {s} is a revision, read-only (Save writes it)", .{file.path[0..@min(file.path.len, limits.host_path_cap)]})); + }; // A `+` name is a generated pane's (+Tutor), no file of its own: // a bare Save asks for a path, as a +New scratch's does. if (c.pane.file) |file| if (file.output == null and !std.mem.startsWith(u8, std.Io.Dir.path.basename(file.path), "+")) return exec.saveFile(c.p, c.id); @@ -1069,6 +1074,12 @@ pub const Syntax = struct { } }; +/// Show a file as it was at revision `rev` (jj), read-only, beside its pane; in such a pane, that file at another revision in its place, or bare, the file. +pub const At = struct { + pub const takes_arg = true; + pub const run = @import("jj.zig").word; +}; + /// Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text. `Diff ` stacks that diff's, `Diff ` git show's. /// The diff viewer's one registration: its word and traits here, all else /// its own (hunks.zig). diff --git a/core/config.zig b/core/config.zig index 998063cc..361a59ed 100644 --- a/core/config.zig +++ b/core/config.zig @@ -76,6 +76,7 @@ pub const leader_path = paths: { .DelBelow = null, .Filter = null, .Diff = null, + .At = null, .Mode = null, .Togglettymode = null, .Collapse = null, diff --git a/core/edit.zig b/core/edit.zig index 0014f681..7a57fd09 100644 --- a/core/edit.zig +++ b/core/edit.zig @@ -705,6 +705,8 @@ fn setEditTextSpan(e: Editor, t: *Text, new: []u8, known_end: ?modal.Cursor, spa return; } const pane = t.pane() orelse return retireEditText(e, new); + // A file at a revision is read-only (jj.zig). + if (pane.file) |*f| if (f.output) |o| if (o.from == .revision) return retireEditText(e, new); // A live query pane's rows are its line 1's (Query.zig): an edit there // is refused, as a tag's prefix refuses one, and one from line 1 into // them is cut at its end. The rows' metadata stays theirs across an diff --git a/core/jj.zig b/core/jj.zig new file mode 100644 index 00000000..368d03a5 --- /dev/null +++ b/core/jj.zig @@ -0,0 +1,337 @@ +//! A file at a revision, as jj shows it (PARDES.md "Changes on the source +//! view"): the address `path@rev`, with a place `path@rev:line`, which a +//! Look resolves anywhere, and `At ` in a file's pane. +//! +//! What jj says is the session machine's: it is run out of the turn as a +//! site of the step's tape (`Site.jj`), its answer recorded; a replica +//! replays the answer and never runs jj. A revision's pane is an output +//! (`Output.Origin.revision`, its argument the revision), named +//! `path@rev`, coloured as its file (File.langPath), read-only (File.edit +//! refuses its text a change; a bare Save says why). +const std = @import("std"); +const pardes = @import("root.zig"); +const Pardes = pardes.Pardes; +const Pane = pardes.Pane; +const File = pardes.panes.File; +const Output = pardes.panes.Output; +const look = @import("look.zig"); +const layout = @import("layout.zig"); + +/// What jj answered: why not, in its own words (its first line, without +/// `Error: `), or the file's bytes. The caller's, in the allocator the site +/// was given. +pub const Shown = union(enum) { refused: []u8, bytes: []u8 }; + +/// The longest text a revision's pane takes. +const bytes_max = 256 << 20; + +/// `text`, not a file of its own, read as `path@rev`: the text before its +/// first `@` the path, the rest the revision (`main`, `@-`, `main@origin`). +pub fn split(text: []const u8) ?struct { path: []const u8, rev: []const u8 } { + const at = std.mem.indexOfScalar(u8, text, '@') orelse return null; + if (at == 0 or at + 1 == text.len or text[at - 1] == '/') return null; + return .{ .path = text[0..at], .rev = text[at + 1 ..] }; +} + +/// The file at `path` (absolute) at revision `rev`, as jj shows it. +pub fn show(p: *Pardes, path: []const u8, rev: []const u8) Shown { + const set = fileset(p.scratch.allocator(), path) catch return refusal(p.gpa, "out of memory"); + return p.tape.site(.jj, p.gpa, runHost, .{ p.gpa, dirOf(path), @as([]const []const u8, &.{ "file", "show", "-r", rev, "--", set }) }); +} + +fn dirOf(path: []const u8) []const u8 { + return std.Io.Dir.path.dirname(path) orelse "/"; +} + +/// The name of `path` as a fileset of that one file in its directory, +/// taken literally whatever it is called. +fn fileset(arena: std.mem.Allocator, path: []const u8) ![]const u8 { + var set: std.ArrayList(u8) = .empty; + try set.appendSlice(arena, "file:\""); + for (std.Io.Dir.path.basename(path)) |c| { + if (c == '"' or c == '\\') try set.append(arena, '\\'); + try set.append(arena, c); + } + try set.append(arena, '"'); + return set.items; +} + +/// jj with `args`, run in `dir`: what it printed, or its refusal. The +/// working copy is left alone (`--ignore-working-copy`): an editor's read +/// makes no operation, and `@` is the working copy as jj last saw it. +fn runHost(gpa: std.mem.Allocator, dir: []const u8, args: []const []const u8) Shown { + // The tape's io spawns nothing (its allocator fails, its environment is + // empty): one of its own, with this process's environment. + var threaded: std.Io.Threaded = .init_single_threaded; + threaded.allocator = gpa; + threaded.environ = .{ .process_environ = .{ .block = .{ .slice = std.mem.span(std.c.environ) } } }; + threaded.environ_initialized = false; + const io = threaded.io(); + var argv: std.ArrayList([]const u8) = .empty; + defer argv.deinit(gpa); + argv.appendSlice(gpa, &.{ "jj", "--ignore-working-copy", "--color=never", "--no-pager" }) catch return refusal(gpa, "out of memory"); + argv.appendSlice(gpa, args) catch return refusal(gpa, "out of memory"); + // As Stream's children: this thread's mask is the child's. + const none = std.posix.sigemptyset(); + var kept: std.posix.sigset_t = undefined; + std.posix.sigprocmask(std.posix.SIG.SETMASK, &none, &kept); + var child = std.process.spawn(io, .{ .argv = argv.items, .cwd = .{ .path = dir }, .stdin = .ignore, .stdout = .pipe, .stderr = .pipe }) catch |err| { + std.posix.sigprocmask(std.posix.SIG.SETMASK, &kept, null); + return refusal(gpa, if (err == error.FileNotFound) "no jj" else @errorName(err)); + }; + std.posix.sigprocmask(std.posix.SIG.SETMASK, &kept, null); + defer child.kill(io); + // One after the other, on an io with no thread to read both at once: + // jj says a refusal in a line and nothing on stdout. + var out: std.ArrayList(u8) = .empty; + defer out.deinit(gpa); + var err: std.ArrayList(u8) = .empty; + defer err.deinit(gpa); + for ([_]std.Io.File{ child.stdout.?, child.stderr.? }, [_]*std.ArrayList(u8){ &out, &err }, [_]usize{ bytes_max, 64 << 10 }) |from, to, cap| { + var chunk: [64 * 1024]u8 = undefined; + while (to.items.len <= cap) { + const n = from.readStreaming(io, &.{&chunk}) catch break; + if (n == 0) break; + to.appendSlice(gpa, chunk[0..n]) catch return refusal(gpa, "out of memory"); + } + } + const term = child.wait(io) catch |e| return refusal(gpa, @errorName(e)); + if (out.items.len > bytes_max) return refusal(gpa, "too much to show"); + if (term == .exited and term.exited == 0) return .{ .bytes = out.toOwnedSlice(gpa) catch return refusal(gpa, "out of memory") }; + var first = std.mem.trim(u8, err.items[0 .. std.mem.indexOfScalar(u8, err.items, '\n') orelse err.items.len], " \t\r"); + if (std.mem.startsWith(u8, first, "Error: ")) first = first["Error: ".len..]; + return refusal(gpa, if (first.len > 0) first else "jj failed"); +} + +fn refusal(gpa: std.mem.Allocator, why: []const u8) Shown { + return .{ .refused = gpa.dupe(u8, why) catch &.{} }; +} + +/// A revision's pane: the file it is of (its name without `@rev`) and the +/// revision. Null for any other pane. +pub fn of(f: *const File.State) ?struct { path: []const u8, rev: []const u8 } { + const o = f.output orelse return null; + if (o.from != .revision) return null; + return .{ .path = f.path[0 .. f.path.len - o.arg().len - 1], .rev = o.arg() }; +} + +/// `path` (absolute) at `rev` in a pane: the one showing it focused, else +/// one made beside pane `near` (or, with `replace`, in its place: it goes), +/// wearing `near`'s layers; its cursor on line `line` (0: the first). Said +/// at `near` when jj refuses. The pane's id. +pub fn open(p: *Pardes, near: usize, path: []const u8, rev: []const u8, at: look.Spot, replace: bool) ?usize { + const name = std.fmt.allocPrint(p.scratch.allocator(), "{s}@{s}", .{ path, rev }) catch return null; + for (p.panes, 0..) |slot, i| if (slot) |shown| if (shown.file) |*f| if (of(f) != null and std.mem.eql(u8, f.path, name)) { + look.focusPaneLine(p, i, at, .center); + return i; + }; + if (rev.len > Output.max_arg) return refused(p, near, "a revision that long"); + const free = p.freeSlot() orelse { + p.reportError(.at(near), "At", error.NoPaneSlots); + return null; + }; + const bytes = switch (show(p, path, rev)) { + .refused => |why| { + defer p.gpa.free(why); + return refused(p, near, why); + }, + .bytes => |b| b, + }; + const pane = Output.open(p, free, std.Io.Dir.path.dirname(path) orelse "/", .revision, rev, bytes) catch |err| { + p.gpa.free(bytes); + p.reportError(.at(near), "At", err); + return null; + }; + const f = &pane.file.?; + const owned = p.gpa.dupe(u8, name) catch { + p.removePane(free, near) catch {}; + return null; + }; + p.gpa.free(f.path); + f.path = owned; + if (p.panes[near]) |from| pane.layers = from.layers; + layout.placeNew(p, near, near, free, .doc); + if (replace) p.removePane(near, free) catch |err| p.reportError(.at(free), "At", err); + layout.compute(p); + // Sized for its place before it is centred there. + p.sync(); + look.focusPaneLine(p, free, at, .center); + return free; +} + +fn refused(p: *Pardes, id: usize, why: []const u8) ?usize { + var line: pardes.Kind.Buf(512) = .{}; + p.reportFailure(id, line.print("At: {s}", .{why[0..@min(why.len, 480)]})); + return null; +} + +/// The `At` word (builtins.zig registers it): in a file's pane, that file +/// at revision `rev` beside it; in a revision's pane, the same file at +/// `rev` in its place, its cursor's line kept; bare there, the file. +pub fn word(c: pardes.builtins.Ctx) void { + const p = c.p; + const f = if (c.pane.file) |*file| file else return p.reportFailure(c.id, "At: only a file's pane takes it"); + const rev = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + const at: look.Spot = .{ .line = @intCast(@max(0, c.pane.body.cur_row) + 1) }; + if (of(f)) |r| { + if (rev.len == 0) return look.lookAt(p, c.id, r.path); + const path = p.scratch.allocator().dupe(u8, r.path) catch return; + _ = open(p, c.id, path, rev, at, true); + return; + } + if (f.output != null or pardes.filesystem.localPath(f.path) == null) return p.reportFailure(c.id, "At: only a file's pane takes it"); + if (rev.len == 0) return p.reportFailure(c.id, "At: which revision?"); + _ = open(p, c.id, f.path, rev, at, false); +} + +/// A Look at `text` (a path relative to `dir`, then `@rev`) that names no +/// file: a file at a revision, if the path is a file. False when it is not +/// one, for the look to go on. +pub fn looked(p: *Pardes, id: usize, dir: []const u8, text: []const u8, at: look.Spot) bool { + const r = split(text) orelse return false; + const path = std.Io.Dir.path.resolvePosix(p.scratch.allocator(), &.{ dir, r.path }) catch return false; + if (pardes.filesystem.localPath(path) == null or pardes.exec.kindOf(p.tape, path) != .file) return false; + _ = open(p, id, path, r.rev, at, false); + return true; +} + +// ---- tests ---- + +const testing = std.testing; + +test "path@rev splits at its first @: a path before it, a revision after" { + const cases = [_]struct { []const u8, []const u8, []const u8 }{ + .{ "a.zig@main", "a.zig", "main" }, + .{ "core/File.zig@@-", "core/File.zig", "@-" }, + .{ "x.zig@main@origin", "x.zig", "main@origin" }, + }; + for (cases) |c| { + const got = split(c[0]).?; + try testing.expectEqualStrings(c[1], got.path); + try testing.expectEqualStrings(c[2], got.rev); + } + for ([_][]const u8{ "@p12", "a.zig@", "a.zig", "dir/@x" }) |text| try testing.expect(split(text) == null); +} + +/// A jj repository in a test's directory: `a.zig` committed as `one`, then +/// as `two`, and `three` in its working copy, never snapshotted. Null with +/// no jj to run. +const Repo = struct { + tmp: testing.TmpDir, + dir: []const u8, + file: []const u8, + + const one = "const one = 1;\nconst x = 2;\n"; + const two = "const two = 2;\nconst x = 2;\nconst y = 3;\n"; + const three = "const three = 3;\n"; + + fn init(gpa: std.mem.Allocator) !?Repo { + var tmp = testing.tmpDir(.{}); + errdefer tmp.cleanup(); + var buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const dir = try gpa.dupe(u8, buf[0..try tmp.dir.realPath(testing.io, &buf)]); + errdefer gpa.free(dir); + if (!try run(gpa, dir, &.{ "git", "init" })) return null; + for ([_][]const u8{ one, two }, [_][]const u8{ "one", "two" }) |text, message| { + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = text }); + if (!try run(gpa, dir, &.{ "commit", "-m", message })) return null; + } + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = three }); + return .{ .tmp = tmp, .dir = dir, .file = try std.fmt.allocPrint(gpa, "{s}/a.zig", .{dir}) }; + } + + fn run(gpa: std.mem.Allocator, dir: []const u8, args: []const []const u8) !bool { + var argv: std.ArrayList([]const u8) = .empty; + defer argv.deinit(gpa); + try argv.appendSlice(gpa, &.{ "jj", "--config=user.name=t", "--config=user.email=t@t", "--quiet" }); + try argv.appendSlice(gpa, args); + const r = std.process.run(gpa, testing.io, .{ .argv = argv.items, .cwd = .{ .path = dir } }) catch return false; + gpa.free(r.stdout); + gpa.free(r.stderr); + return r.term == .exited and r.term.exited == 0; + } + + fn deinit(r: *Repo, gpa: std.mem.Allocator) void { + gpa.free(r.file); + gpa.free(r.dir); + r.tmp.cleanup(); + } +}; + +fn told(p: *Pardes, id: usize) []const u8 { + const pane = p.panes[id].?; + return pane.msg[0..pane.msg_len]; +} + +test "At shows a file at a revision beside it, read-only, coloured as its file; a Look at path@rev:line goes to it; At in it turns it in place; jj's refusals are said" { + const gpa = testing.allocator; + var repo = try Repo.init(gpa) orelse return error.SkipZigTest; + defer repo.deinit(gpa); + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 40 }); + defer p.deinit(); + var line: [4200]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); + const file = p.view().active; + try testing.expectEqualStrings(Repo.three, p.panes[file].?.file.?.content); + p.update(.{ .command = "At @-" }); + const shown = p.view().active; + try testing.expect(shown != file); + const pane = p.panes[shown].?; + try testing.expectEqualStrings(Repo.two, pane.file.?.content); + const name = try std.fmt.allocPrint(gpa, "{s}@@-", .{repo.file}); + defer gpa.free(name); + try testing.expectEqualStrings(name, try pardes.tagline.tagPrefix(p, pane)); + try testing.expectEqualStrings(repo.file, File.langPath(&pane.file.?)); + try testing.expect(pane.colorAlgo() == .source); + // Read-only: a key's edit and a whole-text edit (dd) change nothing, and a bare Save says so. + for ("iz") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + p.update(.{ .key = .{ .cp = pardes.Key.escape } }); + for ("dd") |c| p.update(.{ .key = .{ .cp = c, .text = &[_]u8{c} } }); + try testing.expectEqualStrings(Repo.two, pane.file.?.content); + p.update(.{ .command = "Save" }); + try testing.expect(std.mem.indexOf(u8, told(p, shown), "is a revision, read-only") != null); + // From the file's pane, a Look at the address with a line goes there. + p.view().active = file; + p.update(.{ .command = "Look a.zig@@-:3" }); + try testing.expectEqual(shown, p.view().active); + try testing.expectEqual(@as(i32, 2), pane.body.cur_row); + // Turned to another revision in its place: one pane, the older text. + p.update(.{ .command = "At @--" }); + const turned = p.view().active; + try testing.expect(p.panes[shown] == null); + try testing.expectEqualStrings(Repo.one, p.panes[turned].?.file.?.content); + var n: usize = 0; + for (p.panes) |slot| if (slot) |s| if (s.file) |*f| { + n += @intFromBool(of(f) != null); + }; + try testing.expectEqual(@as(usize, 1), n); + // jj's refusals, in its words. + p.update(.{ .command = "At nosuch" }); + try testing.expect(std.mem.indexOf(u8, told(p, turned), "At: Revision `nosuch` doesn't exist") != null); + p.view().active = file; + p.update(.{ .command = "At" }); + try testing.expect(std.mem.indexOf(u8, told(p, file), "At: which revision?") != null); + // Bare in a revision's pane: the file. + p.view().active = turned; + p.update(.{ .command = "At" }); + try testing.expectEqual(file, p.view().active); +} + +test "a client replays the open of a file at a revision and ends equal" { + const gpa = testing.allocator; + var repo = try Repo.init(gpa) orelse return error.SkipZigTest; + defer repo.deinit(gpa); + const R = pardes.replica; + const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{}, false); + defer a.deinit(); + const r = try R.Replica.init(gpa, 1, try a.unit(0, 0), false); + defer r.deinit(); + var line: [4200]u8 = undefined; + r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-:2", .{repo.file}) })); + r.settle(); + try testing.expect(r.diverged == null); + const id = a.core.view().active; + try testing.expectEqualStrings(Repo.two, a.core.panes[id].?.file.?.content); + try testing.expectEqualStrings(Repo.two, r.core().panes[id].?.file.?.content); + try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); +} diff --git a/core/look.zig b/core/look.zig index 1d296775..53c26943 100644 --- a/core/look.zig +++ b/core/look.zig @@ -1489,6 +1489,8 @@ pub fn lookAt(p: *Pardes, id: usize, operand_raw: []const u8) void { // What is looked for is the place without its trailing `:`, `@p33:` // and `a.txt:` as much as `a.txt:2:`. const found = resolveLookTarget(p, id, trimmed, &realbuf); + // `path@rev`, `path@rev:12`: no file, a file at a revision (jj.zig). + if (found == .none and @import("jj.zig").looked(p, id, Pardes.paneDir(pane), pl.path, pl.at)) return; // A line past the end of an open pane is a miss (the target's line is // already clamped, so the one written is asked). if (found == .pane and found.pane.id < MAX_PANES) if (p.panes[found.pane.id]) |shown| { diff --git a/core/panes.zig b/core/panes.zig index e8f35de8..2f488482 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -558,7 +558,7 @@ pub const Pane = struct { if (std.mem.endsWith(u8, f.path, ".diff") or std.mem.endsWith(u8, f.path, ".patch") or f.pager_diff) return .diff; if (f.output != null) { // A +Preview is a file's text: coloured as the file. - if (f.output.?.from == .preview) return .source; + if (f.output.?.from == .preview or f.output.?.from == .revision) return .source; const tr = Output.fileTraits(f.output); if (tr.locations) return .locations; if (!tr.saves) return .none; diff --git a/core/root.zig b/core/root.zig index 5300ce93..145122e3 100644 --- a/core/root.zig +++ b/core/root.zig @@ -628,6 +628,7 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{ .{ "exec.zig", 3, "kindOf's stat (tape.site(.kind), its io the tape's) and Shell's check (tape.site(.shell))" }, .{ "fs.zig", 38, "the file system behind the tape's sites (open, read, write, stat, mkdir, access; their io the tape's), the process's home (read once at the start, taped), the 9P transport" }, .{ "hunks.zig", 1, "a test helper's file read" }, + .{ "jj.zig", 8, "jj run under tape.site(.jj) on an io of its own (the tape's spawns nothing) with this process's environment, the signal mask cleared as Stream's children's: the session's, a replica replays its answer" }, .{ "look.zig", 6, "openLink's fork (the host's: a view's frontend opens a link) and a remote's error name" }, .{ "memory.zig", 7, "the memory regions themselves (mmap, madvise, their locks)" }, .{ "replica.zig", 73, "the client and session engines: sockets, threads, clocks, the blob cache, traces" }, diff --git a/core/tape.zig b/core/tape.zig index 09985d15..af934b38 100644 --- a/core/tape.zig +++ b/core/tape.zig @@ -112,6 +112,8 @@ pub const Site = enum(u16) { shell, /// The machine's fonts (Font , Fonts): its disk too. fonts, + /// What jj says of a file (jj.zig): a file at a revision. + jj, // Read in place (`value`). clock, wake, @@ -161,6 +163,7 @@ pub const results = .{ ?@import("Store.zig").Record, ?@import("recent.zig").Entry, []const @import("Store.zig").Named, @import("Kind.zig").Outcome, pardes.Term.Prompt, + @import("jj.zig").Shown, }; /// What a host reports to the core as failed (`shell_failed`, `save_failed`, diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index 16a1aac8..a00b8bdf 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -2,6 +2,7 @@ {"name": "Addon", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Addons, the libraries that bring kinds of pane: `Addon load `, `Addon unload `, `Addon reload `; bare, the kinds here."}, {"name": "Adopt", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Take in the shells of a session that died holding them, each as a terminal pane here: the pardes daemon kept their terminals open."}, {"name": "Ascii", "leader": "SPC t a", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "add the printable ASCII bitmaps to the matcher's glyph set"}, + {"name": "At", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Show a file as it was at revision `rev` (jj), read-only, beside its pane; in such a pane, that file at another revision in its place, or bare, the file."}, {"name": "Back", "leader": "SPC j o", "also": ["C-o"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Ctrl-o: one step back into the history."}, {"name": "Build", "leader": "SPC h b", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "This build: its version, commit, jj change and build time (a stamped build's: a release or the ~/.local install), the zig that built it, its optimize mode, target, platform, grammars, whether the addons are compiled in, and its dependencies, printed into an output buffer."}, {"name": "Callees", "leader": "SPC l C", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the functions the function under the cursor calls."}, diff --git a/docs/typ/builtins-tui.json b/docs/typ/builtins-tui.json index 39f762f2..1f0cd09d 100644 --- a/docs/typ/builtins-tui.json +++ b/docs/typ/builtins-tui.json @@ -2,6 +2,7 @@ {"name": "Addon", "leader": null, "also": [], "arg": true, "scope": "root", "setting": false, "choices": null, "doc": "Addons, the libraries that bring kinds of pane: `Addon load `, `Addon unload `, `Addon reload `; bare, the kinds here."}, {"name": "Adopt", "leader": null, "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Take in the shells of a session that died holding them, each as a terminal pane here: the pardes daemon kept their terminals open."}, {"name": "Ascii", "leader": "SPC t a", "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "add the printable ASCII bitmaps to the matcher's glyph set"}, + {"name": "At", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Show a file as it was at revision `rev` (jj), read-only, beside its pane; in such a pane, that file at another revision in its place, or bare, the file."}, {"name": "Back", "leader": "SPC j o", "also": ["C-o"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Ctrl-o: one step back into the history."}, {"name": "Build", "leader": "SPC h b", "also": [], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "This build: its version, commit, jj change and build time (a stamped build's: a release or the ~/.local install), the zig that built it, its optimize mode, target, platform, grammars, whether the addons are compiled in, and its dependencies, printed into an output buffer."}, {"name": "Callees", "leader": "SPC l C", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the functions the function under the cursor calls."}, diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index 127b22a9..7699ee52 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -283,6 +283,16 @@ or one above it. #word("Diff") on a `+Diff` shows the diff itself as text (a paged one's `+Pager` is closed once stacked), and on the text stacks it again. += A file at a revision + +`path@rev` names a file as jj has it at a revision: `a.zig@main`, +`a.zig@@-`, and `a.zig@main:120` at a line. A #word("Look") at one, +anywhere, opens it in a pane of that name, read-only and coloured as the +file. #word("At") with a revision does the same from a file's pane; in a +revision's pane it turns that pane to another revision, and bare it goes +back to the file. What jj refuses (a revision that is not there, a path +the revision has not) is said in jj's words. jj reads the working copy as +it last saw it (`@`): pardes never snapshots it. #word("Syntax") (#key("SPC t h")) turns a text's syntax colours off in this view, and on again. -- cgit v1.3