diff options
| -rw-r--r-- | abi/wire.zig | 8 | ||||
| -rw-r--r-- | core/Core.zig | 1 | ||||
| -rw-r--r-- | core/Effect.zig | 7 | ||||
| -rw-r--r-- | core/File.zig | 609 | ||||
| -rw-r--r-- | core/Places.zig | 2 | ||||
| -rw-r--r-- | core/Query.zig | 9 | ||||
| -rw-r--r-- | core/Stream.zig | 9 | ||||
| -rw-r--r-- | core/Tables.zig | 1 | ||||
| -rw-r--r-- | core/Text.zig | 12 | ||||
| -rw-r--r-- | core/body_layer.zig | 3 | ||||
| -rw-r--r-- | core/builtins.zig | 2 | ||||
| -rw-r--r-- | core/dump.zig | 20 | ||||
| -rw-r--r-- | core/edit.zig | 4 | ||||
| -rw-r--r-- | core/edit_cmd.zig | 17 | ||||
| -rw-r--r-- | core/jj.zig | 1065 | ||||
| -rw-r--r-- | core/look.zig | 23 | ||||
| -rw-r--r-- | core/lsp/Ask.zig | 33 | ||||
| -rw-r--r-- | core/mouse.zig | 5 | ||||
| -rw-r--r-- | core/ninep/ctl.zig | 24 | ||||
| -rw-r--r-- | core/ninep/events.zig | 4 | ||||
| -rw-r--r-- | core/ninep/pane.zig | 137 | ||||
| -rw-r--r-- | core/panes.zig | 18 | ||||
| -rw-r--r-- | core/root.zig | 1 | ||||
| -rw-r--r-- | dev/Lsp.zig | 14 | ||||
| -rw-r--r-- | dev/file_watch.zig | 6 | ||||
| -rw-r--r-- | test/daemon.py | 2 |
26 files changed, 1539 insertions, 497 deletions
diff --git a/abi/wire.zig b/abi/wire.zig index 7b6a22f1..ea5998e6 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -10,6 +10,12 @@ const pardes = @import("core"); const config = @import("pardes_options"); const build_info = @import("build_info"); +/// 34: the `Changes` layer's lines are the pane's buffer's while it is +/// shown: a file pane's `read_only` places and `layer` in the dump and the +/// digest, its buffer dumped whole while it has them (a clean file's text +/// is no longer left for the disk then), a description's ghost its +/// `author`'s place; a dump of 31 loads, a pane whose view showed the +/// layer showing it again (jj.loaded); /// 31: where a view stands in a terminal's history is the view's: a pane's /// `scrolled_to` (and its share's in each view) in the dump and the digest, /// the emulator's own view out of both (its `Parts.view` gone); the @@ -67,7 +73,7 @@ const build_info = @import("build_info"); /// part B); 14: the hello names a session and /// carries the semantics hash, and a ping is answered (phase 5's /// groundwork); 13: the frames went (phase 3). -pub const version: u16 = 31; +pub const version: u16 = 34; /// The terminal's build and the window's step alike (`semantics`). const family = switch (config.platform) { diff --git a/core/Core.zig b/core/Core.zig index f5ed28bd..4c8aa2eb 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -1919,7 +1919,6 @@ pub fn sync(p: *Pardes) void { // and its context declarations. if (pane.file) |*f| pardes.panes.File.refreshContext(p, pane, f); pane.view = .{ .wrap = p.settings.wrap, .body_h = v.row_metrics.body_h, .tagline_h = v.row_metrics.tagline_h, .rect_h = r.h }; - if (pane.layers.lanes > 0) @import("jj.zig").showGhosts(p, pane); // The tag takes a row per line, leaving the body one row if it // had any; a folded pane shows its first line only. Its prefix // is made once, on the stack: this runs on every event, and not diff --git a/core/Effect.zig b/core/Effect.zig index bdf41e66..bf02c5b7 100644 --- a/core/Effect.zig +++ b/core/Effect.zig @@ -163,7 +163,9 @@ fn performInner(p: *Pardes, e: Effect) void { // A save the host could not do (saveFailed) is its err // record alone, not a `save`, and changes nothing: a clean // file stays clean. - const saved_pane = writeChecked(p, sf.pane.index(), pane.serial, f.path, f.content, was) orelse return; + // The file's text: the layer's lines are none of it. + const text = panes.File.fileText(f, p.scratch.allocator()) catch |err| return p.reportError(sf.pane, "Save", err); + const saved_pane = writeChecked(p, sf.pane.index(), pane.serial, f.path, text, was) orelse return; const saved = if (saved_pane.file) |*file| file else return; // Edited while it was written: what is on disk is not this. if (saved.saved_revision != saved.revision) return; @@ -182,7 +184,8 @@ fn performInner(p: *Pardes, e: Effect) void { if (pane.serial != st.serial) return; // a recycled slot: not ours if (pane.file) |*f| { // Failed, it changes nothing: not the name, not dirty. - const after = writeChecked(p, st.pane.index(), st.serial, st.path.slice(), f.content, f.saved_revision) orelse return; + const text = panes.File.fileText(f, p.scratch.allocator()) catch |err| return p.reportError(st.pane, "Save", err); + const after = writeChecked(p, st.pane.index(), st.serial, st.path.slice(), text, f.saved_revision) orelse return; if (after.file == null) return; if (st.promote) promoteSaved(p, st.pane.index(), st.path.slice()) else ctlfs.events.noteLogAs(p, .save, after, st.path.slice()); return; diff --git a/core/File.zig b/core/File.zig index c4fc8a38..0c742eee 100644 --- a/core/File.zig +++ b/core/File.zig @@ -199,8 +199,194 @@ pub const State = struct { /// In its twin group's Follow chain (builtins.Follow), whose panes /// show the text as consecutive pages (followChain). follow: bool = false, + /// Its `Changes` layer's lines while it is shown (`ReadOnly`, jj.zig): + /// read-only lines of the buffer, in order, gpa-owned (a twin holds its + /// own copy); none while it is hidden. + read_only: []ReadOnly = &.{}, + /// Whose layer they are: the serial of the pane whose `Changes` answer + /// they are the ghosts of, in its order (jj.answered); 0, none shown. + layer: u32 = 0, }; +/// A read-only line of a pane's buffer: one of its `Changes` layer's (a +/// line a change took away, a changed line's old text, a change's +/// description: jj.zig `Ghost`), its bytes `content[at..][0..len]`, its +/// text and its `\n` (`lead`: after the last line of a text that ends +/// with none, its `\n` first). Regular text to everything that reads the +/// buffer (a motion, a selection, a search, a Look); the file's text is the +/// buffer less them (`fileText`); an edit touching one is refused whole +/// (`edit`). +pub const ReadOnly = struct { + at: usize, + len: usize, + /// The file's line it stands before, from 0 (the file's line count: + /// after its last). + line: u32, + lead: bool = false, +}; + +/// THE FILE'S TEXT: the buffer less its read-only lines, the one way to it. +/// Whatever reads "the file" (a Save, `body` over 9P, the dirty check, the +/// language server, the syntax parse, jj, a reread's comparison) asks this, +/// never `content`, which is the buffer the drawing and the editing read: +/// the buffer itself while it has none (a file with no layer pays nothing), +/// else a copy in `arena`. +pub fn fileText(f: *const State, arena: std.mem.Allocator) error{OutOfMemory}![]const u8 { + if (f.read_only.len == 0) return f.content; + const out = try arena.alloc(u8, fileLen(f)); + var parts: FileParts = .{ .f = f }; + var n: usize = 0; + while (parts.next()) |part| { + @memcpy(out[n..][0..part.len], part); + n += part.len; + } + return out; +} + +/// The file's text's length (`fileText`). +pub fn fileLen(f: *const State) usize { + var n = f.content.len; + for (f.read_only) |r| n -= r.len; + return n; +} + +/// The file's text a stretch at a time, the buffer between its read-only +/// lines (`fileText` without the copy). +pub const FileParts = struct { + f: *const State, + i: usize = 0, + at: usize = 0, + done: bool = false, + + pub fn next(it: *FileParts) ?[]const u8 { + if (it.done) return null; + const ro = it.f.read_only; + if (it.i == ro.len) { + it.done = true; + return it.f.content[it.at..]; + } + const part = it.f.content[it.at..ro[it.i].at]; + it.at = ro[it.i].at + ro[it.i].len; + it.i += 1; + return part; + } +}; + +/// Whether the file's text is `bytes` (`fileText` without the copy). +pub fn fileEql(f: *const State, bytes: []const u8) bool { + if (fileLen(f) != bytes.len) return false; + var parts: FileParts = .{ .f = f }; + var at: usize = 0; + while (parts.next()) |part| { + if (!std.mem.eql(u8, part, bytes[at..][0..part.len])) return false; + at += part.len; + } + return true; +} + +/// The file's text hashed (Wyhash, as `std.hash.Wyhash.hash(0, text)`): +/// what the dirty check compares, never a copy. +pub fn fileHash(f: *const State) u64 { + if (f.read_only.len == 0) return std.hash.Wyhash.hash(0, f.content); + var h = std.hash.Wyhash.init(0); + var parts: FileParts = .{ .f = f }; + while (parts.next()) |part| h.update(part); + return h.final(); +} + +/// A buffer offset as the file's: less the read-only lines before it; one +/// inside a read-only line, after the file line above it (where the line +/// it stands before starts). +pub fn fileOffset(f: *const State, at: usize) usize { + var less: usize = 0; + for (f.read_only) |r| { + if (r.lead) { + if (at <= r.at) break; + if (at <= r.at + r.len) return r.at - less; + } else { + if (at < r.at) break; + if (at < r.at + r.len) return r.at - less; + } + less += r.len; + } + return at - less; +} + +/// A file offset as the buffer's: a line's start after the read-only lines +/// standing before it (`:N`, a Look, a language server's place land on the +/// file's line, never on one of the layer's); `end`, a range's end, before +/// them (a range of the file's lines holds none of the layer's after it). +pub fn bufferOffset(f: *const State, at: usize, end: bool) usize { + var more: usize = 0; + for (f.read_only) |r| { + const place = r.at - more; + if (if (r.lead or end) place >= at else place > at) break; + more += r.len; + } + return at + more; +} + +/// A buffer row as the file's: a read-only line's, the file line it stands +/// before. +pub fn fileRow(f: *const State, row: usize) usize { + var less: usize = 0; + for (f.read_only, 0..) |r, k| { + const at = r.line + k; + if (at > row) break; + if (at == row) return r.line; + less += 1; + } + return row - less; +} + +/// A file row as the buffer's: after the read-only lines standing before it. +pub fn bufferRow(f: *const State, row: usize) usize { + var more: usize = 0; + for (f.read_only) |r| { + if (r.line > row) break; + more += 1; + } + return row + more; +} + +/// Which read-only line buffer row `row` is (its place in `read_only`), +/// null for a line of the file. +pub fn readOnlyRow(f: *const State, row: usize) ?usize { + for (f.read_only, 0..) |r, k| { + const at = r.line + k; + if (at == row) return k; + if (at > row) return null; + } + return null; +} + +/// Whether the edit putting `bytes` over the `len` bytes at `off` touches +/// a read-only line: changes a byte of one, puts any in at its start or +/// inside it, or leaves it on the end of a line above it (an edit ending +/// where one starts must leave a line's end before it: a line deleted +/// whole above one is the file's edit; a `J` into one is not). +fn touchesReadOnly(f: *const State, off: usize, len: usize, bytes: []const u8) bool { + for (f.read_only) |r| { + const lo = r.at; + const hi = r.at + r.len; + if (lo > off + len) break; + if (off < hi and off + len > lo) return true; + if (r.lead) { + if (len == 0 and off > lo and off <= hi) return true; + } else { + if (len == 0 and off >= lo and off < hi) return true; + if (len > 0 and off + len == lo) { + const ends_line = if (bytes.len > 0) bytes[bytes.len - 1] == '\n' else off == 0 or f.content[off - 1] == '\n'; + if (!ends_line) return true; + } + } + } + return false; +} + +/// What an edit refused for a read-only line says (`edit`). +pub const read_only_said = "a change's line is read-only: nothing edited (Changes hides them)"; + pub const NodeStep = @import("Editor.zig").NodeStep; pub fn graphemeDisplayWidth(tab: u16, grapheme: []const u8) usize { @@ -370,7 +556,8 @@ pub fn gutterWidth(pane: *const Pane) u16 { if (file.output) |o| if (std.meta.eql(o.from, Output.Origin{ .cmd = .Diff })) return 0; // A query pane's rows carry their own line numbers (Query.zig). if (pane.query != null) return 0; - var lines = if (file.line_starts.len > 0) file.line_starts.len else lineCount(file.content); + // The file's lines: the layer's have no number. + var lines = (if (file.line_starts.len > 0) file.line_starts.len else lineCount(file.content)) - file.read_only.len; var digits: u16 = 1; while (lines >= 10) : (lines /= 10) digits += 1; return @max(config.PREFIX_W, digits + 1) + laneCells(pane) + pane.layers.heat; @@ -626,6 +813,7 @@ pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { if (file.line_starts.len > 0 and !index_shared) pardes.memory.freeRaw(p.gpa, indexRoom(file)); if (file.highlights.len > 0) p.tree_sitter_gpa.free(file.highlights); p.gpa.free(file.pager_spans); + p.gpa.free(file.read_only); locations.freeRows(p.gpa, file.location_rows); file.context.deinit(); if (file.node_tree) |tree| syntax.freeTree(tree); @@ -636,14 +824,16 @@ pub fn deinit(p: *Pardes, pane: *Pane, file: *State) void { file.history.destroy(p.gpa); } -/// The edit `replace` makes told to the event readers, before it is made. +/// The edit `replace` makes told to the event readers, before it is made: +/// in the file's text, by its offsets. fn reportEdit(p: *Pardes, f: *State, off: usize, len: usize, bytes: []const u8) void { if (p.fs.listeners == 0) return; const id = for (p.panes, 0..) |slot, i| { const pane = slot orelse continue; if (pane.file) |*state| if (state == f) break i; } else return; - pardes.ctlfs.events.noteEdit(p, id, false, f.content, off, len, bytes); + const text = fileText(f, p.scratch.allocator()) catch return; + pardes.ctlfs.events.noteEdit(p, id, false, text, fileOffset(f, off), len, bytes); } pub fn setContent(p: *Pardes, f: *State, new: []u8) void { @@ -678,16 +868,178 @@ pub fn setRows(p: *Pardes, f: *State, rows: []locations.Row) error{RowsMismatch} /// lies between them, made by `edit`, which takes `new`, a whole text its /// caller made anyway, as the text's buffer. pub fn setContentSpan(p: *Pardes, f: *State, new: []u8, span_in: ?Span) void { - const span = span_in orelse spanOf(f.content, new); - _ = edit(p, f, span.head, f.content.len - span.head - span.tail, new[span.head .. new.len - span.tail], new, true, null); + var span = span_in orelse spanOf(f.content, new); + if (f.read_only.len > 0) span = clearOfReadOnly(f, new, span); + if (edit(p, f, span.head, f.content.len - span.head - span.tail, new[span.head .. new.len - span.tail], new, true, null, .edit)) return; + // Refused (read-only text, said) or no memory: `new` kept until the + // next such, as the editor keeps a text it made (edit.zig + // retireEditText): its caller may still read it. + if (p.retired_edit) |old| p.gpa.free(old); + p.retired_edit = new; +} + +/// Of the splices that make `new` of the buffer, one that touches no +/// read-only line when the shortest (`span`, what it keeps at either end) +/// does: the editor's whole new text says what it changed only by the +/// bytes, and the shortest splice can run into a line of the layer's where +/// the edit did not (`a();` deleted above ` b();`, both starting with +/// four blanks, is the splice `a();\n `; it is also ` a();\n`). +/// Searched back from the shortest's head, a page of bytes at most. +fn clearOfReadOnly(f: *const State, new: []const u8, span: Span) Span { + const old = f.content; + if (!touchesReadOnly(f, span.head, old.len - span.head - span.tail, new[span.head .. new.len - span.tail])) return span; + const n = @min(old.len, new.len); + // The whole tail they share (`spanOf`'s stops at its head). + var shared: usize = 0; + while (shared < n and old[old.len - 1 - shared] == new[new.len - 1 - shared]) shared += 1; + // Never back across a read-only line: an edit made on one (a paste + // below it) is no edit of the line above it. + var floor: usize = 0; + for (f.read_only) |r| { + if (r.at + r.len > span.head) break; + floor = r.at + r.len; + } + var head = span.head; + while (head > floor and span.head - head < 4096) { + head -= 1; + const tail = @min(shared, n - head); + if (!touchesReadOnly(f, head, old.len - head - tail, new[head .. new.len - tail])) return .{ .head = head, .tail = tail }; + } + return span; } /// The one change a text takes: the `len` bytes at `off` replaced by /// `bytes`, in its own buffer, so an edit costs its bytes and what follows -/// them, never a copy of the text. False with no memory for it, and -/// nothing changed. +/// them, never a copy of the text. False with no memory for it, or for an +/// edit of read-only text (said), and nothing changed. pub fn replace(p: *Pardes, f: *State, off: usize, len: usize, bytes: []const u8) bool { - return edit(p, f, off, len, bytes, null, true, null); + return edit(p, f, off, len, bytes, null, true, null, .edit); +} + +/// What an edit is (`edit`): the editor's, of the buffer (refused where +/// it touches read-only text); a program's new text for the file (`load`: +/// never refused); the layer's lines going in or out (`jj.showLayer`: +/// nothing that reads the file hears of it). +pub const How = enum { edit, load, layer }; + +/// A new text for the FILE, `new` (owned), from what is not an edit of +/// the buffer: a Get, a reread from the disk, a language server's edits: +/// never refused for the layer's lines, which leave the buffer around it +/// and come back where the file's lines they stood before went (jj.edited +/// carries them). +pub fn load(p: *Pardes, f: *State, new: []u8) void { + const layer = f.layer; + if (layer != 0) jj.hideLayer(p, f); + defer if (layer != 0) jj.showLayer(p, f, layer); + const span = spanOf(f.content, new); + if (!edit(p, f, span.head, f.content.len - span.head - span.tail, new[span.head .. new.len - span.tail], new, true, null, .load)) pardes.memory.freeRaw(p.gpa, new); +} + +/// `replace` of the file's `len` bytes at `off` (its own offsets, `body` +/// over 9P's), as `load` is a new text: the layer's lines out and back. +pub fn replaceFile(p: *Pardes, f: *State, off: usize, len: usize, bytes: []const u8) bool { + const layer = f.layer; + if (layer != 0) jj.hideLayer(p, f); + defer if (layer != 0) jj.showLayer(p, f, layer); + return replace(p, f, off, len, bytes); +} + +/// `f`'s buffer made `new` (owned) with the read-only lines `spans` (owned) +/// of pane `layer`'s layer, or none (`layer` 0): the layer's lines in or +/// out (jj.showLayer, jj.hideLayer). No edit of the file: nothing that +/// reads it hears of it (no undo step, no event, the text as clean as it +/// was, its declarations its own), and every view of every pane on the +/// buffer keeps its place in the file (`fileOffset`), so one in a line that +/// leaves goes to the start of the file line it stood before, and one at a +/// line's start stays on that line. False with no memory, nothing changed. +pub fn relayer(p: *Pardes, f: *State, new: []u8, spans: []ReadOnly, layer: u32) bool { + const arena = p.scratch.allocator(); + // Each twin its own copy of the read-only lines, made first: a twin + // without them would read the layer's lines as the file's. + var twins: [pardes.MAX_PANES]usize = undefined; + const ntwins = twinsOf(p, f, &twins); + var copies: [pardes.MAX_PANES][]ReadOnly = undefined; + for (0..ntwins) |i| copies[i] = p.gpa.dupe(ReadOnly, spans) catch { + for (copies[0..i]) |c| p.gpa.free(c); + return false; + }; + // Every place on the buffer, as the file's offsets: a cursor, a + // selection's anchor and ranges in the live view, a cursor and a top + // line in the others. + const Place = struct { row: *i32, col: *i32, at: usize }; + const Top = struct { line: *usize, at: usize }; + var places: std.ArrayList(Place) = .empty; + var tops: std.ArrayList(Top) = .empty; + const At = struct { + fn of(q: *Pardes, g: *State, row: i32, col: i32) usize { + const r: usize = @intCast(@max(0, row)); + const start = lineStart(q.gpa, g, r); + const end = if (r + 1 < nlines(q.gpa, g)) lineStart(q.gpa, g, r + 1) - 1 else g.content.len; + return fileOffset(g, @min(@max(start, end), start + @as(usize, @intCast(@max(0, col))))); + } + }; + for (p.panes) |slot| { + const pane = slot orelse continue; + const tf = if (pane.file) |*file| file else continue; + if (tf != f and (f.twin == 0 or tf.twin != f.twin)) continue; + const b = &pane.body; + places.append(arena, .{ .row = &b.cur_row, .col = &b.cur_col, .at = At.of(p, f, b.cur_row, b.cur_col) }) catch return false; + if (b.vsel.active) places.append(arena, .{ .row = &b.vsel.row, .col = &b.vsel.col, .at = At.of(p, f, b.vsel.row, b.vsel.col) }) catch return false; + for (b.sels[0..b.nsel]) |*sr| { + places.append(arena, .{ .row = &sr.row, .col = &sr.col, .at = At.of(p, f, sr.row, sr.col) }) catch return false; + places.append(arena, .{ .row = &sr.arow, .col = &sr.acol, .at = At.of(p, f, sr.arow, sr.acol) }) catch return false; + } + tops.append(arena, .{ .line = &tf.scroll, .at = fileOffset(f, lineStart(p.gpa, f, tf.scroll)) }) catch return false; + for (0..pardes.views.max) |k| { + if (k == p.live or !pardes.views.isOpen(p, @intCast(k))) continue; + const v = &pane.pv[k]; + places.append(arena, .{ .row = &v.body.cur_row, .col = &v.body.cur_col, .at = At.of(p, f, v.body.cur_row, v.body.cur_col) }) catch return false; + tops.append(arena, .{ .line = &v.scroll, .at = fileOffset(f, lineStart(p.gpa, f, v.scroll)) }) catch return false; + } + } + const span = spanOf(f.content, new); + if (!edit(p, f, span.head, f.content.len - span.head - span.tail, new[span.head .. new.len - span.tail], new, false, null, .layer)) { + for (copies[0..ntwins]) |c| p.gpa.free(c); + return false; + } + p.gpa.free(f.read_only); + f.read_only = spans; + f.layer = layer; + for (twins[0..ntwins], copies[0..ntwins]) |id, c| { + const tf = &p.panes[id].?.file.?; + p.gpa.free(tf.read_only); + tf.read_only = c; + tf.layer = layer; + } + for (places.items) |place| { + const pos = positionIn(p.gpa, f, bufferOffset(f, place.at, false)); + place.row.* = @intCast(pos.row); + place.col.* = @intCast(pos.col); + } + for (tops.items) |top| top.line.* = positionIn(p.gpa, f, bufferOffset(f, top.at, false)).row; + return true; +} + +/// Whether an edit of the `len` bytes at `off` is of read-only text: a +/// file at a revision (jj.zig) is that whole, to the editor and to a load; +/// the `Changes` layer's lines are each one, to the editor +/// (`touchesReadOnly`: a load takes them out first). The one check, +/// `edit`'s. +fn readOnly(f: *const State, off: usize, len: usize, bytes: []const u8, how: How) bool { + if (how == .layer) return false; + if (f.output) |o| if (o.from == .revision) return true; + return how == .edit and f.read_only.len > 0 and touchesReadOnly(f, off, len, bytes); +} + +/// Said on each pane of `f` (`readOnly`). +fn refuse(p: *Pardes, f: *const State) void { + for (p.panes, 0..) |slot, id| { + const pane = slot orelse continue; + if (pane.file) |*state| if (state == f) { + pane.body.refused = true; + p.setMessage(.at(id), if (f.read_only.len > 0) read_only_said else "a file at a revision is read-only"); + }; + } } /// A replacement that takes out at least this much, and most of the text, @@ -703,10 +1055,21 @@ const swap_min = 64 << 10; /// and it is a new revision. An edit that takes out most of the text puts /// 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; +fn edit(p: *Pardes, f: *State, off: usize, len: usize, bytes_in: []const u8, whole: ?[]u8, journaled: bool, kept: ?*[]u8, how: How) bool { + // Read-only text (a file at a revision, the layer's lines) takes no + // edit of the editor's: refused whole, in words. + if (readOnly(f, off, len, bytes_in, how)) { + refuse(p, f); + return false; + } + // What reads the file hears of the edit in the file's own offsets (the + // buffer less its read-only lines: `fileOffset`); the layer's own lines + // going in or out it never hears of. The undo's (`turn`) and a load's + // edits come with the layer out (undoStep, `load`). + const told = how != .layer; + const file_off = fileOffset(f, off); + const lines_taken = if (f.read_only.len > 0) std.mem.count(u8, f.content[off..][0..len], "\n") else 0; + const was_clean = f.revision == f.saved_revision; 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 }; @@ -717,7 +1080,9 @@ fn edit(p: *Pardes, f: *State, off: usize, len: usize, bytes_in: []const u8, who // text moves under them. const own = whole == null and @intFromPtr(bytes_in.ptr) < @intFromPtr(room.ptr) + room.len and @intFromPtr(bytes_in.ptr) + bytes_in.len > @intFromPtr(room.ptr); const bytes = if (own) p.scratch.allocator().dupe(u8, bytes_in) catch return false else bytes_in; - const swapping = journaled and len >= swap_min and len * 2 >= old_len; + // The journal keeps the file's text: never a buffer holding the + // layer's lines. + const swapping = journaled and len >= swap_min and len * 2 >= old_len and f.read_only.len == 0; // A text a join is still sending stays as it is (memory.zig `pin`). const keep = whole == null and (swapping or pardes.memory.isPinned(f.content)); const fresh: ?[]u8 = whole orelse if (keep) copySpliced(p.gpa, f.content, off, len, bytes) catch return false else null; @@ -756,18 +1121,19 @@ fn edit(p: *Pardes, f: *State, off: usize, len: usize, bytes_in: []const u8, who } }; }; - reportEdit(p, f, off, len, bytes); - // A pinned change's per-line values ride with the lines (jj.zig). - if (p.changes.answers.items.len | p.changes.heats.items.len > 0) jj.edited(p, f, off, len, bytes); + if (told) reportEdit(p, f, off, len, bytes); + // A pinned change's per-line values ride with the lines (jj.zig), in + // the file's lines. + if (told and p.changes.answers.items.len | p.changes.heats.items.len > 0) jj.edited(p, f, off, len, bytes); if (f.mini) |*mini| mini.deinit(p.gpa); f.mini = null; if (f.line_starts.len > 0) shiftIndex(p.gpa, f, off, len, bytes); - if (journaled and !swapping) f.history.journal.record(p.gpa, f.content, off, len, bytes.len); + if (told and journaled and !swapping) f.history.journal.record(p.gpa, f.content[off..][0..len], file_off, bytes.len); // ponytail: a whole-text hash per edit that keeps the saved length; a // rolling hash when that too matters. - if (f.revision == f.saved_revision or f.saved_hash == null) { - f.saved_hash = std.hash.Wyhash.hash(0, f.content); - f.saved_len = f.content.len; + if (told and (f.revision == f.saved_revision or f.saved_hash == null)) { + f.saved_hash = fileHash(f); + f.saved_len = fileLen(f); } // The kept tree follows the edit (normal.fileTree parses with it), but // not while a rollback copy holds it: an edit in place would change the @@ -799,13 +1165,28 @@ fn edit(p: *Pardes, f: *State, off: usize, len: usize, bytes_in: []const u8, who f.content = buffer[0..new_len]; f.cap = buffer.len; } + // The read-only lines after the edit move with what it put in and took + // out, and the layer's ghosts with them (none is in it: refused). + if (told and f.read_only.len > 0) { + const lines_put = std.mem.count(u8, bytes, "\n"); + for (f.read_only) |*r| if (r.at >= off + len) { + r.at = r.at - len + bytes.len; + r.line = @intCast(r.line + lines_put - lines_taken); + }; + jj.placed(p, f); + } f.revision +%= 1; f.splice = .{ .revision = f.revision, .head = span.head, .tail = span.tail, .old_len = old_len }; - if (f.saved_hash) |h| if ((f.saved_len orelse new_len) == new_len and std.hash.Wyhash.hash(0, f.content) == h) { + if (!told) { + // The file's text is as it was: as clean as it was, its + // declarations still its own. + if (was_clean) f.saved_revision = f.revision; + if (f.context.revision == f.revision -% 1) f.context.revision = f.revision; + } else if (f.saved_hash) |h| if ((f.saved_len orelse fileLen(f)) == fileLen(f) and fileHash(f) == h) { f.saved_revision = f.revision; }; // The clock the session that recorded read (core/tape.zig). - f.mtime = p.tape.value(.mtime, pardes.ctlfs.events.now, .{}); + if (told) f.mtime = p.tape.value(.mtime, pardes.ctlfs.events.now, .{}); if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); f.highlights = &.{}; f.highlight_start = 0; @@ -824,6 +1205,10 @@ fn edit(p: *Pardes, f: *State, off: usize, len: usize, bytes_in: []const u8, who tf.cap = f.cap; tf.line_starts = f.line_starts; tf.line_cap = f.line_cap; + if (!told and tf.context.revision == f.revision -% 1) tf.context.revision = f.revision; + // Its copy of the read-only lines, moved as this one's were (the + // layer's own edit sets them after, jj.showLayer). + if (told and tf.read_only.len == f.read_only.len) @memcpy(tf.read_only, f.read_only); tf.revision = f.revision; tf.saved_revision = f.saved_revision; tf.saved_hash = f.saved_hash; @@ -994,8 +1379,15 @@ pub fn zerox(p: *Pardes, from: usize, to: usize) !*Pane { f.twin = p.next_twin; p.next_twin +%= 1; } + // The layer's lines are the buffer's: a twin shows them too, a copy of + // their places its own. + const read_only = try p.gpa.dupe(ReadOnly, f.read_only); + errdefer p.gpa.free(read_only); const pane = try p.newDocPane(to); + pane.layers.lanes = src.layers.lanes; pane.file = .{ + .read_only = read_only, + .layer = f.layer, .path = path, .content = f.content, .cap = f.cap, @@ -1235,7 +1627,6 @@ fn pageEnd(tab: u16, pane: *Pane) usize { if (pane.wrap_n == 0) return f.scroll + pane.rows; const last = (if (pane.body_visible_rows > 0) @min(pane.wrap_n, pane.body_visible_rows) else pane.wrap_n) - 1; const line: usize = @intCast(pane.wrap_line[last]); - if (pane.wrap_col[last] < 0) return @max(line, f.scroll + 1); if (!pane.body_wrapped or line >= nlines(pane.gpa, f)) return line + 1; const text = sourceLine(pane, @intCast(line)); const width = wrapWidth(pane, pane.view.wrap) -| pane.wrap_pad[last]; @@ -1283,10 +1674,14 @@ pub fn looksLikeDiff(head: []const u8) bool { /// Where the pane is in its text and what the text is saved as now: an /// undo step's edge (Text.Place), kept once, never a copy of the text. fn placeOf(pane: *const Pane, f: *const State) Text.Place { + // In the file's rows: an undo step is the file's (undoStep takes it + // with the layer's lines out). + var vsel = pane.body.vsel; + vsel.row = @intCast(fileRow(f, @intCast(@max(0, vsel.row)))); return .{ - .cur_row = pane.body.cur_row, - .cur_col = pane.body.cur_col, - .vsel = pane.body.vsel, + .cur_row = @intCast(fileRow(f, @intCast(@max(0, pane.body.cur_row)))), + .cur_col = if (readOnlyRow(f, @intCast(@max(0, pane.body.cur_row))) != null) 0 else pane.body.cur_col, + .vsel = vsel, .gen = f.history.gen, .clean = f.revision == f.saved_revision, .saved_hash = f.saved_hash, @@ -1342,17 +1737,22 @@ pub fn restoreSnap(tab: u16, pane: *Pane, f: *State, snap: Text.Place) void { /// after it are one step back to the pane's place now. pub fn pushUndo(p: *Pardes, pane: *Pane) error{OutOfMemory}!void { const f = if (pane.file) |*file| file else return; - try f.history.journal.mark(p.gpa, f.content, placeOf(pane, f)); + try f.history.journal.mark(p.gpa, try fileText(f, p.scratch.allocator()), placeOf(pane, f)); } /// Undo (back) or redo one step: its edits turned round in the text, and the -/// place and name it began at (or, redone, was undone from) back. +/// place and name it began at (or, redone, was undone from) back. The +/// journal is the file's: with the layer's lines shown, the step is taken +/// with them out, and they come back after it where its lines went. pub fn undoStep(p: *Pardes, pane: *Pane, back: bool) error{OutOfMemory}!void { const f = if (pane.file) |*file| file else return; const j = &f.history.journal; if (if (back) j.done == 0 else j.done == j.steps.items.len) return; const at = if (back) j.done - 1 else j.done; const now = placeOf(pane, f); + const layer = f.layer; + if (layer != 0) jj.hideLayer(p, f); + defer if (layer != 0) jj.showLayer(p, f, layer); if (!turn(p, f, at, back)) return error.OutOfMemory; const s = &j.steps.items[at]; if (back) { @@ -1381,14 +1781,14 @@ fn turn(p: *Pardes, f: *State, at: usize, back: bool) bool { const j = &f.history.journal; const step = j.steps.items[at]; const entries = j.entries.items[step.first..][0..step.n]; - if (entries.len == 0) return edit(p, f, f.content.len, 0, "", null, false, null); + if (entries.len == 0) return edit(p, f, f.content.len, 0, "", null, false, null, .load); if (entries[0].swap and (back or entries.len == 1)) { const e = &entries[0]; const now_len = f.content.len; const back_len = e.removed.len; const span = spanOf(f.content, e.removed); var out: []u8 = undefined; - if (!edit(p, f, span.head, now_len - span.head - span.tail, e.removed[span.head .. back_len - span.tail], e.removed.ptr[0..@max(e.room, back_len)], false, &out)) return false; + if (!edit(p, f, span.head, now_len - span.head - span.tail, e.removed[span.head .. back_len - span.tail], e.removed.ptr[0..@max(e.room, back_len)], false, &out, .load)) return false; j.fold(p.gpa, at); e.* = .{ .off = 0, .removed = out[0..now_len], .ins = back_len, .swap = true, .room = out.len }; return true; @@ -1396,7 +1796,7 @@ fn turn(p: *Pardes, f: *State, at: usize, back: bool) bool { if (entries.len == 1) { const e = &entries[0]; const put = pardes.memory.dupeUnfilled(p.gpa, f.content[e.off..][0..e.ins]) catch return false; - if (!edit(p, f, e.off, e.ins, e.removed, null, false, null)) { + if (!edit(p, f, e.off, e.ins, e.removed, null, false, null, .load)) { pardes.memory.freeRaw(p.gpa, put); return false; } @@ -1426,7 +1826,7 @@ fn turn(p: *Pardes, f: *State, at: usize, back: bool) bool { } const new = gap.whole(); const span = spanOf(f.content, new); - if (!edit(p, f, span.head, f.content.len - span.head - span.tail, new[span.head .. new.len - span.tail], gap.buf, false, null)) { + if (!edit(p, f, span.head, f.content.len - span.head - span.tail, new[span.head .. new.len - span.tail], gap.buf, false, null, .load)) { for (puts) |put| pardes.memory.freeRaw(p.gpa, put); pardes.memory.freeRaw(p.gpa, gap.buf); return false; @@ -1514,8 +1914,8 @@ pub fn changed(p: *Pardes, id: u8, bytes: []const u8) void { const pane = p.panes[id] orelse return; const f = if (pane.file) |*file| file else return; f.disk_gone = false; - if (std.mem.eql(u8, f.content, bytes)) return; - if (f.saved_hash) |saved| if (f.revision != f.saved_revision and std.hash.Wyhash.hash(0, f.content) != saved) { + if (fileEql(f, bytes)) return; + if (f.saved_hash) |saved| if (f.revision != f.saved_revision and fileHash(f) != saved) { const disk = std.hash.Wyhash.hash(0, bytes); // The disk holds what the text was read or saved as: no news, only // a watch looking again (an undo back to this name, a restart). @@ -1535,7 +1935,7 @@ pub fn changed(p: *Pardes, id: u8, bytes: []const u8) void { pardes.ctlfs.events.notePath(p, "changed", std.fmt.bufPrint(&rec, "{d} reloaded", .{pane.serial}) catch unreachable); // a u32 fits 32 pushUndo(p, pane) catch |err| return p.reportError(.at(id), "reload", err); const new = p.gpa.dupe(u8, bytes) catch |err| return p.reportError(.at(id), "reload", err); - setContent(p, f, new); + load(p, f, new); f.saved_revision = f.revision; restoreSnap(p.settings.tab, pane, f, .{ .cur_row = pane.body.cur_row, .cur_col = pane.body.cur_col, .vsel = pane.body.vsel }); } @@ -1547,7 +1947,8 @@ pub fn changed(p: *Pardes, id: u8, bytes: []const u8) void { /// render, since the view's geometry is made of them (`geometry`). pub fn refreshContext(p: *Pardes, pane: *Pane, f: *State) void { if (!f.tree_context or !supportsContext(pane) or f.context.revision == f.revision) return; - const declarations = syntax.contextDeclarations(p.tree_sitter_gpa, f.path, f.content) catch return; + // The file's declarations, in its lines (the layer's are none of it). + const declarations = syntax.contextDeclarations(p.tree_sitter_gpa, f.path, fileText(f, p.scratch.allocator()) catch return) catch return; f.context.replace(p.tree_sitter_gpa, declarations, f.revision); } @@ -1588,6 +1989,10 @@ pub fn refreshHighlights(p: *Pardes) void { if (!f.tree_context and pane.colorAlgo() == .source) paintAhead(p, pane, f); continue; } + if (f.read_only.len > 0) { + highlightLayered(p, pane, f); + continue; + } // A view far from what is painted (a jump: ge, a Look) paints only // itself on the frame, a third of the work; the stretch around it // comes painted ahead (paintAhead) where there are workers. @@ -1640,6 +2045,8 @@ pub fn refreshHighlights(p: *Pardes) void { /// rows, and a half page up (or down) missed it by a line and painted on /// the frame, 11-17 ms in ReleaseSafe. fn paintAhead(p: *Pardes, pane: *Pane, f: *State) void { + // A worker paints the buffer: with the layer's lines in it, never. + if (f.read_only.len > 0) return; const seen = &p.stream.ahead_seen; // A view standing still (typing in it) needs nothing ahead: each edit // is a new revision, and a paint asked at every keystroke was a copy @@ -1657,6 +2064,41 @@ fn paintAhead(p: *Pardes, pane: *Pane, f: *State) void { Stream.paintAhead(p, pane.serial, f.revision, langPath(f), f.content, start, end); } +/// The layer's lines shown (`read_only`): the file's text parsed for its +/// colours, never they (a line a change took away is no line of the +/// file's syntax: an unmatched brace in one would colour what follows), +/// the colours laid out in the buffer around them and none on them +/// (jj.paint inks them): the view's stretch and a view either side of it, +/// on the loop (a worker paints the buffer, paintAhead). +fn highlightLayered(p: *Pardes, pane: *Pane, f: *State) void { + f.syntax_dirty = false; + const rows: usize = pane.rows; + const start = if (f.tree_context) 0 else lineStart(p.gpa, f, f.scroll -| rows); + const end = if (f.tree_context) f.content.len else @max(start, lineStart(p.gpa, f, f.scroll + 2 * rows + SYNTAX_CONTEXT_AFTER_ROWS)); + const text = fileText(f, p.scratch.allocator()) catch return; + const file_start = fileOffset(f, start); + const got = syntax.highlightFileRange(p.tree_sitter_gpa, langPath(f), text, file_start, fileOffset(f, end)) catch return; + defer p.tree_sitter_gpa.free(got); + const out = p.tree_sitter_gpa.alloc(u8, end - start) catch return; + @memset(out, 0); + // The file's bytes between the read-only lines, a stretch at a time. + var from: usize = 0; + var at = start; + for (f.read_only) |r| { + if (r.at + r.len <= start) continue; + if (r.at >= end) break; + const n = @min(r.at -| at, got.len -| from); + @memcpy(out[at - start ..][0..n], got[from..][0..n]); + from += n; + at = @max(at, @min(end, r.at + r.len)); + } + const n = @min(end - at, got.len -| from); + @memcpy(out[at - start ..][0..n], got[from..][0..n]); + if (f.highlights.len > 0) p.tree_sitter_gpa.free(f.highlights); + f.highlights = out; + f.highlight_start = start; +} + /// 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 { @@ -1672,12 +2114,15 @@ fn prepareContextRows(pane: *Pane, file: *State) void { pane.context_rows = 0; if (!file.tree_context or !supportsContext(pane) or pane.rows > pane.wrap_line.len) return; const capacity = @min(pane.rows -| 1, pane.context_row_limit orelse std.math.maxInt(u16)); // retain an ordinary body row + // The declarations are the file's lines; the rows, the buffer's. + const top = fileRow(file, file.scroll); for (file.context.declarations) |declaration| { - if (declaration.start_line >= file.scroll) break; - if (declaration.end_line < file.scroll) continue; - var row = declaration.start_line; - while (row <= declaration.header_end_line and row < file.scroll) : (row += 1) { + if (declaration.start_line >= top) break; + if (declaration.end_line < top) continue; + var line = declaration.start_line; + while (line <= declaration.header_end_line and line < top) : (line += 1) { if (pane.context_rows >= capacity) return; + const row = bufferRow(file, line); if (pane.context_rows > 0 and row <= pane.wrap_line[pane.context_rows - 1]) continue; pane.wrap_line[pane.context_rows] = @intCast(row); pane.context_rows += 1; @@ -1687,12 +2132,6 @@ fn prepareContextRows(pane: *Pane, file: *State) void { pub fn wrapWidth(pane: *const Pane, wrap: bool) usize { if (!wrap or pane.rows > pane.wrap_line.len) return 0; - return bodyWidth(pane); -} - -/// The cells a body row has for text after the gutter (and a cell for a -/// wrapped line's marker). -pub fn bodyWidth(pane: *const Pane) usize { return @max(1, @as(usize, pane.cols -| gutterWidth(pane)) -| 1); } @@ -1714,7 +2153,7 @@ pub fn bodyText(tab: u16, arena: std.mem.Allocator, pane: *Pane, f: *State) ![]c geometry(tab, pane); const out = try arena.alloc(u8, pane.geometry_len); const width = wrapWidth(pane, pane.view.wrap); - const filled = if (hasGhosts(pane)) fillBody(true, tab, out, pane, f, width, false) else fillBody(false, tab, out, pane, f, width, false); + const filled = fillBody(tab, out, pane, f, width, false); std.debug.assert(filled == out.len); return out; } @@ -1758,13 +2197,7 @@ fn mapRows(tab: u16, pane: *Pane, f: *State) usize { pane.body_wrapped = width > 0; f.tables.ensure(tab, pane.gpa, f); prepareContextRows(pane, f); - return if (hasGhosts(pane)) fillBody(true, tab, null, pane, f, width, true) else fillBody(false, tab, null, pane, f, width, true); -} - -/// Whether this view of the pane shows ghost rows (jj.zig): its pinned -/// changes shown, and some. -fn hasGhosts(pane: *const Pane) bool { - return pane.layers.lanes > 0 and pane.ghosts.len > 0; + return fillBody(tab, null, pane, f, width, true); } /// Everything the geometry is made of, hashed: the text (its revision and @@ -1791,10 +2224,9 @@ fn geometryKey(pane: *const Pane, f: *const State) u64 { /// Run the file-body row walk. With no destination it is the exact sizing /// pass; with one it fills that allocation and records the wrapping map. -/// `ghosted`: the view shows ghost rows (`Pane.ghosts`), each a row of its -/// own before the line it stands at, no number, its text cut to the row; a -/// body with none walks without them. -fn fillBody(comptime ghosted: bool, tab: u16, dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) usize { +/// A read-only line (the `Changes` layer's) is a line as any, wrapped as +/// any; the numbers are the file's, and it has none. +fn fillBody(tab: u16, dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) usize { if (record_wrap) pane.wrap_n = 0; const prefix_width = gutterWidth(pane); // Where a number ends: a blank, then the heat lane and the lanes after it. @@ -1806,42 +2238,12 @@ fn fillBody(comptime ghosted: bool, tab: u16, dst: ?[]u8, pane: *Pane, f: *State var body_line: usize = f.scroll; var body_at: usize = 0; var written: usize = 0; - // The first ghost row at or below the top line. - var ghost: usize = 0; - if (ghosted) while (ghost < pane.ghosts.len and pane.ghosts[ghost].at < f.scroll) { - ghost += 1; - }; for (0..if (pane.body_rows > 0) pane.body_rows else pane.rows) |i| { if (i > 0) { if (dst) |out| out[written] = '\n'; written += 1; } const context = i < pane.context_rows; - if (ghosted and !context and body_at == 0 and ghost < pane.ghosts.len and pane.ghosts[ghost].at == body_line) { - const g = pane.ghosts[ghost]; - const said = pane.ghost_text[g.text..][0..g.len]; - var fit: [jj.row_max]u8 = undefined; - // A description is one compact row whatever the scroll. - const shown = if (g.kind == .description) - jj.fitted(tab, said, bodyWidth(pane), &fit) - else if (width > 0) - said[0..fitEnd(tab, said, 0, width)] - else - said[modal.graphemeStart(said, @min(@as(usize, @intCast(@max(0, pane.hscroll))), said.len))..]; - if (record_wrap) { - pane.wrap_line[i] = @intCast(body_line); - pane.wrap_col[i] = -1 - @as(i32, @intCast(ghost)); - pane.wrap_pad[i] = 0; - pane.wrap_n = @intCast(i + 1); - } - if (dst) |out| { - @memset(out[written..][0..prefix_width], ' '); - @memcpy(out[written + prefix_width ..][0..shown.len], shown); - } - written += prefix_width + shown.len; - ghost += 1; - continue; - } const row = if (context) @as(usize, @intCast(pane.wrap_line[i])) else body_line; const at = if (context) 0 else body_at; const text = if (row < total) sourceLine(pane, @intCast(row)) else ""; @@ -1859,7 +2261,7 @@ fn fillBody(comptime ghosted: bool, tab: u16, dst: ?[]u8, pane: *Pane, f: *State modal.graphemeStart(text, @min(@as(usize, @intCast(pane.hscroll)), text.len)) else at; - if ((width > 0 or pane.context_rows > 0 or ghosted) and record_wrap) { + if ((width > 0 or pane.context_rows > 0) and record_wrap) { pane.wrap_line[i] = @intCast(row); pane.wrap_col[i] = @intCast(cut); pane.wrap_pad[i] = @intCast(pad); @@ -1871,8 +2273,10 @@ fn fillBody(comptime ghosted: bool, tab: u16, dst: ?[]u8, pane: *Pane, f: *State if (dst) |out| { const prefix = out[written..][0..prefix_width]; @memset(prefix, ' '); - if (at == 0 and prefix.len > 0) { - var lineno = row + 1; + // A read-only line has no number; the others, the file's. + const numbered = f.read_only.len == 0 or readOnlyRow(f, row) == null; + if (at == 0 and prefix.len > 0 and numbered) { + var lineno = (if (f.read_only.len == 0) row else fileRow(f, row)) + 1; var digit: usize = number_end; if (row == end_slot) { prefix[digit - 1] = '~'; @@ -1933,21 +2337,22 @@ fn fillBody(comptime ghosted: bool, tab: u16, dst: ?[]u8, pane: *Pane, f: *State /// 3. changes (`Changes [revset]`, jj.zig): while `lanes` is set, a /// lane each of the pane's pinned changes after the line number (the /// gutter `lanes` cells wider), a line one added whole green across -/// it (jj.paint). Ruled, not built (PARDES.md "Changes on the source -/// view"): a changed line's words tinted, ghost rows for what the -/// shown revision has not. -/// 4. churn, ruled, not built: a heat lane after the number and a strip -/// by the scroll thumb. +/// it, a changed line's words, and the ghost lines (the buffer's +/// read-only lines, `State.read_only`) inked (jj.paint). +/// 4. churn (`Churn`): a heat lane after the number and a strip by the +/// scroll thumb. /// /// Two bytes, hashed in one update: a digest takes every view's of every /// pane at every step. pub const Layers = struct { ink: bool = true, - /// Whether this view shows the pane's pinned changes (`Pardes.changes`: - /// the revset and jj's answers are the pane's), as the cells their - /// lanes take (laneCells), 0 while it does not: set from the view's - /// frontend, in a window two, which its strips of pixels fill one and - /// a half of (Surface.Lane), in a terminal three, a glyph each. + /// Whether the pane shows its pinned changes (`Pardes.changes`: the + /// revset and jj's answers are the pane's, and shown, their lines are + /// its buffer's, so every view of it shows them or none does: + /// jj.setLanes), as the cells their lanes take in this view + /// (laneCells), 0 while it does not: by the view's frontend, in a window + /// two, which its strips of pixels fill one and a half of + /// (Surface.Lane), in a terminal three, a glyph each. lanes: u8 = 0, /// Whether this view shows the pane's churn (`Churn`, jj.Heat), as the /// cells its lane takes: one after the number, before the lanes. @@ -2156,7 +2561,7 @@ pub fn paintWordSelection( var vr: i32 = 0; while (vr + @as(i32, pane.tag_rows) < @as(i32, r.h)) : (vr += 1) { const here = pane.wrapAt(p.settings.tab, vr); - if (here.line != row or here.ghost) continue; + if (here.line != row) continue; var hi = word_hi; const next = pane.wrapAt(p.settings.tab, vr + 1); if (next.line == row) hi = @min(hi, next.at); diff --git a/core/Places.zig b/core/Places.zig index c81c7264..1c24e992 100644 --- a/core/Places.zig +++ b/core/Places.zig @@ -671,7 +671,7 @@ pub fn paint(set: *Places, p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, while (vr < body_h) : (vr += 1) { const w = pane.wrapAt(p.settings.tab, vr); const line = w.line; - if (line == last_line or line < 0 or w.ghost) continue; + if (line == last_line or line < 0) continue; if (line >= nlines) break; last_line = line; const ls = File.lineStart(p.gpa, f, @intCast(line)); diff --git a/core/Query.zig b/core/Query.zig index 2ffcfd3b..f91339ca 100644 --- a/core/Query.zig +++ b/core/Query.zig @@ -1079,7 +1079,9 @@ fn writePlacesRows(p: *Pardes, q: *Query, out: *std.ArrayList(u8), rows: *std.Ar } const shade: []const u8 = if (f.highlights.len > 0 and ls >= f.highlight_start and le <= f.highlight_start + f.highlights.len) f.highlights[ls - f.highlight_start .. le - f.highlight_start] else &.{}; try q.items.append(p.gpa, .{ .kind = .hit, .serial = tp.serial, .hit = i, .n = n }); - try writeHitRow(p, out, rows, &sh, width, rel, path, line + 1, f.content[ls..le], hits[i].start - ls, @min(hits[i].end, le) - ls, shade); + // The file's line number (the `Changes` layer's lines have none: a + // hit in one says the line it stands before). + try writeHitRow(p, out, rows, &sh, width, rel, path, File.fileRow(f, line) + 1, f.content[ls..le], hits[i].start - ls, @min(hits[i].end, le) - ls, shade); i += n; } } @@ -1710,7 +1712,8 @@ fn displayPreview(p: *Pardes, qid: usize, path: []const u8, at: look.Spot) void if (t.at.line == 0 or t.at.line > nlines) continue; const full = if (t.path.len > 0 and t.path[0] == '/') t.path else std.fmt.bufPrint(&pathbuf, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), t.path }) catch continue; if (!std.mem.eql(u8, full, f.path)) continue; - const ls = File.lineStart(p.gpa, f, t.at.line - 1); + // The server's line is the file's (File.bufferRow). + const ls = File.lineStart(p.gpa, f, File.bufferRow(f, t.at.line - 1)); const le = std.mem.indexOfScalarPos(u8, f.content, ls, '\n') orelse f.content.len; const col = @min(t.at.col -| 1, le - ls); const end = @min(if (t.at.end_col > 0 and t.at.end_line == t.at.line) t.at.end_col else col + 1, le - ls); @@ -2088,7 +2091,7 @@ pub fn paint(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, body_h: u16) while (vr < body_h) : (vr += 1) { const w = pane.wrapAt(p.settings.tab, vr); const row = w.line; - if (row == last or row < 1 or w.ghost) continue; + if (row == last or row < 1) continue; last = row; const i: usize = @intCast(row - 1); if (i >= q.items.items.len or @as(usize, @intCast(row)) >= f.location_rows.len) continue; diff --git a/core/Stream.zig b/core/Stream.zig index 7956e4f2..c231d413 100644 --- a/core/Stream.zig +++ b/core/Stream.zig @@ -363,8 +363,9 @@ pub fn paintRows(p: *Pardes, path: []const u8) void { if (s.rows_paint != null or !p.tape.has(p, .search)) return; var content: ?[]const u8 = null; var revision: u32 = 0; - for (p.panes) |slot| if (slot) |pane| if (pane.file) |f| if (f.output == null and std.mem.eql(u8, f.path, path)) { - content = f.content; + for (p.panes) |slot| if (slot) |pane| if (pane.file) |*f| if (f.output == null and std.mem.eql(u8, f.path, path)) { + // The file's text: the `Changes` layer's lines are none of it. + content = panes.File.fileText(f, p.scratch.allocator()) catch return; revision = f.revision; break; }; @@ -459,7 +460,9 @@ pub fn parseFor(p: *Pardes, id: usize) void { } const workers = p.tape.has(p, .search) and !p.fs.serving; if (!workers and f.content.len > 64 << 10) return; - const job = TextJob.make(p.gpa, pane.serial, f.revision, 0, f.path, f.content) orelse return; + // The file's text parsed: the `Changes` layer's lines are none of it. + const text = panes.File.fileText(&f, p.scratch.allocator()) catch return; + const job = TextJob.make(p.gpa, pane.serial, f.revision, 0, f.path, text) orelse return; s.gen +%= 1; s.parse_gen = s.gen; job.gen = s.parse_gen; diff --git a/core/Tables.zig b/core/Tables.zig index 61a67bfe..a0256d8a 100644 --- a/core/Tables.zig +++ b/core/Tables.zig @@ -660,7 +660,6 @@ pub fn paint(p: *Pardes, s: *Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: var vr: u16 = 0; while (vr < body_h) : (vr += 1) { const w = pane.wrapAt(p.settings.tab, vr); - if (w.ghost) continue; const table = File.rowTable(pane, w.line) orelse continue; const text = File.sourceLine(pane, w.line); var buf: [max_pads]Pad = undefined; diff --git a/core/Text.zig b/core/Text.zig index 1b3e6273..54d69a74 100644 --- a/core/Text.zig +++ b/core/Text.zig @@ -458,15 +458,17 @@ pub const Journal = struct { j.done = j.steps.items.len; } - /// The `len` bytes of `text` at `off` about to be replaced by `ins` - /// bytes, kept in the last step: in its last entry when they touch it + /// `removed`, the bytes at `off` about to be replaced by `ins` bytes + /// (a file's text's offset: a buffer's read-only lines are none of it, + /// File.fileOffset), kept in the last step: in its last entry when they touch it /// (typing on, deleting what was typed or what borders it, a write /// going on where the last ended), else as an entry of its own. The /// steps to redo go, made on the text before it; an edit with no step to /// go in (before the first mark, or with every step undone) is kept by /// none. On no memory the journal empties: its entries would no longer /// be the text's. - pub fn record(j: *Journal, gpa: std.mem.Allocator, text: []const u8, off: usize, len: usize, ins: usize) void { + pub fn record(j: *Journal, gpa: std.mem.Allocator, removed_bytes: []const u8, off: usize, ins: usize) void { + const len = removed_bytes.len; if (len == 0 and ins == 0) return; j.dropRedo(gpa); if (j.done == 0) return; @@ -485,7 +487,7 @@ pub const Journal = struct { const before = off + len == last.off; if (ins == 0 and (before or off == last.off + last.ins)) { const more = memory.unfilled(gpa, last.removed.len + len) catch return j.deinit(gpa); - const taken = text[off..][0..len]; + const taken = removed_bytes; if (before) { @memcpy(more[0..len], taken); @memcpy(more[len..], last.removed); @@ -500,7 +502,7 @@ pub const Journal = struct { return j.bound(gpa); } } - const removed = memory.dupeUnfilled(gpa, text[off..][0..len]) catch return j.deinit(gpa); + const removed = memory.dupeUnfilled(gpa, removed_bytes) catch return j.deinit(gpa); j.entries.append(gpa, .{ .off = off, .removed = removed, .ins = ins }) catch { memory.freeRaw(gpa, removed); return j.deinit(gpa); diff --git a/core/body_layer.zig b/core/body_layer.zig index 95fb2700..9c4a4c73 100644 --- a/core/body_layer.zig +++ b/core/body_layer.zig @@ -88,7 +88,6 @@ fn paintSourceSelection(p: *Pardes, s: *Surface, pane: *Pane, r: Rect, rows: []c var visible: i32 = 0; while (visible < @as(i32, r.h -| pane.tag_rows)) : (visible += 1) { const source = pane.wrapAt(p.settings.tab, visible); - if (source.ghost) continue; const line = edit.pointerSourceLine(pane, terminal_lines, source.line); const start = @min(line.len, @as(usize, @intCast(@max(0, source.at)))); const next = pane.wrapAt(p.settings.tab, visible + 1); @@ -407,7 +406,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane var vr: i32 = 0; while (vr + @as(i32, pane.tag_rows) < @as(i32, body_bottom)) : (vr += 1) { const w = pane.wrapAt(p.settings.tab, vr); - if (w.line < bnd.lo_row or w.line > bnd.hi_row or w.ghost) continue; + if (w.line < bnd.lo_row or w.line > bnd.hi_row) continue; const visible_line = modal.lineSlice(body, @intCast(vr)); // Only the visible columns are measured: a selection that // starts before this row's first column starts at it, and diff --git a/core/builtins.zig b/core/builtins.zig index e6d22c17..fbb82fc3 100644 --- a/core/builtins.zig +++ b/core/builtins.zig @@ -358,7 +358,7 @@ pub fn warnModifiedIn(c: Ctx, asking: Pane.Discarding, which: Asked) bool { // Nor is a buffer never edited at all: its first edit is what keeps // the text it had (File.zig), so with none there is nothing to lose. const saved = f.saved_hash orelse continue; - if (std.hash.Wyhash.hash(0, f.content) == saved) continue; + if (panes.File.fileHash(&f) == saved) continue; } if (pane.discard_warned) |w| if (w.revision == f.revision and w.by == asking) continue; pane.discard_warned = .{ .revision = f.revision, .by = asking }; diff --git a/core/dump.zig b/core/dump.zig index d09f18c2..c0a84ffe 100644 --- a/core/dump.zig +++ b/core/dump.zig @@ -138,6 +138,18 @@ pub fn dumpExit(p: *Pardes) !void { try dumpState(p); } +/// What a load makes again of each file's pane: its declarations from the +/// file's text (the `Changes` layer's lines are none of it); and a layer a +/// view showed in a dump made before the layer's lines were the buffer's +/// (wire 31 and older: a view's bit, no lines), its lines in it (jj.loaded). +fn afterLoad(p: *Pardes) void { + for (p.panes) |slot| if (slot) |pane| if (pane.file) |*f| { + const text = pardes.panes.File.fileText(f, p.scratch.allocator()) catch continue; + f.context.reload(p.tree_sitter_gpa, f.path, text, f.revision); + }; + @import("jj.zig").loaded(p); +} + /// A file kept slim in a dump (`dumpExit`, a closed pane's past its bound, /// Store.zig): without its undo, and a clean file on disk without its /// text, which `revivePane` reads from its file again. @@ -151,7 +163,9 @@ const Slim = struct { fn take(f: *pardes.panes.File.State) Slim { const s: Slim = .{ .f = f, .history = f.history, .content = f.content }; f.history = ∅ - if (f.output == null and f.revision == f.saved_revision and filesystem.localPath(f.path) != null) f.content = &.{}; + // Not with the `Changes` layer's lines in it: the disk has the + // file's text, not the buffer. + if (f.output == null and f.revision == f.saved_revision and f.read_only.len == 0 and filesystem.localPath(f.path) != null) f.content = &.{}; return s; } @@ -440,7 +454,7 @@ fn loadKnowing(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: for (others) |o| gpa.free(o.panes); gpa.free(others); l.shared.shrinkRetainingCapacity(at); - for (p.panes) |slot| if (slot) |pane| if (pane.file) |*f| f.context.reload(p.tree_sitter_gpa, f.path, f.content, f.revision); + afterLoad(p); p.readSessionFacts(); return p; } @@ -526,7 +540,7 @@ fn loadImage(gpa: std.mem.Allocator, opts: Options, bytes: []const u8, notes: ?* try views.undumpedOld(p, others, gpa); } l.made.shrinkRetainingCapacity(at); - for (p.panes) |slot| if (slot) |pane| if (pane.file) |*f| f.context.reload(p.tree_sitter_gpa, f.path, f.content, f.revision); + afterLoad(p); p.readSessionFacts(); return p; } diff --git a/core/edit.zig b/core/edit.zig index 70b765cc..3517fe80 100644 --- a/core/edit.zig +++ b/core/edit.zig @@ -705,9 +705,9 @@ fn setEditTextSpan(e: Editor, t: *Text, new: []u8, known_end: ?modal.Cursor, spa t.own = new; return; } + // Read-only text (a file at a revision, the `Changes` layer's lines) is + // refused where every edit of a text is, File.edit, in words. 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/edit_cmd.zig b/core/edit_cmd.zig index ab4f2b5d..aec97c63 100644 --- a/core/edit_cmd.zig +++ b/core/edit_cmd.zig @@ -134,13 +134,15 @@ const World = struct { /// What the Edit sees of a pane. Its name is a copy in `arena`: the pane /// may be gone by the time a running Edit's end says it. Its text is the -/// pane's own, read only while the Edit runs its commands' parse. +/// file's (File.fileText: the `Changes` layer's lines are none of it), as +/// 9P serves it, its dot in that text: what it changes is the file's, and +/// what its `w` writes. fn fileOf(arena: std.mem.Allocator, pane: *panes.Pane, id: usize) !sam.File { const f = ninep_pane.fileOf(pane).?; return .{ .name = try arena.dupe(u8, f.path), - .text = f.content, - .dot = ninep_pane.dotOf(pane), + .text = try panes.File.fileText(f, arena), + .dot = ninep_pane.fileDot(pane), .dirty = ninep_pane.dirtyOf(pane), .scratch = f.output != null, .id = id, @@ -406,17 +408,18 @@ fn commit(p: *Pardes, pd: *Pending, outputs: []const []const u8) void { o.text = outputs[j]; }; if (ops.len > 0) { - const new = sam.apply(p.gpa, pf.content, ops) catch |err| return p.reportError(.at(at), "Edit", err); + const was = panes.File.fileText(pf, p.scratch.allocator()) catch |err| return p.reportError(.at(at), "Edit", err); + const new = sam.apply(p.gpa, was, ops) catch |err| return p.reportError(.at(at), "Edit", err); // `s/a/a/` changes nothing: no undo step, no new revision. - if (std.mem.eql(u8, new, pf.content)) p.gpa.free(new) else { + if (std.mem.eql(u8, new, was)) p.gpa.free(new) else { panes.File.pushUndo(p, pane) catch |err| { p.gpa.free(new); return p.reportError(.at(at), "Edit", err); }; - panes.File.setContent(p, pf, new); + panes.File.load(p, pf, new); } } - if (ops.len > 0 or f.moved) ninep_pane.setDot(p.settings.tab, pane, sam.moveDot(f.dot, ops)); + if (ops.len > 0 or f.moved) ninep_pane.setFileDot(p.settings.tab, pane, sam.moveDot(f.dot, ops)); if (f.renamed) ninep_pane.nameBuffer(p, f.id, f.name, false) catch |err| p.reportError(.at(f.id), "Edit", err); } // What was printed, `>`'s output in its place among it. diff --git a/core/jj.zig b/core/jj.zig index 1ec1a0dc..18926594 100644 --- a/core/jj.zig +++ b/core/jj.zig @@ -203,10 +203,10 @@ pub fn looked(p: *Pardes, id: usize, dir: []const u8, text: []const u8, at: look /// What jj answered for a pane's `Changes`: replicated state, the /// session's (`Pardes.changes`, by the pane's serial: a client never runs -/// jj; one that joins late has it in the dump), its revset with it, drawn -/// by each view that shows them (File.Layers.lanes: a view holds that, not -/// the revset; one set a pane, so a view's `Changes other` replaces what -/// every view shows). From two jj runs off the loop (`Ask`): the changes +/// jj; one that joins late has it in the dump), its revset with it. Shown, +/// its ghosts are lines of the pane's buffer, read-only (File.read_only, +/// `showLayer`), so the layer is the pane's: every view of it shows it or +/// none does. From two jj runs off the loop (`Ask`): the changes /// with their diffs of the file (`jj log -p --git`, the diffs read with /// diff.zig's walk), and who wrote each line of the shown revision (`jj /// file annotate`). @@ -222,10 +222,11 @@ pub const Changes = struct { lines: []Line = &.{}, /// Each pin's hunks in the file, a pin's together, each in place order. hunks: []Hunk = &.{}, - /// The ghost rows' text: the lines the hunks took away, hunk after - /// hunk, each with its `\n`; then each pin's description row. + /// The ghosts' text: the lines the hunks took away, hunk after hunk, + /// each with its `\n`; then each pin's description. ghost_text: []u8 = &.{}, - /// The rows a view shows that the text has not, in `at` order. + /// The lines the layer puts in the buffer, the text has not, in `at` + /// order (shown, the buffer's read-only lines in this order). ghosts: []Ghost = &.{}, /// The words a changed line changed: byte ranges of a line (`Line`), or /// of `ghost_text` (`Ghost`), each `.{ from, to }`. @@ -260,8 +261,13 @@ pub fn churned(p: *Pardes, serial: u32) ?*Heat { return null; } -/// Pane `serial`'s answers let go (the pane's end). +/// Pane `serial`'s answers let go (the pane's end); a twin showing its +/// layer, its lines out. pub fn forget(p: *Pardes, serial: u32) void { + for (p.panes) |slot| if (slot) |pane| if (pane.file) |*f| if (f.layer == serial and pane.serial != serial) { + hideLayer(p, f); + setLanes(p, f, false); + }; for (p.changes.answers.items, 0..) |*c, i| if (c.serial == serial) { c.deinit(p.gpa); _ = p.changes.answers.swapRemove(i); @@ -366,15 +372,15 @@ pub const Hunk = struct { pub const carrier = std.math.maxInt(u16); }; -/// A row a view shows that is not a line of the text (PARDES.md "Changes on -/// the source view": a ghost row): a line a pin took away whole, drawn where -/// it stood, red across; or a pin's description (`id title author age`), -/// after its last line, its lane an arrow to it. No number, the cursor -/// steps over it, search and selection do not see it; a Look on it looks at -/// its word as anywhere, on a description's id its change's patch -/// (`lookGhost`). A line a pin CHANGED -/// is a ghost row too: its old text right above the line, the words that -/// went in red, the line with the words that came in green. +/// A line the layer puts in the buffer that the file has not (PARDES.md +/// "Changes on the source view": a ghost line): a line a pin took away +/// whole, where it stood, red across; or a pin's description (`id title +/// author age`, whole), after its last line, its lane an arrow to it. A +/// line a pin CHANGED has one too: its old text right above the line, the +/// words that went in red, the line with the words that came in green. +/// Shown, it is regular text, read-only (File.ReadOnly): no number, the +/// cursor goes onto it, a search finds in it, a Look looks at its word, on +/// a description's id its change's patch (`lookGhost`). pub const Ghost = struct { /// The line of the shown text it stands before (`lines.len`: after the /// last). It rides with the text as the lines' values do (`splice`). @@ -390,6 +396,8 @@ pub const Ghost = struct { /// A changed line's: the words that went (`Changes.marks`). marks: u32 = 0, nmarks: u16 = 0, + /// A description's: where its author starts in its text. + author: u32 = 0, /// A line taken away whole; a line's old text, the line that took its /// place right below it; a pin's description. @@ -397,23 +405,24 @@ pub const Ghost = struct { }; /// The `Changes` word (builtins.zig registers it): in a file's pane (or a -/// revision's), the changes `revset` names pinned on the pane and shown in -/// this view; another revset replaces them (in every view that shows -/// them). Bare: shown in this view or not, the pane's pinned ones (none -/// yet: `@`, the change against its parent). What jj refuses is said in -/// its words. +/// revision's), the changes `revset` names pinned on the pane and shown, +/// in every view of it (its lines are its buffer's); another revset +/// replaces them. Bare: shown or not, the pane's pinned ones (none yet: +/// `@`, the change against its parent). What jj refuses is said in its +/// words. pub fn changesWord(c: pardes.builtins.Ctx) void { const p = c.p; const pane = c.pane; const f = if (pane.file) |*file| file else return p.reportFailure(c.id, "Changes: only a file's pane takes it"); const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); if (arg.len == 0 and pane.layers.lanes > 0) { - pane.layers.lanes = 0; + hideLayer(p, f); + setLanes(p, f, false); return; } - const cells: u8 = if (p.view().frontend.windowed) 2 else levels; if (arg.len == 0 and answered(p, pane.serial) != null) { - pane.layers.lanes = cells; + setLanes(p, f, true); + showLayer(p, f, pane.serial); return; } const revset = if (arg.len == 0) "@" else arg; @@ -424,10 +433,26 @@ pub fn changesWord(c: pardes.builtins.Ctx) void { .{ .path = f.path, .rev = "@" } else return p.reportFailure(c.id, "Changes: only a file's pane takes it"); - pane.layers.lanes = cells; + setLanes(p, f, true); ask(p, .changes, c.id, pane.serial, shown.path, shown.rev, revset); } +/// The layer shown in every view of every pane on `f`'s buffer, or in +/// none: its lines are the buffer's (File.read_only). A view's lanes take +/// cells by its frontend (File.Layers.lanes). +fn setLanes(p: *Pardes, f: *const File.State, on: bool) void { + for (p.panes) |slot| { + const pane = slot orelse continue; + const tf = if (pane.file) |*file| file else continue; + if (tf.content.ptr != f.content.ptr) continue; + for (0..pardes.views.max) |k| { + const v = p.views[k] orelse continue; + const cells: u8 = if (!on) 0 else if (v.frontend.windowed) 2 else levels; + if (k == p.live) pane.layers.lanes = cells else pane.pv[k].layers.lanes = cells; + } + } +} + /// The `Churn` word (builtins.zig registers it): in a file's pane (or a /// revision's), how many changes in `window` touched each declaration, /// shown in this view as a heat lane after the line number and a strip by @@ -726,6 +751,13 @@ pub fn receive(p: *Pardes, b: *const pardes.Stream.Batch) void { /// lines, never asking jj again: the lines a splice takes out take their /// values with them, and a line it puts in is nobody's. pub fn edited(p: *Pardes, f: *const File.State, off: usize, len: usize, bytes: []const u8) void { + // The values are the file's lines': the layer's lines before the edit + // are none of them. + var shown_before: usize = 0; + for (f.read_only) |r| { + if (r.at >= off) break; + shown_before += 1; + } var i = p.changes.answers.items.len; while (i > 0) { i -= 1; @@ -733,11 +765,14 @@ pub fn edited(p: *Pardes, f: *const File.State, off: usize, len: usize, bytes: [ const id = p.paneBySerial(c.serial) orelse continue; const shown = if (p.panes[id].?.file) |*shown| shown else continue; if (shown.content.ptr != f.content.ptr) continue; - splice(p.gpa, c, f.content, off, len, bytes) catch { - // No room for it: its values would lie, so it goes. + // The layer shown: its ghosts stand where its lines are (`placed`). + const placed_by_lines = c.serial == f.layer; + splice(p.gpa, c, f.content, off, len, bytes, shown_before, placed_by_lines) catch { + // No room for it: its values would lie, so it goes; the one + // shown stays (its lines are the buffer's, its places theirs). + if (placed_by_lines) continue; c.deinit(p.gpa); _ = p.changes.answers.swapRemove(i); - showGhosts(p, p.panes[id].?); }; } i = p.changes.heats.items.len; @@ -747,7 +782,7 @@ pub fn edited(p: *Pardes, f: *const File.State, off: usize, len: usize, bytes: [ const id = p.paneBySerial(h.serial) orelse continue; const shown = if (p.panes[id].?.file) |*shown| shown else continue; if (shown.content.ptr != f.content.ptr) continue; - _ = spliceValues(u16, p.gpa, &h.lines, 0, f.content, off, len, bytes) catch { + _ = spliceValues(u16, p.gpa, &h.lines, 0, f.content, off, len, bytes, shown_before) catch { h.deinit(p.gpa); _ = p.changes.heats.swapRemove(i); }; @@ -760,11 +795,12 @@ pub fn edited(p: *Pardes, f: *const File.State, off: usize, len: usize, bytes: [ /// line's text after what it puts in: the lines it takes and puts come /// before it. Else the line it starts in keeps its value, and the lines /// taken and put come after it. -fn splice(gpa: std.mem.Allocator, c: *Changes, text: []const u8, off: usize, len: usize, bytes: []const u8) error{OutOfMemory}!void { - const cut = try spliceValues(Line, gpa, &c.lines, .{ .pin = .none }, text, off, len, bytes) orelse return; +fn splice(gpa: std.mem.Allocator, c: *Changes, text: []const u8, off: usize, len: usize, bytes: []const u8, shown_before: usize, placed_by_lines: bool) error{OutOfMemory}!void { + const cut = try spliceValues(Line, gpa, &c.lines, .{ .pin = .none }, text, off, len, bytes, shown_before) orelse return; const from = cut.from; const take = cut.take; const put = cut.put; + if (placed_by_lines) return; // A ghost row stands before the line it stood before; one before a // line taken out, before the line after what took its place. for (c.ghosts) |*g| { @@ -774,14 +810,16 @@ fn splice(gpa: std.mem.Allocator, c: *Changes, text: []const u8, off: usize, len } /// A value a line, `values`, spliced as `splice` says, a line put in -/// `none`; null when no line is taken or put. -fn spliceValues(comptime T: type, gpa: std.mem.Allocator, values: *[]T, none: T, text: []const u8, off: usize, len: usize, bytes: []const u8) error{OutOfMemory}!?struct { from: usize, take: usize, put: usize } { +/// `none`; null when no line is taken or put. `text` is the buffer, whose +/// `shown_before` lines before the edit are the layer's (none of the +/// file's: File.read_only). +fn spliceValues(comptime T: type, gpa: std.mem.Allocator, values: *[]T, none: T, text: []const u8, off: usize, len: usize, bytes: []const u8, shown_before: usize) error{OutOfMemory}!?struct { from: usize, take: usize, put: usize } { const taken = std.mem.count(u8, text[off..][0..len], "\n"); const put = std.mem.count(u8, bytes, "\n"); if (taken == 0 and put == 0) return null; const line_start = if (std.mem.lastIndexOfScalar(u8, text[0..off], '\n')) |nl| nl + 1 else 0; const in_lead = std.mem.trimStart(u8, text[line_start..off], " \t").len == 0; - const from = std.mem.count(u8, text[0..line_start], "\n") + @intFromBool(!in_lead); + const from = std.mem.count(u8, text[0..line_start], "\n") - shown_before + @intFromBool(!in_lead); if (from > values.len) return null; const take = @min(taken, values.len - from); const next = try gpa.alloc(T, values.len - take + put); @@ -800,11 +838,11 @@ fn pinAnswer(p: *Pardes, id: usize, b: *const pardes.Stream.Batch, revset: []con var line: pardes.Kind.Buf(512) = .{}; const f = if (pane.file) |*file| file else return; // Nothing pinned yet: no gutter for it. - defer if (answered(p, pane.serial) == null) { - pane.layers.lanes = 0; - }; + defer if (answered(p, pane.serial) == null) setLanes(p, f, false); if (b.end == .failed) return p.reportFailure(id, line.print("Changes: {s}", .{b.rows[0..@min(b.rows.len, 480)]})); - var got = parse(p.gpa, p.scratch.allocator(), b.rows, b.styles, f.content) catch |err| return p.reportFailure(id, line.print("Changes: {s}", .{@errorName(err)})); + // jj's lines lined up with the file's (the layer's are none of it). + const text = File.fileText(f, p.scratch.allocator()) catch |err| return p.reportFailure(id, line.print("Changes: {s}", .{@errorName(err)})); + var got = parse(p.gpa, p.scratch.allocator(), b.rows, b.styles, text) catch |err| return p.reportFailure(id, line.print("Changes: {s}", .{@errorName(err)})); switch (got) { .refused => |why| { defer p.gpa.free(why); @@ -819,6 +857,8 @@ fn pinAnswer(p: *Pardes, id: usize, b: *const pardes.Stream.Batch, revset: []con @memcpy(changes.revset[0..revset.len], revset); changes.revset_len = @intCast(revset.len); changes.serial = pane.serial; + // The lines shown go before the answer they are of. + hideLayer(p, f); if (answered(p, pane.serial)) |kept| { kept.deinit(p.gpa); kept.* = changes.*; @@ -827,7 +867,7 @@ fn pinAnswer(p: *Pardes, id: usize, b: *const pardes.Stream.Batch, revset: []con return p.reportFailure(id, "Changes: out of memory"); }; p.setStatus(.at(id), ""); - showGhosts(p, pane); + if (pane.layers.lanes > 0) showLayer(p, f, pane.serial); }, } } @@ -876,7 +916,8 @@ pub fn parsed(p: *Pardes, serial: u32) void { return forgetHeat(p, serial); } if (f.context.revision != f.revision) return pardes.Stream.parseFor(p, id); - const lines = heatOf(p.gpa, p.scratch.allocator(), h.pending[0..h.pending_was], h.pending[h.pending_was..], f.content, f.context.declarations, &h.hottest) catch |err| return p.reportFailure(id, line.print("Churn: {s}", .{@errorName(err)})); + const text = File.fileText(f, p.scratch.allocator()) catch |err| return p.reportFailure(id, line.print("Churn: {s}", .{@errorName(err)})); + const lines = heatOf(p.gpa, p.scratch.allocator(), h.pending[0..h.pending_was], h.pending[h.pending_was..], text, f.context.declarations, &h.hottest) catch |err| return p.reportFailure(id, line.print("Churn: {s}", .{@errorName(err)})); p.gpa.free(h.pending); h.pending = &.{}; h.lines = lines; @@ -944,17 +985,92 @@ fn heatOf(gpa: std.mem.Allocator, arena: std.mem.Allocator, logged: []const u8, return out; } -/// The pane's ghost rows as its geometry reads them (`Pane.ghosts`): the -/// session's answers' (one set a pane), its geometry made again when they -/// change (each step while a view shows them, and as an answer lands). -pub fn showGhosts(p: *Pardes, pane: *Pane) void { - const ch = answered(p, pane.serial); - const ghosts: []const Ghost = if (ch) |c| c.ghosts else &.{}; - const text: []const u8 = if (ch) |c| c.ghost_text else ""; - if (ghosts.ptr == pane.ghosts.ptr and ghosts.len == pane.ghosts.len and text.ptr == pane.ghost_text.ptr) return; - pane.ghosts = ghosts; - pane.ghost_text = text; - pane.geometry_key = 0; +/// The layer of pane `owner` (its `Changes` answer's ghosts, in order) +/// put in `f`'s buffer as its read-only lines (File.ReadOnly), each where +/// it stands: before its file line, a line of its own (PARDES.md "Changes +/// on the source view"). One already there goes first. Every view keeps +/// its place in the file (File.relayer). +pub fn showLayer(p: *Pardes, f: *File.State, owner: u32) void { + const ch = answered(p, owner) orelse return hideLayer(p, f); + if (f.layer != 0) hideLayer(p, f); + // Not out (no memory): nothing more. + if (f.layer != 0) return; + // The file's text, the layer out. + const text = f.content; + var size = text.len; + for (ch.ghosts) |g| size += g.len + 1; + const new = pardes.memory.unfilled(p.gpa, size) catch return; + const spans = p.gpa.alloc(File.ReadOnly, ch.ghosts.len) catch { + pardes.memory.freeRaw(p.gpa, new); + return; + }; + const lines = lineCount(text); + // `text` copied up to `from`; line `line` starts at `line_at`; `n` + // bytes of `new` written. + var from: usize = 0; + var line: usize = 0; + var line_at: usize = 0; + var n: usize = 0; + for (ch.ghosts, spans) |g, *r| { + const at = @min(g.at, lines); + while (line < at) : (line += 1) line_at = if (std.mem.indexOfScalarPos(u8, text, line_at, '\n')) |nl| nl + 1 else text.len; + @memcpy(new[n..][0 .. line_at - from], text[from..line_at]); + n += line_at - from; + from = line_at; + const said = ch.ghost_text[g.text..][0..g.len]; + // After a last line with no `\n`, its `\n` first. + const lead = line_at == text.len and text.len > 0 and text[text.len - 1] != '\n'; + r.* = .{ .at = n, .len = g.len + 1, .line = @intCast(at), .lead = lead }; + if (lead) { + new[n] = '\n'; + @memcpy(new[n + 1 ..][0..g.len], said); + } else { + @memcpy(new[n..][0..g.len], said); + new[n + g.len] = '\n'; + } + n += g.len + 1; + } + @memcpy(new[n..][0 .. text.len - from], text[from..]); + std.debug.assert(n + text.len - from == size); + if (File.relayer(p, f, new, spans, owner)) return; + pardes.memory.freeRaw(p.gpa, new); + p.gpa.free(spans); +} + +/// The layer's lines out of `f`'s buffer, which is the file's text again; +/// every view keeps its place in the file: one in a line that leaves goes +/// to the start of the file line it stood before (File.relayer). +pub fn hideLayer(p: *Pardes, f: *File.State) void { + if (f.layer == 0) return; + const text = File.fileText(f, p.scratch.allocator()) catch return; + const new = pardes.memory.dupeUnfilled(p.gpa, text) catch return; + if (!File.relayer(p, f, new, &.{}, 0)) pardes.memory.freeRaw(p.gpa, new); +} + +/// A session loaded from a dump that kept a layer shown as a view's bit +/// and no lines (wire 31 and older: the ghost rows were drawn, not the +/// buffer's): each pane whose views showed it, its lines in its buffer +/// and shown in every view (File.read_only), its places kept in the file. +pub fn loaded(p: *Pardes) void { + for (p.panes) |slot| { + const pane = slot orelse continue; + const f = if (pane.file) |*file| file else continue; + if (f.layer != 0 or answered(p, pane.serial) == null) continue; + const shown = pane.layers.lanes > 0 or for (0..pardes.views.max) |k| { + if (k != p.live and p.views[k] != null and pane.pv[k].layers.lanes > 0) break true; + } else false; + if (!shown) continue; + setLanes(p, f, true); + showLayer(p, f, pane.serial); + } +} + +/// After an edit of `f`'s buffer (File.edit): the shown layer's ghosts +/// stand before the file lines their lines stand before. +pub fn placed(p: *Pardes, f: *const File.State) void { + const ch = answered(p, f.layer) orelse return; + if (ch.ghosts.len != f.read_only.len) return; + for (ch.ghosts, f.read_only) |*g, r| g.at = r.line; } const Read = union(enum) { refused: []u8, read: Changes }; @@ -969,6 +1085,9 @@ fn parse(gpa: std.mem.Allocator, arena: std.mem.Allocator, logged: []const u8, a defer if (!kept) out.deinit(gpa); var pins: std.ArrayList(Pin) = .empty; defer pins.deinit(gpa); + // Each pin's whole author and title, for its description (`describe`): + // never cut. + var whole: std.ArrayList([2][]const u8) = .empty; // Each change jj answered, oldest first: its pin (or `Hunk.carrier`) // and where its diff starts in `logged`; then the end. const Step = struct { pin: u16, diff: usize }; @@ -978,6 +1097,7 @@ fn parse(gpa: std.mem.Allocator, arena: std.mem.Allocator, logged: []const u8, a if (e.pinned and pins.items.len == pins_max) return .{ .refused = try std.fmt.allocPrint(gpa, "more than {d} changes touch it", .{pins_max}) }; if (steps.items.len == Hunk.carrier) return .{ .refused = try std.fmt.allocPrint(gpa, "more than {d} changes between them touch it", .{Hunk.carrier}) }; if (e.pinned) try pins.append(gpa, e.pin); + if (e.pinned) try whole.append(arena, .{ e.author, e.title }); try steps.append(arena, .{ .pin = if (e.pinned) @intCast(pins.items.len - 1) else Hunk.carrier, .diff = it.index orelse logged.len }); }; try steps.append(arena, .{ .pin = Hunk.carrier, .diff = logged.len }); @@ -999,7 +1119,7 @@ fn parse(gpa: std.mem.Allocator, arena: std.mem.Allocator, logged: []const u8, a for (steps.items[0 .. steps.items.len - 1], steps.items[1..], 0..) |s, next, i| try hunksOf(gpa, arena, s.pin, @intCast(i), logged[s.diff..next.diff], text, out.lines, &hunks, &removed, &marks, &taken); out.hunks = try hunks.toOwnedSlice(gpa); nest(out.lines, out.pins.len); - out.ghosts = try ghostsOf(gpa, arena, out.pins, out.lines, out.hunks, taken.items, &removed, now, moved); + out.ghosts = try ghostsOf(gpa, arena, out.pins, whole.items, out.lines, out.hunks, taken.items, &removed, now, moved); out.ghost_text = try removed.toOwnedSlice(gpa); out.marks = try marks.toOwnedSlice(gpa); kept = true; @@ -1024,7 +1144,7 @@ fn logTemplate(gpa: std.mem.Allocator, revset: []const u8) error{OutOfMemory}![] /// A `logTemplate` line, or null for a line of a diff (which starts with /// a blank, a sign, `@`, `\\` or a word and a blank: never eight of jj's /// id letters, k to z, and a tab). -fn entryOf(l: []const u8) ?struct { pin: Pin, pinned: bool } { +fn entryOf(l: []const u8) ?struct { pin: Pin, pinned: bool, author: []const u8, title: []const u8 } { if (l.len < 11 or l[8] != '\t' or l[10] != '\t') return null; for (l[0..8]) |c| if (c < 'k' or c > 'z') return null; var cols = std.mem.splitScalar(u8, l[11..], '\t'); @@ -1035,7 +1155,7 @@ fn entryOf(l: []const u8) ?struct { pin: Pin, pinned: bool } { const title = cols.rest(); pin.title_len = @intCast(@min(title.len, pin.title.len)); @memcpy(pin.title[0..pin.title_len], title[0..pin.title_len]); - return .{ .pin = pin, .pinned = l[9] == 'p' }; + return .{ .pin = pin, .pinned = l[9] == 'p', .author = author, .title = title }; } /// Which pin wrote each line of `text` (what the pane shows: `whole` is the @@ -1265,7 +1385,7 @@ const max_run = 1024; /// inside lines rewritten since jj's snapshot (`Moved.place`) has no row. /// `text` holds the hunks' removed lines; the descriptions' rows go on /// after them. -fn ghostsOf(gpa: std.mem.Allocator, arena: std.mem.Allocator, pins: []const Pin, lines: []const Line, hunks: []const Hunk, taken: []const Taken, text: *std.ArrayList(u8), now: i64, moved: Moved) error{OutOfMemory}![]Ghost { +fn ghostsOf(gpa: std.mem.Allocator, arena: std.mem.Allocator, pins: []const Pin, whole: []const [2][]const u8, lines: []const Line, hunks: []const Hunk, taken: []const Taken, text: *std.ArrayList(u8), now: i64, moved: Moved) error{OutOfMemory}![]Ghost { const Made = struct { g: Ghost, rank: u64 }; var made: std.ArrayList(Made) = .empty; var ti: usize = 0; @@ -1325,9 +1445,9 @@ fn ghostsOf(gpa: std.mem.Allocator, arena: std.mem.Allocator, pins: []const Pin, rank = m.rank | 1; }; const at_text = text.items.len; - try describe(gpa, text, pin, now); + const author = try describe(gpa, text, pin, whole[k][0], whole[k][1], now); try made.append(arena, .{ - .g = .{ .at = place, .pin = @intCast(k), .kind = .description, .line = @max(first, 1), .text = @intCast(at_text), .len = @intCast(text.items.len - at_text) }, + .g = .{ .at = place, .pin = @intCast(k), .kind = .description, .line = @max(first, 1), .text = @intCast(at_text), .len = @intCast(text.items.len - at_text), .author = @intCast(author - at_text) }, .rank = rank, }); } @@ -1367,46 +1487,33 @@ fn carried(hunks: []const Hunk, from: u16, after: u32, moved: Moved) ?u32 { return moved.place(@intCast(std.math.clamp(pos, 0, @as(i64, moved.was)))); } -/// A pin's description row (PARDES.md: compact, one blank between): its -/// id's first four letters, its title, its author's first name, its age -/// short (`5h`, `2d`, `3w`, `4m`, `1y`; under an hour `now`), no "ago". -fn describe(gpa: std.mem.Allocator, text: *std.ArrayList(u8), pin: Pin, now: i64) error{OutOfMemory}!void { - const author = pin.author[0..pin.author_len]; - try text.print(gpa, "{s} {s} {s} ", .{ pin.id[0..4], pin.title[0..pin.title_len], author[0 .. std.mem.indexOfScalar(u8, author, ' ') orelse author.len] }); +/// A pin's description line (PARDES.md: `id title author age`, one blank +/// between): its id's first four letters, its whole title (its +/// description's first line), its whole author, its age short (`5h`, `2d`, +/// `3w`, `4m`, `1y`; under an hour `now`), no "ago". Nothing is cut: a +/// line too long for its pane wraps as any line does. Where its author +/// starts in `text`. +fn describe(gpa: std.mem.Allocator, text: *std.ArrayList(u8), pin: Pin, author: []const u8, title: []const u8, now: i64) error{OutOfMemory}!usize { + try text.print(gpa, "{s} {s} ", .{ pin.id[0..4], title }); + const at = text.items.len; + try text.print(gpa, "{s} ", .{author}); const s = @max(0, now - pin.time); const day = 24 * 3600; for ([_]struct { u8, i64 }{ .{ 'y', 365 * day }, .{ 'm', 30 * day }, .{ 'w', 7 * day }, .{ 'd', day }, .{ 'h', 3600 } }) |unit| { - if (s >= unit[1]) return text.print(gpa, "{d}{c}", .{ @divFloor(s, unit[1]), unit[0] }); + if (s >= unit[1]) { + try text.print(gpa, "{d}{c}", .{ @divFloor(s, unit[1]), unit[0] }); + return at; + } } try text.appendSlice(gpa, "now"); + return at; } -/// The bytes a description row has at most, cut (`fitted`). -pub const row_max = 256; - -/// A description row (`describe`: `id title author age`) as a body row of -/// `room` cells shows it: whole when it fits, else its title cut to the -/// room left (a `…` where it is cut), so the author and the age stay at -/// its end (PARDES.md: one compact row, both shown). -pub fn fitted(tab: u16, said: []const u8, room: usize, buf: *[row_max]u8) []const u8 { - if (said.len + 3 > row_max or File.displayWidth(tab, said) <= room) return said; - var tail = said.len; - for (0..2) |_| tail = std.mem.lastIndexOfScalar(u8, said[0..tail], ' ') orelse return said; - const head = @min(5, tail); - const keep = room -| File.displayWidth(tab, said[0..head]) -| File.displayWidth(tab, said[tail..]) -| 1; - const title = if (keep == 0) "" else std.mem.trimEnd(u8, said[head..tail][0..File.fitEnd(tab, said[head..tail], 0, keep)], " "); - var out: std.ArrayList(u8) = .initBuffer(buf); - out.appendSliceAssumeCapacity(said[0..head]); - out.appendSliceAssumeCapacity(title); - out.appendSliceAssumeCapacity("\u{2026}"); - out.appendSliceAssumeCapacity(said[tail..]); - return out.items; -} - -/// The lanes on ghost row `gi` (`ghosts[gi]`): those of the line above it -/// that run on below it or whose description is this row or one after it -/// at the same place, then its own pin's. -fn ghostLanes(ch: *const Changes, ghosts: []const Ghost, gi: usize) [levels]PinIndex { +/// The lanes on ghost line `gi` (`ghosts[gi]`): those of the line above it +/// that run on below it or whose description is this line or one after it +/// at the same place, then its own pin's (on a description's rows after +/// its first, not: its lane ended in the arrow). +fn ghostLanes(ch: *const Changes, ghosts: []const Ghost, gi: usize, first_row: bool) [levels]PinIndex { const g = ghosts[gi]; var out: [levels]PinIndex = @splat(.none); var n: usize = 0; @@ -1418,43 +1525,69 @@ fn ghostLanes(ch: *const Changes, ghosts: []const Ghost, gi: usize) [levels]PinI if (later.kind == .description and later.pin == @intFromEnum(lane)) break true; } else false; if (!below and !closes) continue; + if (!first_row and g.kind == .description and @intFromEnum(lane) == g.pin) continue; out[n] = lane; n += 1; }; - if (n < levels and std.mem.indexOfScalar(PinIndex, out[0..n], @enumFromInt(g.pin)) == null) out[n] = @enumFromInt(g.pin); + const own = first_row or g.kind != .description; + if (own and n < levels and std.mem.indexOfScalar(PinIndex, out[0..n], @enumFromInt(g.pin)) == null) out[n] = @enumFromInt(g.pin); return out; } -/// A ghost row's cells: a line taken away whole red across, its text in -/// the line numbers' grey (dimmer than the text's ink); a description's id -/// and title in its lane's colour `lane`, or with one change pinned (no one -/// colour a lane) its id in the theme's keyword ink; its author and age -/// grey; `said`, the row's text as the body shows it (a description -/// `fitted`). -fn inkGhost(p: *Pardes, s: *pardes.Surface, g: Ghost, said: []const u8, marks: []const [2]u32, lane: ?[3]u8, x: u16, y: u16, w: u16) void { +/// A ghost line's cells on one of its rows (body row `vr`, from byte +/// `from` of buffer line `row` to byte `to`): a line taken away whole red +/// across, its text in the line numbers' grey (dimmer than the text's ink); +/// a changed line's old text grey, the words that went red; a +/// description's id and title in its lane's colour `lane`, or with one +/// change pinned (no one colour a lane) its id in the theme's keyword ink, +/// its author and age grey. +fn inkGhost(p: *Pardes, s: *pardes.Surface, pane: *const Pane, g: Ghost, row: i32, from: usize, to: usize, pad: i32, marks: []const [2]u32, lane: ?[3]u8, x: u16, y: u16, w: u16) void { const th = p.theme(); + const tab = p.settings.tab; + const said = File.sourceLine(pane, row); + const Ink = struct { + q: *Pardes, + s: *pardes.Surface, + pane: *const Pane, + row: i32, + from: usize, + to: usize, + pad: i32, + x: u16, + y: u16, + w: u16, + /// The cells of bytes `lo` to `hi` on this row. + fn cells(k: @This(), lo: usize, hi: usize) [2]u16 { + const a = @max(k.from, lo); + const b = @min(k.to, hi); + if (a >= b) return .{ 0, 0 }; + const c0 = k.pad + File.displayOffset(k.q.settings.tab, k.pane, k.row, @intCast(k.from), @intCast(a)); + const c1 = k.pad + File.displayOffset(k.q.settings.tab, k.pane, k.row, @intCast(k.from), @intCast(b)); + return .{ @intCast(std.math.clamp(c0, 0, k.w)), @intCast(std.math.clamp(c1, 0, k.w)) }; + } + fn fg(k: @This(), lo: usize, hi: usize, rgb: [3]u8) void { + const c = k.cells(lo, hi); + for (c[0]..c[1]) |cell| k.s.at(k.x + @as(u16, @intCast(cell)), k.y).style.fg = .{ .rgb = rgb }; + } + }; + const ink: Ink = .{ .q = p, .s = s, .pane = pane, .row = row, .from = from, .to = to, .pad = pad, .x = x, .y = y, .w = w }; + _ = tab; switch (g.kind) { .deleted => s.tint(x, y, w, pardes.colors.Grounds.of(th).del.row, th.lineno), .changed => { - const cells = @min(w, File.displayWidth(p.settings.tab, said)); - for (0..cells) |c| s.at(x + @as(u16, @intCast(c)), y).style.fg = .{ .rgb = th.lineno }; + ink.fg(0, said.len, th.lineno); for (marks[g.marks..][0..g.nmarks]) |m| { - const from = File.displayWidth(p.settings.tab, said[0..@min(m[0], said.len)]); - const to = @min(w, File.displayWidth(p.settings.tab, said[0..@min(m[1], said.len)])); - if (from < to) s.tint(x + @as(u16, @intCast(from)), y, @intCast(to - from), pardes.colors.Grounds.of(th).del.emph, null); + const c = ink.cells(m[0], m[1]); + if (c[0] < c[1]) s.tint(x + c[0], y, c[1] - c[0], pardes.colors.Grounds.of(th).del.emph, null); } }, .description => { - // `id title author age`: the last two words grey. - var grey = said.len; - for (0..2) |_| grey = std.mem.lastIndexOfScalar(u8, said[0..grey], ' ') orelse 0; - const id_cells = if (lane != null) File.displayWidth(p.settings.tab, said) else std.mem.indexOfScalar(u8, said, ' ') orelse said.len; - const title_cells = File.displayWidth(p.settings.tab, said[0..grey]); - const cells = @min(w, File.displayWidth(p.settings.tab, said)); - for (0..cells) |c| { - if (c >= id_cells and c < title_cells) continue; - s.at(x + @as(u16, @intCast(c)), y).style.fg = .{ .rgb = if (c >= title_cells) th.lineno else lane orelse th.kw }; - } + // `id title author age`: the id (and with several pinned the + // title) in the lane's colour, the author and the age grey. + const id_end = std.mem.indexOfScalar(u8, said, ' ') orelse said.len; + const author = @min(g.author, said.len); + ink.fg(0, if (lane != null) author else id_end, lane orelse th.kw); + ink.fg(author, said.len, th.lineno); }, } } @@ -1467,7 +1600,7 @@ fn inkCame(p: *Pardes, s: *pardes.Surface, pane: *Pane, marks: []const [2]u32, r const here = pane.wrapAt(tab, vr); const next = pane.wrapAt(tab, @as(i32, vr) + 1); const first: u32 = @intCast(here.at); - const end: u32 = if (next.line == row and !next.ghost) @intCast(next.at) else len; + const end: u32 = if (next.line == row) @intCast(next.at) else len; for (marks) |m| { const lo = @max(first, @min(m[0], len)); const hi = @min(end, @min(m[1], len)); @@ -1478,74 +1611,70 @@ fn inkCame(p: *Pardes, s: *pardes.Surface, pane: *Pane, marks: []const [2]u32, r } } -/// The line `]g` (`forward`) or `[g` goes to from line `from` of pane's -/// text: the next or the previous change's first line in this view (a run -/// of lines one pin wrote, or where lines one took away stood); null with -/// none shown, or none that way. +/// The pin buffer row `row` of `f` is one of: of a ghost line, its pin's +/// (none for a description); of a file line, the pin that wrote it. +fn ownerOf(ch: *const Changes, f: *const File.State, row: usize) PinIndex { + if (File.readOnlyRow(f, row)) |k| { + if (k >= ch.ghosts.len) return .none; + const g = ch.ghosts[k]; + return if (g.kind == .description) .none else @enumFromInt(g.pin); + } + const line = File.fileRow(f, row); + return if (line < ch.lines.len) ch.lines[line].pin else .none; +} + +/// The line `]g` (`forward`) or `[g` goes to from buffer line `from` of +/// the pane: the next or the previous change's first line (the first of a +/// run of lines one pin wrote or took away: a ghost line is a line); null +/// with none shown, or none that way. pub fn nextChange(p: *Pardes, pane: *const Pane, from: usize, forward: bool) ?usize { if (pane.layers.lanes == 0) return null; - const ch = answered(p, pane.serial) orelse return null; - var best: ?usize = null; - const Best = struct { - fn take(b: *?usize, at: usize, here: usize, fwd: bool) void { - if (if (fwd) at <= here else at >= here) return; - if (b.*) |was| if (if (fwd) at >= was else at <= was) return; - b.* = at; + const f = if (pane.file) |*file| file else return null; + const ch = answered(p, f.layer) orelse return null; + const n = File.lineCount(f.content); + var row = from; + while (true) { + if (forward) { + row += 1; + if (row >= n) return null; + } else { + if (row == 0) return null; + row -= 1; } - }; - for (ch.lines, 0..) |l, i| if (l.pin != .none and (i == 0 or ch.lines[i - 1].pin != l.pin)) Best.take(&best, i, from, forward); - for (ch.ghosts) |g| if (g.kind == .deleted) Best.take(&best, @min(g.at, ch.lines.len -| 1), from, forward); - return best; + const owner = ownerOf(ch, f, row); + if (owner != .none and (row == 0 or ownerOf(ch, f, row - 1) != owner)) return row; + } } -/// A Look (B3) at column `col` of body row `vr` of pane `id` when it is a -/// ghost row (mouse.zig): a regular Look of the word there, as the same -/// text anywhere is looked at; on a description's id, its change's patch at -/// the row for the last line of its this file has (`Diff <id> <path>:<line>`, -/// what a user could type). False on any other row. +/// A Look (B3) at column `col` of body row `vr` of pane `id` on the id of +/// a change's description line (mouse.zig): its change's patch at the row +/// for the last line of it this file has (`Diff <id> <path>:<line>`, what a +/// user could type). False anywhere else: the Look is a regular one. pub fn lookGhost(p: *Pardes, id: usize, vr: i32, col: i32) bool { const pane = p.panes[id].?; - if (pane.layers.lanes == 0 or !pane.wrapAt(p.settings.tab, vr).ghost) return false; - const ch = answered(p, pane.serial) orelse return false; - const gi: usize = @intCast(-1 - pane.wrap_col[@intCast(vr)]); - if (gi >= pane.ghosts.len) return false; - const g = pane.ghosts[gi]; - const said = pane.ghost_text[g.text..][0..g.len]; - const at = File.rawAtDisplay(p.settings.tab, said, @intCast(@max(0, col - @as(i32, File.gutterWidth(pane))))); - const what = wordAt(said, at) orelse return true; - const id_end = std.mem.indexOfScalar(u8, said, ' ') orelse said.len; - if (g.kind == .description and what.ptr == said.ptr and what.len == id_end) { - const f = &pane.file.?; - const path = if (of(f)) |r| r.path else f.path; - var last: u32 = g.line; - for (ch.hunks) |h| if (h.pin == g.pin) { - last = @max(last, h.new_start + h.new_len -| 1); - }; - var line: [4200]u8 = undefined; - const arg = std.fmt.bufPrint(&line, "{s} {s}:{d}", .{ ch.pins[g.pin].id, path, last }) catch return true; - pardes.exec.runBuiltin(p, .Diff, id, "Diff", arg); - return true; - } - pardes.look.lookAt(p, id, what); + const f = if (pane.file) |*file| file else return false; + const ch = answered(p, f.layer) orelse return false; + const tab = p.settings.tab; + const w = pane.wrapAt(tab, vr); + if (w.line < 0 or w.at != 0) return false; + const gi = File.readOnlyRow(f, @intCast(w.line)) orelse return false; + if (gi >= ch.ghosts.len) return false; + const g = ch.ghosts[gi]; + if (g.kind != .description) return false; + const said = File.sourceLine(pane, w.line); + const at = File.byteAtRowDisplay(tab, pane, w.line, 0, col - @as(i32, File.gutterWidth(pane)) - w.pad); + if (at < 0 or at >= (std.mem.indexOfScalar(u8, said, ' ') orelse said.len)) return false; + const path = if (of(f)) |r| r.path else f.path; + var last: u32 = g.line; + for (ch.hunks) |h| if (h.pin == g.pin) { + last = @max(last, h.new_start + h.new_len -| 1); + }; + var line: [4200]u8 = undefined; + const arg = std.fmt.bufPrint(&line, "{s} {s}:{d}", .{ ch.pins[g.pin].id, path, last }) catch return true; + pardes.exec.runBuiltin(p, .Diff, id, "Diff", arg); return true; } -/// The word of a ghost row's text at byte `at`: a run of what a path, a -/// name, an address or an id is made of. -fn wordAt(text: []const u8, at: usize) ?[]const u8 { - const part = struct { - fn of(c: u8) bool { - return std.ascii.isAlphanumeric(c) or std.mem.indexOfScalar(u8, "_./:@-+~", c) != null or c >= 0x80; - } - }.of; - if (at >= text.len or !part(text[at])) return null; - var lo = at; - while (lo > 0 and part(text[lo - 1])) lo -= 1; - var hi = at; - while (hi < text.len and part(text[hi])) hi += 1; - return std.mem.trimEnd(u8, text[lo..hi], ".:"); -} - /// A jj change id as jj writes one: its letters, k to z. pub fn isChangeId(text: []const u8) bool { if (text.len < 4 or text.len > 32) return false; @@ -1708,10 +1837,10 @@ fn hueApart(a: [3]u8, b: [3]u8) f32 { /// The pane's pinned changes as a view shows them, on its body's rows (body_layer.zig, while /// File.Layers.lanes is set): in the gutter's lane cells after the number a /// lane each pin whose block runs down the row, at its level, a glyph in a -/// terminal, a strip of pixels in a window (Surface.lanes); and a line a -/// pin added whole green across it, as a diff's added line; on a ghost row -/// (`Ghost`) its lanes and its cells (`inkGhost`). Not yet: a changed -/// line's words. +/// terminal, a strip of pixels in a window (Surface.lanes); a line a pin +/// added whole green across it, as a diff's added line, a changed line's +/// words that came green; on each row of a ghost line (`Ghost`) its lanes +/// and its cells (`inkGhost`). pub fn paint(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void { if (pane.layers.heat > 0) paintHeat(p, s, pane, r, tx, body_h); if (pane.layers.lanes > 0) paintLanes(p, s, pane, r, tx, tw, body_h); @@ -1733,18 +1862,20 @@ fn heatColour(th: *const pardes.Theme, count: u16, hottest: u16) ?[3]u8 { /// The heat lane: a cell after the line number (before the changes' /// lanes, which stay next to the text they mark), a half block in its -/// line's colour; none on a ghost row or a line in no declaration. +/// line's colour; none on a ghost line or a line in no declaration. fn paintHeat(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u16, body_h: u16) void { const heat = churned(p, pane.serial) orelse return; + const f = if (pane.file) |*file| file else return; const x = tx + File.gutterWidth(pane) - File.laneCells(pane) - 1; const body_y = p.bodyTop(pane, r); const scroll = pane.scroll(); var vr: u16 = pane.context_rows; while (vr < body_h) : (vr += 1) { const row: i32 = if (pane.wrap_n == 0) scroll + @as(i32, vr) else if (vr < pane.wrap_n) pane.wrap_line[vr] else break; - if (vr < pane.wrap_n and pane.wrap_col[vr] < 0) continue; - if (row < 0 or row >= heat.lines.len) continue; - const rgb = heatColour(p.theme(), heat.lines[@intCast(row)], heat.hottest) orelse continue; + if (row < 0 or File.readOnlyRow(f, @intCast(row)) != null) continue; + const line = File.fileRow(f, @intCast(row)); + if (line >= heat.lines.len) continue; + const rgb = heatColour(p.theme(), heat.lines[line], heat.hottest) orelse continue; var style = s.at(x, body_y + vr).style; style.fg = .{ .rgb = rgb }; s.set(x, body_y + vr, "\u{258c}", style); @@ -1771,8 +1902,10 @@ pub fn railHeat(p: *Pardes, s: *pardes.Surface, pane: *Pane, id: usize, rail: pa } fn paintLanes(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void { - const ch = answered(p, pane.serial) orelse return; + const f = if (pane.file) |*file| file else return; + const ch = answered(p, f.layer) orelse return; if (ch.lines.len == 0) return; + const tab = p.settings.tab; var buf: [8][3]u8 = undefined; const colours = laneColours(p.theme(), &buf); if (colours.len == 0) return; @@ -1786,29 +1919,34 @@ fn paintLanes(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u const windowed = p.view().frontend.windowed; const ground = pardes.colors.Grounds.of(p.theme()).add.row; const body_y = p.bodyTop(pane, r); - const scroll = pane.scroll(); + const nrows = File.lineCount(f.content); var vr: u16 = pane.context_rows; while (vr < body_h) : (vr += 1) { const y = body_y + vr; var taken = false; - // On a description row, its change's lane: an arrow to it. + // On a description's first row, its change's lane: an arrow to it. var points: PinIndex = .none; - const lanes: [levels]PinIndex = if (vr < pane.wrap_n and pane.wrap_col[vr] < 0) ghost: { - const gi: usize = @intCast(-1 - pane.wrap_col[vr]); - if (gi >= pane.ghosts.len) continue; - const g = pane.ghosts[gi]; - const said = pane.ghost_text[g.text..][0..g.len]; - var fit: [row_max]u8 = undefined; - inkGhost(p, s, g, if (g.kind == .description) fitted(p.settings.tab, said, File.bodyWidth(pane), &fit) else said, ch.marks, if (one == null) colours[g.pin % colours.len] else null, tx + gutter, y, tw - gutter); - if (g.kind == .description) points = @enumFromInt(g.pin); - taken = g.kind != .description or takenAbove(pane.ghosts, gi); - break :ghost ghostLanes(ch, pane.ghosts, gi); + const w = pane.wrapAt(tab, vr); + if (w.line < 0) continue; + const row: usize = @intCast(w.line); + if (row >= nrows) break; + const lanes: [levels]PinIndex = if (File.readOnlyRow(f, row)) |gi| ghost: { + // A ghost line, on each row it wraps to. + if (gi >= ch.ghosts.len) continue; + const g = ch.ghosts[gi]; + const next = pane.wrapAt(tab, @as(i32, vr) + 1); + const to: usize = if (next.line == w.line) @intCast(next.at) else File.sourceLine(pane, w.line).len; + const first_row = w.at <= 0; + inkGhost(p, s, pane, g, w.line, @intCast(@max(0, w.at)), to, w.pad, ch.marks, if (one == null) colours[g.pin % colours.len] else null, tx + gutter, y, tw - gutter); + if (g.kind == .description and first_row) points = @enumFromInt(g.pin); + taken = g.kind != .description or takenAbove(ch.ghosts, gi); + break :ghost ghostLanes(ch, ch.ghosts, gi, first_row); } else line: { - const row: i32 = if (pane.wrap_n == 0) scroll + @as(i32, vr) else if (vr < pane.wrap_n) pane.wrap_line[vr] else break; - if (row < 0 or row >= ch.lines.len) continue; - const line = ch.lines[@intCast(row)]; + const at = File.fileRow(f, row); + if (at >= ch.lines.len) continue; + const line = ch.lines[at]; if (line.whole and line.pin != .none) s.tint(tx + gutter, y, tw - gutter, ground, null); - if (!line.whole and line.nmarks > 0) inkCame(p, s, pane, ch.marks[line.marks..][0..line.nmarks], row, vr, tx + gutter, y, tw - gutter); + if (!line.whole and line.nmarks > 0) inkCame(p, s, pane, ch.marks[line.marks..][0..line.nmarks], w.line, vr, tx + gutter, y, tw - gutter); break :line line.lanes; }; for (lanes, 0..) |lane, level| { @@ -2049,7 +2187,7 @@ test "Changes pins a revset's changes on the pane, shown in this view: who wrote try testing.expect(std.mem.indexOf(u8, told(p, id), "Changes: no change of `@` touches a.zig") != null); } -test "the pinned changes are the pane's, shown in a view by its own bit: another view's Changes shows its set in both, and its bare Changes hides them there alone" { +test "the layer is the pane's: Changes in one view shows its lines in every view of the pane, another revset there replaces them in all, and a bare Changes in any hides them in all, the text the file's again" { const gpa = testing.allocator; var repo = try Repo.init(gpa) orelse return error.SkipZigTest; defer repo.deinit(gpa); @@ -2062,23 +2200,28 @@ test "the pinned changes are the pane's, shown in a view by its own bit: another const other = p.openView().?; p.update(.{ .command = "Changes @--::@-" }); try testing.expectEqual(before + levels, File.gutterWidth(pane)); - // A view of its own: nothing shown there until it asks. + const shown = try gpa.dupe(u8, pane.file.?.content); + defer gpa.free(shown); + try testing.expect(pane.file.?.read_only.len > 0); + // Shown in the other view too, its lines the same. p.toView(other); - try testing.expectEqual(0, pane.layers.lanes); - try testing.expectEqual(before, File.gutterWidth(pane)); + try testing.expectEqual(levels, pane.layers.lanes); + try testing.expectEqual(before + levels, File.gutterWidth(pane)); + try testing.expectEqualStrings(shown, pane.file.?.content); p.update(.{ .command = "Changes @-" }); try testing.expectEqualStrings("@-", answered(p, pane.serial).?.pinned()); try testing.expectEqual(@as(usize, 1), answered(p, pane.serial).?.pins.len); - // The first view shows the new set, not nothing. p.toView(.at(0)); try testing.expectEqual(levels, pane.layers.lanes); - // Hidden in the other view alone. + // Hidden from the other view: hidden in both, the buffer the file's. p.toView(other); p.update(.{ .command = "Changes" }); try testing.expectEqual(0, pane.layers.lanes); p.toView(.at(0)); - try testing.expectEqual(levels, pane.layers.lanes); - try testing.expectEqual(before + levels, File.gutterWidth(pane)); + try testing.expectEqual(0, pane.layers.lanes); + try testing.expectEqual(before, File.gutterWidth(pane)); + try testing.expectEqualStrings(Repo.two, pane.file.?.content); + try testing.expectEqual(@as(usize, 0), pane.file.?.read_only.len); } test "a client replays Changes from what the session's jj answered and ends equal" { @@ -2222,7 +2365,9 @@ test "Changes draws a lane a pinned change after the line number, nested ones a var repo = try Repo.with(gpa, &.{ .{ fn_text, "fn" }, .{ mid_text, "mid" }, .{ shift_text, "shift" } }, null) orelse return error.SkipZigTest; defer repo.deinit(gpa); for ([_]bool{ false, true }) |windowed| { - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = windowed }); + // Tall enough that every line is in view however long the test's + // directory makes the tag. + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 40, .windowed = windowed }); defer p.deinit(); var line: [4200]u8 = undefined; p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); @@ -2247,7 +2392,7 @@ test "Changes draws a lane a pinned change after the line number, nested ones a // stand between): `fn`'s spine on all; `mid` on 3-6; `shift` on 4. const want = [_][]const u8{ "0", "0", "01", "012", "01", "01", "0", "0", "0", "0" }; for (want, 0..) |lanes, row| { - const y = body.y + @as(u16, @intCast(pane.wrapRow(p.settings.tab, @intCast(row), 0).row)); + const y = body.y + @as(u16, @intCast(pane.wrapRow(p.settings.tab, @intCast(File.bufferRow(&pane.file.?, row)), 0).row)); if (windowed) { var n: usize = 0; for (s.lanes.items) |lane| if (lane.y == y) { @@ -2332,7 +2477,7 @@ fn saidOf(arena: std.mem.Allocator, ch: *const Changes) ![3][]const u8 { return said; } -test "Changes draws what the text has not where it stood, as ghost rows: a line a change took away whole red across, each change's description after its last line in its lane's colour, its lane an arrow to it; no number, their lanes; one change pinned, its lane green beside what it wrote and red beside what it took away; the rows below moved down in this view alone" { +test "Changes draws what the text has not where it stood, as ghost rows: a line a change took away whole red across, each change's description after its last line in its lane's colour, its lane an arrow to it; no number, their lanes; one change pinned, its lane green beside what it wrote and red beside what it took away; the lines below moved down in every view of the pane: the layer is the pane's" { const gpa = testing.allocator; var repo = try Ghosts.repo() orelse return error.SkipZigTest; defer repo.deinit(gpa); @@ -2414,13 +2559,13 @@ test "Changes draws what the text has not where it stood, as ghost rows: a line const text_x = body.x + File.gutterWidth(pane); for ([_]u16{ 4, 5 }, [_]bool{ true, false }) |col, went| try testing.expectEqual(went, std.meta.eql(s.at(text_x + col, body.y + 2).style.bg, pardes.Color{ .rgb = grounds.del.emph })); for ([_]u16{ 4, 5, 6 }, [_]bool{ true, true, false }) |col, came| try testing.expectEqual(came, std.meta.eql(s.at(text_x + col, body.y + 3).style.bg, pardes.Color{ .rgb = grounds.add.emph })); - // The other view shows no lanes: its rows are the text's, unmoved. + // The layer is the pane's (its lines are its buffer's): the other + // view shows the same lines. p.toView(other); - const plain = try Ghosts.rows(p, pane, arena.allocator(), &buf); - var lines = std.mem.splitScalar(u8, Ghosts.mid_text, '\n'); - for (plain[0..6]) |row| try testing.expectEqualStrings(lines.next().?, Ghosts.text(pane, row)); + try testing.expect(pane.layers.lanes > 0); + const there = try Ghosts.rows(p, pane, arena.allocator(), &buf); + for (want, there[0..want.len]) |w, row| try testing.expectEqualStrings(w, Ghosts.text(pane, row)); p.toView(.at(0)); - try testing.expectEqualStrings(said[2], Ghosts.text(pane, (try Ghosts.rows(p, pane, arena.allocator(), &buf))[5])); // One change pinned, mid: a diff. Its rows `b();` (its old text), // `b2();`, `x();`, its description: the lane red beside the first, // green beside the lines, green into its arrow; its id the @@ -2449,7 +2594,7 @@ test "Changes draws what the text has not where it stood, as ghost rows: a line } } -test "the cursor steps over ghost rows and selection does not see them; ]g and [g go from change to change; a Look on one looks at its word as anywhere" { +test "]g and [g go from change to change, to each one's first line, a layer's line among them; a Look on a word of a layer's line is a Look of that word as anywhere" { const gpa = testing.allocator; var repo = try Ghosts.repo() orelse return error.SkipZigTest; defer repo.deinit(gpa); @@ -2460,51 +2605,30 @@ test "the cursor steps over ghost rows and selection does not see them; ]g and [ const id = p.view().active; const pane = p.panes[id].?; p.update(.{ .command = "Changes ::@" }); - const key = struct { - fn send(q: *Pardes, keys: []const u8) void { - for (keys) |k| q.update(.{ .key = .{ .cp = k, .text = &[_]u8{k} } }); - } - }.send; - // From `x();` (line 4) a `j` is on `e();` (line 5), three ghost rows below. - p.update(.{ .command = "Look a.zig:4" }); - try testing.expectEqual(@as(i32, 3), pane.body.cur_row); - key(p, "j"); - try testing.expectEqual(@as(i32, 4), pane.body.cur_row); - try testing.expectEqual(@as(i32, 9), pane.wrapRow(p.settings.tab, 4, 0).row); - // All selected: a ghost row keeps its own ground. - key(p, "%"); - p.sync(); - var arena: std.heap.ArenaAllocator = .init(gpa); - defer arena.deinit(); - var s = try p.render(arena.allocator()); - var body = s.region(.body, id).?.rect; - const x = body.x + File.gutterWidth(pane) + 4; - try testing.expectEqual(pardes.Color{ .rgb = pardes.colors.Grounds.of(p.theme()).del.row }, s.at(x, body.y + 6).style.bg); - try testing.expect(!std.meta.eql(s.at(x, body.y + 6).style.bg, s.at(x, body.y + 4).style.bg)); - key(p, ";"); - // ]g, [g: the changes start on lines 1 (fn), 3 (mid) and 5 (fn again, - // after the lines cut took away). - p.update(.{ .command = "Look a.zig:1" }); - for ([_]i32{ 2, 4, 4 }) |want| { - key(p, "]g"); + // The lines (Ghosts.want): fn's first two, mid's from the old text of + // the line it changed (2), cut's two lines taken away (6), fn's again + // after cut's description (9). + Lines.at(pane, 0, 0); + for ([_]i32{ 2, 6, 9, 9 }) |want| { + Lines.send(p, "]g"); try testing.expectEqual(want, pane.body.cur_row); } - for ([_]i32{ 2, 0 }) |want| { - key(p, "[g"); + for ([_]i32{ 6, 2, 0 }) |want| { + Lines.send(p, "[g"); try testing.expectEqual(want, pane.body.cur_row); } - // A Look (B3) on `c();`'s ghost row is a Look of `c`, as `Look c` - // typed in the pane: no file at a revision opens. - p.update(.{ .command = "Look a.zig:1" }); + // A Look (B3) on `c();`, a line cut took away: a Look of `c`, as + // `Look c` typed in the pane; no file at a revision opens. p.sync(); - s = try p.render(arena.allocator()); - body = s.region(.body, id).?.rect; - p.update(.{ .mouse = .{ .button = .right, .kind = .press, .col = body.x + File.gutterWidth(pane) + 4, .row = body.y + 6 } }); - p.update(.{ .mouse = .{ .button = .right, .kind = .release, .col = body.x + File.gutterWidth(pane) + 4, .row = body.y + 6 } }); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const s = try p.render(arena.allocator()); + const body = s.region(.body, id).?.rect; + Lines.click(p, .right, body.x + File.gutterWidth(pane) + 4, body.y + 6); try testing.expectEqual(id, p.view().active); for (p.panes) |slot| if (slot) |q| if (q.file) |*f| try testing.expect(of(f) == null); const clicked: [2]i32 = .{ pane.body.cur_row, pane.body.cur_col }; - p.update(.{ .command = "Look a.zig:1" }); + Lines.at(pane, 0, 0); look.lookAt(p, id, "c"); try testing.expectEqual(clicked, [2]i32{ pane.body.cur_row, pane.body.cur_col }); } @@ -2605,14 +2729,14 @@ test "ghost rows ride with the text: a line deleted above moves them up, a line r.confirm(try a.local(.{ .command = "Look a.zig:4" })); for (";xd") |k| r.confirm(try a.local(.{ .key = .{ .cp = k, .text = &[_]u8{k} } })); r.settle(); - try testing.expectEqualStrings("fn f() void {\n b2();\n x();\n}\n", a.core.panes[a.core.view().active].?.file.?.content); + try testing.expectEqualStrings("fn f() void {\n b2();\n x();\n}\n", try File.fileText(&a.core.panes[a.core.view().active].?.file.?, a.core.scratch.allocator())); try testing.expectEqualSlices(u32, &.{ 1, 3, 3, 3, 3, 4 }, ats(answered(a.core, serial).?, &got)); try testing.expect(r.diverged == null); try testing.expectEqualSlices(Ghost, answered(a.core, serial).?.ghosts, answered(r.core(), serial).?.ghosts); try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); } -test "a description's ghost row keeps its author and age: in a pane narrower than the row its title gives way, cut to the room" { +test "a description is whole, its title and its author never cut: in a pane narrower than it, it wraps as any line does, its author and age at the end of its last row; its lane ends on its first row in the arrow, its rows after carry the lane's cells blank" { const gpa = testing.allocator; const title = "a title long enough that no narrow pane holds the whole of it beside its author and its age"; var repo = try Repo.with(gpa, &.{.{ "fn f() void {\n a();\n}\n", title }}, null) orelse return error.SkipZigTest; @@ -2628,24 +2752,51 @@ test "a description's ghost row keeps its author and age: in a pane narrower tha const ch = answered(p, pane.serial).?; var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); + const said = try std.fmt.allocPrint(arena.allocator(), "{s} {s} t now", .{ ch.pins[0].id[0..4], title }); + try testing.expectEqualStrings(said, File.sourceLine(pane, 3)); + // Its rows from the fourth, each within the room, put back together: + // the whole of it. var buf: [64][]const u8 = undefined; const got = try Ghosts.rows(p, pane, arena.allocator(), &buf); - const row = Ghosts.text(pane, got[3]); const room = pane.cols - File.gutterWidth(pane) - 1; - try testing.expect(File.displayWidth(p.settings.tab, row) <= room); - try testing.expectStringStartsWith(row, try std.fmt.allocPrint(arena.allocator(), "{s} a title long", .{ch.pins[0].id[0..4]})); - try testing.expectStringEndsWith(row, "\u{2026} t now"); - // Drawn: the id in the keyword's ink, the author and the age grey, - // at the row's end. + var whole: std.ArrayList(u8) = .empty; + var n: usize = 0; + while (whole.items.len < said.len) : (n += 1) { + const row = Ghosts.text(pane, got[3 + n]); + try testing.expect(File.displayWidth(p.settings.tab, row) <= room); + try whole.appendSlice(arena.allocator(), row); + } + try testing.expectEqualStrings(said, whole.items); + try testing.expect(n >= 3); + try testing.expectStringEndsWith(Ghosts.text(pane, got[3 + n - 1]), " t now"); + // Drawn: the id in the keyword's ink on its first row, the author and + // the age grey at the end of its last; the arrow on the first row, + // the rows after it no lane. p.sync(); const s = try p.render(arena.allocator()); const body = s.region(.body, id).?.rect; const x = body.x + File.gutterWidth(pane); try testing.expectEqual(pardes.Color{ .rgb = p.theme().kw }, s.at(x, body.y + 3).style.fg); - const age_x = x + @as(u16, @intCast(File.displayWidth(p.settings.tab, row))) - 1; - try testing.expectEqualStrings("w", s.at(age_x, body.y + 3).grapheme()); - try testing.expectEqual(pardes.Color{ .rgb = p.theme().lineno }, s.at(age_x, body.y + 3).style.fg); - try testing.expectEqual(pardes.Color{ .rgb = p.theme().lineno }, s.at(age_x - 4, body.y + 3).style.fg); + const last: u16 = body.y + 3 + @as(u16, @intCast(n - 1)); + const end = x + @as(u16, @intCast(File.displayWidth(p.settings.tab, Ghosts.text(pane, got[3 + n - 1])))) - 1; + try testing.expectEqualStrings("w", s.at(end, last).grapheme()); + try testing.expectEqual(pardes.Color{ .rgb = p.theme().lineno }, s.at(end, last).style.fg); + try testing.expectEqual(pardes.Color{ .rgb = p.theme().lineno }, s.at(end - 4, last).style.fg); + const first = x - File.laneCells(pane); + for (0..n) |k| { + const y = body.y + 3 + @as(u16, @intCast(k)); + if (windowed) { + var lanes: usize = 0; + for (s.lanes.items) |lane| if (lane.y == y) { + lanes += 1; + try testing.expectEqual(@as(u8, if (k == 0) @intCast(File.laneCells(pane)) else 0), lane.arrow); + }; + try testing.expectEqual(@as(usize, @intFromBool(k == 0)), lanes); + } else for (0..levels) |level| { + const glyph = if (k > 0) " " else if (level == 0) "\u{2570}" else if (level + 1 == levels) "\u{2192}" else "\u{2500}"; + try testing.expectEqualStrings(glyph, s.at(first + @as(u16, @intCast(level)), y).grapheme()); + } + } } } @@ -2718,6 +2869,390 @@ test "lines typed between the word and jj's answer: the ghost rows stand where t try testing.expectEqualSlices(Ghost, ch.ghosts, answered(w.r.core(), w.serial).?.ghosts); } +/// A function `cut` took a line away from and changed another in, and a +/// file beside it: `Changes @-` puts in the buffer the line taken away (a +/// builtin's name and a path in it), the changed line's old text and +/// cut's description, as lines. +const Lines = struct { + const fn_text = "fn f() void {\n a();\n // Syntax b.zig\n c();\n}\n"; + const cut_text = "fn f() void {\n a();\n c2();\n}\n"; + + fn repo() !?Repo { + var r = try Repo.with(testing.allocator, &.{ .{ fn_text, "fn" }, .{ cut_text, "cut" } }, null) orelse return null; + errdefer r.deinit(testing.allocator); + try r.tmp.dir.writeFile(testing.io, .{ .sub_path = "b.zig", .data = "const b = 1;\n" }); + return r; + } + + /// The buffer's lines, the layer shown; `said` cut's description. + fn shown(said: []const u8) [7][]const u8 { + return .{ "fn f() void {", " a();", " // Syntax b.zig", " c();", " c2();", said, "}" }; + } + + fn open(p: *Pardes, file: []const u8) !*Pane { + var line: [4200]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{file}) }); + p.update(.{ .command = "Changes @-" }); + return p.panes[p.view().active].?; + } + + fn send(p: *Pardes, keys: []const u8) void { + for (keys) |k| p.update(.{ .key = if (k == 27) .{ .cp = pardes.Key.escape } else .{ .cp = k, .text = &[_]u8{k} } }); + } + + fn click(p: *Pardes, button: pardes.Mouse.Button, col: u16, row: u16) void { + p.update(.{ .mouse = .{ .button = button, .kind = .press, .col = col, .row = row } }); + p.update(.{ .mouse = .{ .button = button, .kind = .release, .col = col, .row = row } }); + } + + fn at(pane: *Pane, row: i32, col: i32) void { + pane.body.cur_row = row; + pane.body.cur_col = col; + pane.body.vsel.active = false; + pane.body.nsel = 0; + } + + fn description(arena: std.mem.Allocator, ch: *const Changes) ![]const u8 { + return std.fmt.allocPrint(arena, "{s} cut t now", .{ch.pins[0].id[0..4]}); + } +}; + +test "the layer's lines are the pane's text, read-only: j and k go onto them, a selection through them yanks the texts in order, / finds a word only a deleted line has, B2 on a builtin's name there runs it and B3 on a path opens it, a text object and a count work there; typing, d, a paste and a replace there or across their edge are refused in words, the file as it was; a Look at :N is the file's line N; hidden with the cursor in one, it is at the start of the file line it stood before" { + const gpa = testing.allocator; + var repo = try Lines.repo() orelse return error.SkipZigTest; + defer repo.deinit(gpa); + for ([_]bool{ false, true }) |windowed| { + // Tall enough that the body's lines stay in view beside the `/` + // query however long the test's directory makes the tags. + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 44, .windowed = windowed }); + defer p.deinit(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const pane = try Lines.open(p, repo.file); + const id = p.view().active; + const f = &pane.file.?; + const ch = answered(p, pane.serial).?; + const want = Lines.shown(try Lines.description(arena.allocator(), ch)); + for (want, 0..) |w, row| try testing.expectEqualStrings(w, File.sourceLine(pane, @intCast(row))); + try testing.expectEqualStrings(Lines.cut_text, try File.fileText(f, arena.allocator())); + // j and k: onto the line taken away, the old text, the line, the + // description, and back. + p.update(.{ .command = "Look :2" }); + Lines.send(p, ";"); + try testing.expectEqual(@as(i32, 1), pane.body.cur_row); + for ([_]i32{ 2, 3, 4, 5 }) |row| { + Lines.send(p, "j"); + try testing.expectEqual(row, pane.body.cur_row); + } + Lines.send(p, "k"); + try testing.expectEqual(@as(i32, 4), pane.body.cur_row); + // From `a();` through the two lines taken away to `c2();`: yanked, + // the texts as shown, in order. + Lines.at(pane, 1, 0); + Lines.send(p, "xxxxy;"); + try testing.expectEqualStrings(" a();\n // Syntax b.zig\n c();\n c2();\n", p.registers.text(p.gpa, pardes.Registers.default).?); + // A text object (the word under the cursor) and a count there. + Lines.at(pane, 2, 8); + Lines.send(p, "miwy;"); + try testing.expectEqualStrings("Syntax", p.registers.text(p.gpa, pardes.Registers.default).?); + Lines.at(pane, 2, 0); + Lines.send(p, "2j"); + try testing.expectEqual(@as(i32, 4), pane.body.cur_row); + // Refused, in words, the buffer and the file as they were: a key + // typed in it, its line deleted, a paste in it, a character + // replaced, a deletion from the line above into it. + const before = try arena.allocator().dupe(u8, f.content); + for ([_][]const u8{ "iz\x1b", "d", "xd", "p", "rq", "kxxd" }) |keys| { + p.view().active = id; + Lines.at(pane, 2, 6); + p.setMessage(.at(id), ""); + Lines.send(p, keys); + try testing.expectEqualStrings(before, f.content); + try testing.expect(std.mem.indexOf(u8, told(p, id), File.read_only_said) != null); + Lines.send(p, "\x1b;"); + } + try testing.expectEqualStrings(Lines.cut_text, try File.fileText(f, arena.allocator())); + try testing.expectEqual(f.saved_revision, f.revision); + // B2 on the builtin's name in the line taken away runs it; B3 on + // the path there opens it (no selection held: B2 in one runs it). + // (The refusals' words, stacked in the notice band over the body's + // first rows, gone.) + pane.msg_len = 0; + pane.msg_older_len = 0; + p.view().active = id; + Lines.at(pane, 0, 0); + p.sync(); + const s = try p.render(arena.allocator()); + const body = s.region(.body, id).?.rect; + const tx = body.x + File.gutterWidth(pane); + const ty = body.y + @as(u16, @intCast(pane.wrapRow(p.settings.tab, 2, 0).row)); + const ink = pane.layers.ink; + Lines.click(p, .middle, tx + 9, ty); + try testing.expectEqual(!ink, pane.layers.ink); + Lines.click(p, .right, tx + 16, ty); + const opened = p.panes[p.view().active].?; + try testing.expect(std.mem.endsWith(u8, opened.file.?.path, "/b.zig")); + p.view().active = id; + // `:3` is the file's line 3, `c2();`: past the two lines above it. + p.update(.{ .command = "Look :3" }); + Lines.send(p, ";"); + try testing.expectEqual(@as(i32, 4), pane.body.cur_row); + // Hidden with the cursor in the old text: at the start of the line + // it stood before, `c2();`. + Lines.at(pane, 3, 6); + p.update(.{ .command = "Changes" }); + try testing.expectEqualStrings(Lines.cut_text, f.content); + try testing.expectEqual(@as(i32, 2), pane.body.cur_row); + try testing.expectEqual(@as(i32, 0), pane.body.cur_col); + // Shown again: the cursor stays on its line. + p.update(.{ .command = "Changes" }); + try testing.expectEqual(@as(i32, 4), pane.body.cur_row); + // `/` finds a word only the line taken away has. + p.view().active = id; + Lines.at(pane, 0, 0); + Lines.send(p, "/Syntax"); + p.update(.{ .key = .{ .cp = pardes.Key.enter } }); + p.view().active = id; + try testing.expectEqual(@as(i32, 2), pane.body.cur_row); + } +} + +test "THE FILE'S TEXT: with the layer's lines in the buffer, every reader of the file reads what it reads with them out, byte for byte: a Save, a Save to another name, Edit's w, body over 9P, the dirty check, a reread from the disk, a Get, jj's lines asked again, the context declarations, the colours of the file's lines, the language server's text and the place it is asked at" { + const gpa = testing.allocator; + var repo = try Lines.repo() orelse return error.SkipZigTest; + defer repo.deinit(gpa); + const th = @import("ninep/harness.zig"); + const Node = @import("ninep/tree.zig").Node; + const Lsp = @import("dev").host_io.Lsp; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const keep = arena.allocator(); + const Seen = struct { + lsp_source: []const u8 = "", + lsp_offset: u32 = 0, + saved: []const u8 = "", + clean: bool = false, + other: []const u8 = "", + written: []const u8 = "", + body: []const u8 = "", + reread_clean: bool = false, + gotten: []const u8 = "", + lines: []const Line = &.{}, + declarations: []const [3]usize = &.{}, + colours: []const u8 = "", + }; + var seen: [2]Seen = .{ .{}, .{} }; + const other = try std.fmt.allocPrint(keep, "{s}/copy.zig", .{repo.dir}); + const w_path = try std.fmt.allocPrint(keep, "{s}/w.zig", .{repo.dir}); + for ([_]bool{ false, true }, &seen) |shown, *got| { + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 30, .windowed = false }); + defer p.deinit(); + var line: [4200]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); + const id = p.view().active; + const pane = p.panes[id].?; + const f = &pane.file.?; + if (shown) p.update(.{ .command = "Changes @-" }); + try testing.expectEqual(shown, f.read_only.len > 0); + // The same edit of a file line, `c2();` (its line 3). + p.update(.{ .command = "Look :3" }); + Lines.send(p, ";A // e\x1b"); + try testing.expect(f.revision != f.saved_revision); + // The language server: the place it is asked at, the text it is sent. + p.update(.{ .command = "Def" }); + got.lsp_offset = p.lsp_ask.last.?.offset; + const job = try Lsp.snapshot(gpa, p, .{ .id = 1, .kind = .definition, .pane = .at(id), .offset = got.lsp_offset, .arg = "" }); + defer job.free(gpa); + got.lsp_source = try keep.dupe(u8, job.source); + // The context declarations and the colours of the file's lines. + f.tree_context = true; + File.refreshContext(p, pane, f); + var decls: std.ArrayList([3]usize) = .empty; + for (f.context.declarations) |d| try decls.append(keep, .{ d.start_line, d.end_line, d.header_end_line }); + got.declarations = decls.items; + f.tree_context = false; + p.sync(); + _ = try p.render(arena.allocator()); + var colours: std.ArrayList(u8) = .empty; + for (0..File.fileLen(f)) |b| { + const at = File.bufferOffset(f, b, false); + try colours.append(keep, if (at >= f.highlight_start and at - f.highlight_start < f.highlights.len) f.highlights[at - f.highlight_start] else 0xff); + } + got.colours = colours.items; + // body over 9P. + got.body = try keep.dupe(u8, th.rd(p, Node.of(pane.serial, .body), 0, 1 << 16).bytes); + // A Save: what the host is asked to write; clean after it. + p.update(.{ .command = "Save" }); + while (p.nextEffect()) |e| p.perform(e); + got.saved = try keep.dupe(u8, p.fallback.get(repo.file) orelse ""); + got.clean = f.revision == f.saved_revision and !pardes.ctlfs.pane.dirtyOf(pane); + // A Save to another name; Edit's w. + p.update(.{ .command = try std.fmt.bufPrint(&line, "Save {s}", .{other}) }); + while (p.nextEffect()) |e| p.perform(e); + got.other = try keep.dupe(u8, p.fallback.get(other) orelse ""); + p.view().active = id; + p.update(.{ .command = try std.fmt.bufPrint(&line, "Edit ,w {s}", .{w_path}) }); + while (p.nextEffect()) |e| p.perform(e); + got.written = try keep.dupe(u8, p.fallback.get(w_path) orelse ""); + // The disk reread as what was saved: nothing reloaded, clean. + const revision = f.revision; + File.changed(p, @intCast(id), got.saved); + got.reread_clean = f.revision == revision and f.revision == f.saved_revision; + // jj asked again: who wrote each of the file's lines. + p.view().active = id; + p.update(.{ .command = "Changes @-" }); + got.lines = try keep.dupe(Line, answered(p, pane.serial).?.lines); + if (!shown) p.update(.{ .command = "Changes" }); + try testing.expectEqual(shown, f.read_only.len > 0); + // A Get: the file's text from where it was read, the layer kept. + p.update(.{ .command = "Get" }); + got.gotten = try keep.dupe(u8, try File.fileText(f, arena.allocator())); + try testing.expectEqual(shown, f.read_only.len > 0); + } + const off, const on = seen; + try testing.expectEqualStrings("fn f() void {\n a();\n c2(); // e\n}\n", off.saved); + inline for (comptime std.meta.fieldNames(Seen)) |name| { + const a = @field(off, name); + const b = @field(on, name); + if (@TypeOf(a) == bool or @TypeOf(a) == u32) try testing.expectEqual(a, b) else try testing.expectEqualSlices(@TypeOf(a[0]), a, b); + } + try testing.expect(off.clean and off.reread_clean); + try testing.expect(off.declarations.len > 0); +} + +test "an edit made while the layer is shown is the file's: journaled in its lines, its undo lands right shown or hidden, hidden and shown again between; the layer's lines are never in the journal" { + const gpa = testing.allocator; + var repo = try Lines.repo() orelse return error.SkipZigTest; + defer repo.deinit(gpa); + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 20, .windowed = false }); + defer p.deinit(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const pane = try Lines.open(p, repo.file); + const f = &pane.file.?; + const typed = "fn f() void {\n a();\n c2(); // e\n}\n"; + // `c2();`, the line after the two of the layer: appended to, shown. + Lines.at(pane, 4, 0); + Lines.send(p, "A // e\x1b"); + try testing.expectEqualStrings(typed, try File.fileText(f, arena.allocator())); + try testing.expectEqualStrings(" c2(); // e", File.sourceLine(pane, 4)); + // Undone while shown, redone. + Lines.send(p, "u"); + try testing.expectEqualStrings(Lines.cut_text, try File.fileText(f, arena.allocator())); + try testing.expectEqual(@as(usize, 3), f.read_only.len); + try testing.expectEqual(@as(i32, 4), pane.body.cur_row); + Lines.send(p, "U"); + try testing.expectEqualStrings(typed, try File.fileText(f, arena.allocator())); + // Hidden, shown again, then undone: the same file text, the lines + // where they stood. + p.update(.{ .command = "Changes" }); + try testing.expectEqualStrings(typed, f.content); + p.update(.{ .command = "Changes" }); + Lines.send(p, "u"); + try testing.expectEqualStrings(Lines.cut_text, try File.fileText(f, arena.allocator())); + try testing.expectEqualStrings(" c2();", File.sourceLine(pane, 4)); + // Hidden, undone back to before the edit and redone: the file's. + p.update(.{ .command = "Changes" }); + Lines.send(p, "U"); + try testing.expectEqualStrings(typed, f.content); + Lines.send(p, "u"); + try testing.expectEqualStrings(Lines.cut_text, f.content); + // No entry of the journal holds a byte of the layer's. + for (f.history.journal.entries.items) |e| try testing.expect(std.mem.indexOf(u8, e.removed, "Syntax") == null); +} + +test "9P serves the file's text: body, addr and data in its offsets; dot and sel with the cursor in a layer's line are after the file line above it; a write over 9P is the file's, the layer's lines standing where they stood" { + const gpa = testing.allocator; + var repo = try Lines.repo() orelse return error.SkipZigTest; + defer repo.deinit(gpa); + const th = @import("ninep/harness.zig"); + const Node = @import("ninep/tree.zig").Node; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 20, .windowed = false }); + defer p.deinit(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const pane = try Lines.open(p, repo.file); + const serial = pane.serial; + try testing.expectEqualStrings(Lines.cut_text, th.rd(p, Node.of(serial, .body), 0, 1 << 16).bytes); + // The cursor in the line taken away: dot is where `c2();` starts in + // the file, after `a();` (14 + 9 bytes). + Lines.at(pane, 2, 6); + try testing.expectEqualStrings(" 23 23 ", th.rd(p, Node.of(serial, .dot), 0, 64).bytes); + // A selection from `a();` into the old text: what the file has of it. + Lines.at(pane, 1, 0); + Lines.send(p, "xx"); + try testing.expectEqualStrings(" a();\n", th.rd(p, Node.of(serial, .sel), 0, 64).bytes); + Lines.send(p, ";"); + // `addr` 3 is the file's line 3; `data` there is it. + _ = th.wr(p, Node.of(serial, .addr), "3"); + try testing.expectEqualStrings(" c2();\n", th.rd(p, Node.of(serial, .xdata), 0, 64).bytes); + // Written over: the file's line, the layer's lines still before it. + _ = th.wr(p, Node.of(serial, .addr), "3"); + _ = th.wr(p, Node.of(serial, .data), " c3();\n"); + try testing.expectEqualStrings("fn f() void {\n a();\n c3();\n}\n", th.rd(p, Node.of(serial, .body), 0, 1 << 16).bytes); + try testing.expectEqualStrings(" // Syntax b.zig", File.sourceLine(pane, 2)); + try testing.expectEqualStrings(" c3();", File.sourceLine(pane, 4)); + // `dot=addr` from 9P lands on the file's line. + _ = th.wr(p, Node.of(serial, .addr), "3"); + _ = th.wr(p, Node.of(serial, .ctl), "dot=addr"); + try testing.expectEqual(@as(i32, 4), pane.body.cur_row); +} + +test "a session dumped by a build whose layer was a view's bit and no lines (wire 31) loads with the layer shown as it was, its lines in the buffer, the file's text and its places as they were; a hidden one stays hidden" { + const gpa = testing.allocator; + var repo = try Lines.repo() orelse return error.SkipZigTest; + defer repo.deinit(gpa); + for ([_]bool{ true, false }) |shown| { + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 20, .windowed = false }); + defer p.deinit(); + const pane = try Lines.open(p, repo.file); + const f = &pane.file.?; + // As 31 kept it: the view's bit (or none), the buffer the file's. + hideLayer(p, f); + if (!shown) setLanes(p, f, false); + try testing.expectEqualStrings(Lines.cut_text, f.content); + Lines.at(pane, 2, 3); + try pardes.dump.dumpState(p); + const q = try pardes.dump.initFromDump(gpa, .{ .tty_only = true, .cols = 60, .rows = 20, .windowed = false }, p.dump_out.?); + defer q.deinit(); + const back = q.panes[q.view().active].?; + const bf = &back.file.?; + try testing.expectEqualStrings(Lines.cut_text, try File.fileText(bf, q.scratch.allocator())); + try testing.expectEqual(shown, bf.read_only.len == 3); + try testing.expectEqual(shown, back.layers.lanes > 0); + // The cursor on `c2();` (the file's line 3) as it was. + try testing.expectEqualStrings(" c2();", File.sourceLine(back, back.body.cur_row)); + } +} + +test "a client replays the layer's lines and an edit refused among them, and ends equal; a client joined over a pane showing the layer loads its lines" { + var repo = try Lines.repo() orelse return error.SkipZigTest; + defer repo.deinit(testing.allocator); + const R = pardes.replica; + const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{}); + defer a.deinit(); + const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0)); + defer r.deinit(); + var line: [4200]u8 = undefined; + r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) })); + r.confirm(try a.local(.{ .command = "Changes @-" })); + r.confirm(try a.local(.{ .command = "Look :2" })); + for (";jjiz") |k| r.confirm(try a.local(.{ .key = .{ .cp = k, .text = &[_]u8{k} } })); + r.confirm(try a.local(.{ .key = .{ .cp = pardes.Key.escape } })); + for ("jA;") |k| r.confirm(try a.local(.{ .key = .{ .cp = k, .text = &[_]u8{k} } })); + r.confirm(try a.local(.{ .key = .{ .cp = pardes.Key.escape } })); + r.settle(); + try testing.expect(r.diverged == null); + const id = a.core.view().active; + const af = &a.core.panes[id].?.file.?; + const rf = &r.core().panes[id].?.file.?; + try testing.expectEqualStrings("fn f() void {\n a();\n c2();;\n}\n", try File.fileText(af, a.core.scratch.allocator())); + try testing.expectEqualStrings(af.content, rf.content); + try testing.expectEqualSlices(File.ReadOnly, af.read_only, rf.read_only); + try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); + try R.loadsAsSession(a, 2); +} + /// A function three changes wrote: `fn` all of it, `mid` its lines 3-6 /// (rewriting two, adding two), `shift` line 4 again. const Stack = struct { @@ -2795,7 +3330,7 @@ test "the lanes ride with the text: a line typed in a nested block is nobody's, // `x();` (line 5, mid's) deleted: its value goes with it. r.confirm(try a.local(.{ .command = "Look a.zig:5" })); try Keys.send(a, r, ";xd"); - try testing.expectEqualStrings(Stack.shift_text[0..41] ++ Stack.shift_text[50..], a.core.panes[a.core.view().active].?.file.?.content); + try testing.expectEqualStrings(Stack.shift_text[0..41] ++ Stack.shift_text[50..], try File.fileText(&a.core.panes[a.core.view().active].?.file.?, a.core.scratch.allocator())); try testing.expectEqualSlices(u16, &.{ 0, 0, 1, 2, 1, 0, 0, 0, 0 }, pinsOf(answered(a.core, serial).?, &got)); try testing.expectEqual(before[5].lanes, answered(a.core, serial).?.lines[4].lanes); try testing.expect(r.diverged == null); diff --git a/core/look.zig b/core/look.zig index 53c26943..2e3d9e57 100644 --- a/core/look.zig +++ b/core/look.zig @@ -727,7 +727,7 @@ pub fn advanceLookHover(p: *Pardes) void { p.look_hover_wait = null; } -pub fn focusPaneLine(p: *Pardes, id: usize, at: Spot, landing: enum { center, keep }) void { +pub fn focusPaneLine(p: *Pardes, id: usize, at_in: Spot, landing: enum { center, keep }) void { if (id >= MAX_PANES) return; const pane = p.panes[id] orelse return; p.view().active = id; @@ -735,7 +735,13 @@ pub fn focusPaneLine(p: *Pardes, id: usize, at: Spot, landing: enum { center, ke pane.body.normal.clear(); // A kind's place is its `address`'s (lookKind). if (pane.addon != null) return; - if (at.line == 0) return; + if (at_in.line == 0) return; + // A place's line is the file's: past the `Changes` layer's lines. + var at = at_in; + if (pane.file) |*f| if (f.read_only.len > 0) { + at.line = @intCast(panes.File.bufferRow(f, at.line - 1) + 1); + if (at.end_line != 0) at.end_line = @intCast(panes.File.bufferRow(f, at.end_line - 1) + 1); + }; if (pane.file) |*f| { if (at.line > panes.File.nlines(p.gpa, f)) return; if (landing == .center) { @@ -1108,14 +1114,16 @@ fn lookAddress(p: *Pardes, id: usize, path: []const u8, expr: []const u8) void { return missed(p, id, "{s} is no text to address", .{missText(subject, &cut)}); }; if (!by_serial and path.len > 0 and (f.output != null or !std.mem.endsWith(u8, f.path, std.Io.Dir.path.basename(path)))) return; - var a: Addr = .{ .text = f.content, .lim = null, .expr = expr }; + // An address is the file's (`:N` its line N): its text, the `Changes` + // layer's lines none of it (File.fileText), its dot there (fileDot). + var a: Addr = .{ .text = panes.File.fileText(&f, p.scratch.allocator()) catch |err| return p.reportError(.at(id), "look", err), .lim = null, .expr = expr }; // A miss names the file it was looked for in, and is that file's pane's. var cut: [miss_path_cap + "…".len]u8 = undefined; const name = missText(f.path, &cut); // A look whose address fails opens nothing: a pane it opened to read // the address in goes again, the miss said from the pane it came from. const opened_here = open == null and target != id; - const r = a.address(ninep_pane.dotOf(pane)) orelse { + const r = a.address(ninep_pane.fileDot(pane)) orelse { // A line past the end says so as `file:N` does, whichever way it // was written: `<file>:N has no line N`. if (std.fmt.parseInt(usize, expr, 10)) |line| { @@ -1135,7 +1143,7 @@ fn lookAddress(p: *Pardes, id: usize, path: []const u8, expr: []const u8) void { return missed(p, target, "{s}: {s}", .{ name, why }); } clearNavigationSelection(p, pane); - ninep_pane.setDot(p.settings.tab, pane, r); + ninep_pane.setFileDot(p.settings.tab, pane, r); v.active = target; } @@ -1391,13 +1399,14 @@ fn noteLookSource(p: *Pardes, id: usize) void { fn settleLine(p: *Pardes, id: usize, path: []const u8, at: Spot, before: usize, opened: ?usize) void { const shown = p.panes[p.view().active] orelse return; const f = if (shown.file) |*file| file else return; - if (at.line > panes.File.nlines(p.gpa, f)) { + // N is the file's line N (the `Changes` layer's lines have no number). + if (at.line > panes.File.nlines(p.gpa, f) - f.read_only.len) { if (opened) |free| p.removePane(free, null) catch |err| p.reportError(.at(id), "look", err); if (p.panes[before] != null) p.view().active = before; return missedLine(p, id, path, at.line); } if (at.line > 0 and at.col == 0 and at.end_line == 0) { - const start = modal.lineStartOffset(f.content, at.line - 1); + const start = modal.lineStartOffset(f.content, panes.File.bufferRow(f, at.line - 1)); const next = std.mem.indexOfScalarPos(u8, f.content, start, '\n'); const end = if (next) |i| i + 1 else f.content.len; @import("ninep/pane.zig").setDot(p.settings.tab, shown, .{ .q0 = @intCast(start), .q1 = @intCast(end) }); diff --git a/core/lsp/Ask.zig b/core/lsp/Ask.zig index 500f02b5..4d57f21e 100644 --- a/core/lsp/Ask.zig +++ b/core/lsp/Ask.zig @@ -62,15 +62,18 @@ pub fn lspRequest(p: *Pardes, asked: usize, kind: lsp.Kind, arg_in: []const u8) (!zig_buf and std.mem.indexOfAny(u8, arg, " \t\r\n\"\\") != null)) return p.reportFailure(id, said.print("Rename: {s} is no name", .{arg})); } - var off = if (pane.file) |f| modal.offsetAt(f.content, .{ + // A place in the file's text, as the server has it (File.fileText: the + // `Changes` layer's lines are none of it; one in them is after the file + // line above). + var off = if (pane.file) |*f| panes.File.fileOffset(f, modal.offsetAt(f.content, .{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)), - }) else 0; + })) else 0; // Def or Refs given a symbol (a 2-1 chord's selection) asks at its // occurrence nearest the cursor, which a sweep leaves at one end of // what it selected; the server is asked at a place, never a name. if ((kind == .definition or kind == .references) and arg.len > 0) { - const content = pane.file.?.content; + const content = panes.File.fileText(&pane.file.?, p.scratch.allocator()) catch |err| return p.reportError(.at(id), lspWord(kind), err); var nearest: ?usize = null; var best: usize = 0; var from: usize = 0; @@ -188,48 +191,51 @@ fn mapLspEditOffset(edits: []const LspEdit, old: usize) usize { return new_at + (old - old_at); } +/// The server's edits, of the file's text (its offsets; the `Changes` +/// layer's lines are none of it), made as the file's new text (File.load). fn applyLspEdits(p: *Pardes, pane: *Pane, revision: u32, edits: []const LspEdit) bool { const f = if (pane.file) |*file| file else return false; if (f.revision != revision) return false; + const text = panes.File.fileText(f, p.scratch.allocator()) catch return false; var removed: usize = 0; var added: usize = 0; var previous_end: usize = 0; var same = true; for (edits) |e| { - if (e.start < previous_end or e.start > e.end or e.end > f.content.len) return false; + if (e.start < previous_end or e.start > e.end or e.end > text.len) return false; if (e.start == e.end and e.text.len == 0) return false; // an empty insert is a malformed record removed = std.math.add(usize, removed, e.end - e.start) catch return false; added = std.math.add(usize, added, e.text.len) catch return false; previous_end = e.end; - if (same and !std.mem.eql(u8, f.content[e.start..e.end], e.text)) same = false; + if (same and !std.mem.eql(u8, text[e.start..e.end], e.text)) same = false; } if (same) return false; // a no-op response earns no undo entry - const final_len = std.math.add(usize, f.content.len - removed, added) catch return false; + const final_len = std.math.add(usize, text.len - removed, added) catch return false; const replacement = p.gpa.alloc(u8, final_len) catch return false; - const old_cursor = modal.offsetAt(f.content, .{ + const old_cursor = panes.File.fileOffset(f, modal.offsetAt(f.content, .{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)), - }); + })); const mapped_cursor = mapLspEditOffset(edits, old_cursor); var read_at: usize = 0; var write_at: usize = 0; for (edits) |e| { - @memcpy(replacement[write_at .. write_at + (e.start - read_at)], f.content[read_at..e.start]); + @memcpy(replacement[write_at .. write_at + (e.start - read_at)], text[read_at..e.start]); write_at += e.start - read_at; @memcpy(replacement[write_at .. write_at + e.text.len], e.text); write_at += e.text.len; read_at = e.end; } - @memcpy(replacement[write_at..], f.content[read_at..]); + @memcpy(replacement[write_at..], text[read_at..]); edit.pushUndo(p.editor(), &pane.body) catch { p.gpa.free(replacement); return false; }; - panes.File.setContent(p, f, replacement); - const cursor = modal.positionAt(f.content, mapped_cursor); + panes.File.load(p, f, replacement); + const cursor = modal.positionAt(f.content, panes.File.bufferOffset(f, mapped_cursor, false)); pane.body.cur_row = @intCast(cursor.row); pane.body.cur_col = @intCast(cursor.col); pane.body.vsel.active = false; @@ -336,7 +342,8 @@ pub fn lspResponse(p: *Pardes, id: u32, response: ?[]const u8) void { // and n and N step it. const spot = look.parsePathLine(place); if (!p.look_missed and spot.at.line > 0) if (p.panes[v.active]) |there| if (there.file) |*tf| if (spot.at.line <= panes.File.nlines(p.gpa, tf)) { - const ls = panes.File.lineStart(p.gpa, tf, spot.at.line - 1); + // The server's line is the file's (File.bufferRow). + const ls = panes.File.lineStart(p.gpa, tf, panes.File.bufferRow(tf, spot.at.line - 1)); const line = tf.content[ls .. std.mem.indexOfScalarPos(u8, tf.content, ls, '\n') orelse tf.content.len]; const col = @min(spot.at.col -| 1, line.len); // To its end when the server said it, else the word there. diff --git a/core/mouse.zig b/core/mouse.zig index 7c9007a1..2d731acf 100644 --- a/core/mouse.zig +++ b/core/mouse.zig @@ -1250,8 +1250,9 @@ fn dragRelease(p: *Pardes, button: Mouse.Button) void { } } else { const clk = pane.sel[b]; - // A right-click on a ghost row (jj.zig) looks at the word - // there, as anywhere. + // A right-click on a change's id in its description line + // (jj.zig) opens its patch there; anywhere else on the + // layer's lines, a Look as anywhere (below). if (s.button == config.look_button and clk.r0 >= pane.tag_rows and clk.r0 == clk.r1 and clk.c0 == clk.c1 and pane.layers.lanes > 0 and @import("jj.zig").lookGhost(p, s.id, clk.r0 - pane.tag_rows, clk.c0)) { diff --git a/core/ninep/ctl.zig b/core/ninep/ctl.zig index 7b4e2754..2090f17e 100644 --- a/core/ninep/ctl.zig +++ b/core/ninep/ctl.zig @@ -426,7 +426,7 @@ pub fn paneText(p: *Pardes, pane: *Pane, buf: *[pane_text_cap]u8) []const u8 { pane.serial, if (pane_files.tagOf(p, pane)) |tag| tag.len else |_| 0, // a length, as a stat's: none when the tag cannot be made // A terminal's body is its history, read whole on an open's first read. - if (pane.isTerminal()) pardes.Term.scrollbackLen(pane.terminal) else pane_files.bodyOf(pane).len, + if (pane.isTerminal()) pardes.Term.scrollbackLen(pane.terminal) else pane_files.bodyOf(p, pane).len, // A directory pane is one, as acme's isdir says. @intFromBool(if (pane.file) |f| f.listing != null else false), @intFromBool(pane_files.dirtyOf(pane)), @@ -1202,10 +1202,10 @@ fn acmeCtl(p: *Pardes, req: Req, serial: u32, line: []const u8, apply: bool) Acm .delete => return .{ .builtin = "Delete" }, .@"dot=addr", .@"addr=dot", .@"limit=addr", .show, .cleartag => { if (apply) switch (w) { - .@"dot=addr" => pane_files.setDot(p.settings.tab, pane, pf.addr), - .@"addr=dot" => pf.addr = pane_files.dotOf(pane), + .@"dot=addr" => pane_files.setFileDot(p.settings.tab, pane, pf.addr), + .@"addr=dot" => pf.addr = pane_files.fileDot(pane), .@"limit=addr" => pf.limit = pf.addr, - .show => pane_files.showOffset(p.settings.tab, pane, pane_files.dotOf(pane).q0), + .show => pane_files.showFileOffset(p.settings.tab, pane, pane_files.fileDot(pane).q0), else => _ = pane_files.truncate(p, pane, .tag), }; return .done; @@ -1240,7 +1240,7 @@ pub fn getRefused(p: *Pardes, pane: *Pane, word: []const u8) ?[]const u8 { if (f.output != null and f.content.len < 100) return null; // Dirty by a rename alone is no text to lose: only edits are asked about. const saved = f.saved_hash orelse return null; - if (std.hash.Wyhash.hash(0, f.content) == saved) return null; + if (panes.File.fileHash(f) == saved) return null; if (pane.discard_warned) |w| if (w.revision == f.revision and w.by == .get) return null; pane.discard_warned = .{ .revision = f.revision, .by = .get }; const id = p.paneBySerial(pane.serial).?; @@ -1274,10 +1274,11 @@ pub fn getFile(p: *Pardes, pane: *Pane, path: []const u8) GetError!void { p.gpa.free(bytes); return if (err == error.OutOfMemory) error.OutOfMemory else error.InvalidName; }; - panes.File.setContent(p, f, bytes); + // The file's new text: the layer's lines out and back (File.load). + panes.File.load(p, f, bytes); f.saved_revision = f.revision; - f.saved_hash = std.hash.Wyhash.hash(0, f.content); - f.saved_len = f.content.len; + f.saved_hash = panes.File.fileHash(f); + f.saved_len = panes.File.fileLen(f); f.disk_newer = null; f.disk_newer_warned = false; f.disk_gone = false; @@ -1307,10 +1308,11 @@ pub fn get(p: *Pardes, pane: *Pane) GetError!void { p.gpa.free(bytes); return err; }; - panes.File.setContent(p, f, bytes); + // The file's new text: the layer's lines out and back (File.load). + panes.File.load(p, f, bytes); f.saved_revision = f.revision; - f.saved_hash = std.hash.Wyhash.hash(0, f.content); - f.saved_len = f.content.len; + f.saved_hash = panes.File.fileHash(f); + f.saved_len = panes.File.fileLen(f); f.disk_newer = null; f.disk_gone = false; f.on_disk = fs.localPath(f.path) != null; diff --git a/core/ninep/events.zig b/core/ninep/events.zig index 1fd05b54..f1e17324 100644 --- a/core/ninep/events.zig +++ b/core/ninep/events.zig @@ -722,7 +722,7 @@ pub fn writeEvent(p: *Pardes, asked: Req, id: usize) Reply { } const serial = pane0.serial; { - const body = pane_files.bodyOf(pane0); + const body = pane_files.bodyOf(p, pane0); const tag = pane_files.tagOf(p, pane0) catch return Reply.fail(req.tag, E.NOMEM); var check: EventReader = .{ .data = req.data }; while (check.next()) |r| { @@ -749,7 +749,7 @@ pub fn writeEvent(p: *Pardes, asked: Req, id: usize) Reply { while (run.next()) |r| { const live = p.paneBySerial(serial) orelse break; const pane = p.panes[live].?; - const whole = if (r.action.onTag()) pane_files.tagOf(p, pane) catch return Reply.fail(req.tag, E.NOMEM) else pane_files.bodyOf(pane); + const whole = if (r.action.onTag()) pane_files.tagOf(p, pane) catch return Reply.fail(req.tag, E.NOMEM) else pane_files.bodyOf(p, pane); const lo = @min(@as(usize, r.q0), whole.len); const hi = @max(lo, @min(@as(usize, r.q1), whole.len)); // An empty range with no text is a click at that point: expanded as diff --git a/core/ninep/pane.zig b/core/ninep/pane.zig index d47b637b..2616c735 100644 --- a/core/ninep/pane.zig +++ b/core/ninep/pane.zig @@ -146,11 +146,28 @@ pub const State = struct { // ---- what a pane is ---- -pub fn bodyOf(pane: *const Pane) []const u8 { +/// A pane's text as 9P serves it: a file's text (File.fileText: the +/// buffer less its read-only lines, the `Changes` layer's, which are no +/// text of the file's). Every address, `dot` and range over 9P is of this +/// text (`fileDot`); a write to it is the file's (`spliceBody`). +pub fn bodyOf(p: *Pardes, pane: *const Pane) []const u8 { + if (pane.file) |*f| return panes.File.fileText(f, p.scratch.allocator()) catch ""; + return ""; +} + +/// The buffer the editor edits (with the layer's lines): what the +/// editor's own dot is of (`dotOf`, `setDot`). +fn bufferOf(pane: *const Pane) []const u8 { if (pane.file) |*f| return f.content; return ""; } +/// Whether 9P reads of the pane are a copy of its file's text, not a +/// region of its buffer (`fsPayload` reads the buffer). +fn layered(pane: *const Pane) bool { + return if (pane.file) |*f| f.read_only.len > 0 else false; +} + pub fn fileOf(pane: *Pane) ?*panes.File.State { return if (pane.file) |*f| f else null; } @@ -240,7 +257,7 @@ fn positionAt(pane: *const Pane, text: []const u8, off: usize) modal.Cursor { } pub fn dotOf(pane: *Pane) State.Range { - const text = bodyOf(pane); + const text = bufferOf(pane); // In runes, as every address is (modal.runeStart). const head = runeOffsetAt(pane, text, .{ .row = @intCast(@max(0, pane.body.cur_row)), .col = @intCast(@max(0, pane.body.cur_col)) }); if (!pane.body.vsel.active) return .{ .q0 = clip(head), .q1 = clip(head) }; @@ -251,7 +268,7 @@ pub fn dotOf(pane: *Pane) State.Range { } pub fn setDot(tab: u16, pane: *Pane, r: State.Range) void { - const text = bodyOf(pane); + const text = bufferOf(pane); const q0 = @min(@as(usize, r.q0), text.len); const q1 = @max(q0, @min(@as(usize, r.q1), text.len)); const a = runePositionAt(pane, text, q0); @@ -268,7 +285,7 @@ pub fn setDot(tab: u16, pane: *Pane, r: State.Range) void { /// a write shown is not a write that moves dot (acme's textinsert leaves /// dot where its rule puts it; only the view follows the text). pub fn showOffset(tab: u16, pane: *Pane, off: usize) void { - const text = bodyOf(pane); + const text = bufferOf(pane); const c = positionAt(pane, text, @min(off, text.len)); // Where dot is now, kept: pinned, so the view moving under it does not // move it to the view's top (pinCursor). @@ -282,6 +299,26 @@ pub fn showOffset(tab: u16, pane: *Pane, off: usize) void { pane.body.cur_col = col; } +/// `dotOf` in the file's text's offsets, as 9P serves it (`bodyOf`): a dot +/// in a read-only line is after the file line above it. +pub fn fileDot(pane: *Pane) State.Range { + const d = dotOf(pane); + const f = if (pane.file) |*file| file else return d; + return .{ .q0 = clip(panes.File.fileOffset(f, d.q0)), .q1 = clip(panes.File.fileOffset(f, d.q1)) }; +} + +/// `setDot` from the file's text's offsets (`fileDot`). +pub fn setFileDot(tab: u16, pane: *Pane, r: State.Range) void { + const f = if (pane.file) |*file| file else return setDot(tab, pane, r); + setDot(tab, pane, .{ .q0 = clip(panes.File.bufferOffset(f, r.q0, false)), .q1 = clip(panes.File.bufferOffset(f, r.q1, r.q1 > r.q0)) }); +} + +/// `showOffset` of a file's text's offset. +pub fn showFileOffset(tab: u16, pane: *Pane, off: usize) void { + const f = if (pane.file) |*file| file else return showOffset(tab, pane, off); + showOffset(tab, pane, panes.File.bufferOffset(f, off, false)); +} + pub fn clampAddr(pf: *State, len: usize) void { const n = clip(len); pf.addr.q0 = @min(pf.addr.q0, n); @@ -314,18 +351,21 @@ pub fn wholeUtf8(data: []const u8) usize { return data.len; } +/// `bytes` over `q0`..`q1` of the file's text (`bodyOf`'s offsets): the +/// file's edit (File.replaceFile), never refused for the layer's lines. pub fn spliceBody(p: *Pardes, pane: *Pane, q0: usize, q1: usize, bytes: []const u8) ?usize { const f = fileOf(pane) orelse return null; const take = if (bytes.len == 0) 0 else wholeUtf8(bytes); - const lo = @min(q0, f.content.len); - const hi = @max(lo, @min(q1, f.content.len)); + const text = bodyOf(p, pane); + const lo = @min(q0, text.len); + const hi = @max(lo, @min(q1, text.len)); // An empty range deleted, or a range replaced by what it holds: no // edit, so no undo step and no new revision. - if (std.mem.eql(u8, f.content[lo..hi], bytes[0..take])) return take; + if (std.mem.eql(u8, text[lo..hi], bytes[0..take])) return take; const join = pane.fs.joined == f.revision; pane.fs.joined = null; if (!pane.fs.nomark and !join) panes.File.pushUndo(p, pane) catch return null; - if (!panes.File.replace(p, f, lo, hi - lo, bytes[0..take])) return null; + if (!panes.File.replaceFile(p, f, lo, hi - lo, bytes[0..take])) return null; return take; } @@ -340,7 +380,7 @@ pub fn fileSize(p: *Pardes, id: usize, f: PaneFile) u64 { const pf = &pane.fs; return switch (f) { // 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, + .body => if (pane.file == null and pane.isTerminal()) pardes.Term.scrollbackLen(pane.terminal) else if (kindText(p, pane)) |t| t.len else bodyOf(p, pane).len, // What addr selects, generated by each read: no length, as acme's // data and xdata have none; and rows, made by each read. .data, .xdata, .rows => 0, @@ -351,7 +391,7 @@ pub fn fileSize(p: *Pardes, id: usize, f: PaneFile) u64 { break :ctl ctl.paneText(p, pane, &buf).len; }, .sel => sel: { - const d = dotOf(pane); + const d = fileDot(pane); break :sel @max(d.q0, d.q1) - d.q0; }, .addr => if (pf.addr_failed) 0 else range_len, @@ -407,14 +447,14 @@ pub fn read(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply // A failed address reads empty, as an unset limit does: there is // none. data and xdata are what refuse. .addr => readRange(p, req, if (pf.addr_failed) null else addr: { - clampAddr(pf, bodyOf(pane).len); + clampAddr(pf, bodyOf(p, pane).len); break :addr pf.addr; }), - .dot => readRange(p, req, dotOf(pane)), + .dot => readRange(p, req, fileDot(pane)), .limit => readRange(p, req, pf.limit), - .data => readData(req, id, pane, pf, false), - .xdata => readData(req, id, pane, pf, true), - .sel => readSel(req, id, pane), + .data => readData(p, req, id, pane, pf, false), + .xdata => readData(p, req, id, pane, pf, true), + .sel => readSel(p, req, id, pane), .dirty => readFlag(p, req, dirtyOf(pane)), .mark => readFlag(p, req, !pf.nomark), .scroll => readFlag(p, req, !pf.noscroll), @@ -457,7 +497,9 @@ fn kindText(p: *Pardes, pane: *Pane) ?[]const u8 { fn readBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { if (pane.file != null) { - const text = bodyOf(pane); + const text = bodyOf(p, pane); + // The layer's lines in the buffer: a copy of the file's text. + if (layered(pane)) return tree.window(p, req, text); const off = @min(req.off, text.len); const n = @min(text.len - off, req.size); return .{ .tag = req.tag, .payload = .{ .region = .{ @@ -476,9 +518,9 @@ fn readBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { return tree.window(p, req, text); } -fn readData(req: Req, id: usize, pane: *Pane, pf: *State, stop_at_end: bool) Reply { +fn readData(p: *Pardes, req: Req, id: usize, pane: *Pane, pf: *State, stop_at_end: bool) Reply { if (pf.addr_failed) return tree.failText(req.tag, E.INVAL, e_addr_failed); - const text = bodyOf(pane); + const text = bodyOf(p, pane); clampAddr(pf, text.len); const q0: usize = pf.addr.q0; const hi: usize = if (stop_at_end) @max(q0, @as(usize, pf.addr.q1)) else text.len; @@ -487,6 +529,11 @@ fn readData(req: Req, id: usize, pane: *Pane, pf: *State, stop_at_end: bool) Rep pf.addr.q0 = clip(end); if (!stop_at_end) pf.addr.q1 = clip(end); if (pane.file == null) return .{ .tag = req.tag }; + if (layered(pane)) { + var whole = req; + whole.off = 0; + return tree.window(p, whole, text[q0..end]); + } return .{ .tag = req.tag, .payload = .{ .region = .{ .pane = @intCast(id), .serial = pane.serial, @@ -495,14 +542,19 @@ fn readData(req: Req, id: usize, pane: *Pane, pf: *State, stop_at_end: bool) Rep } } }; } -fn readSel(req: Req, id: usize, pane: *Pane) Reply { +fn readSel(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { if (pane.file == null) return .{ .tag = req.tag }; - const text = bodyOf(pane); - const d = dotOf(pane); + const text = bodyOf(p, pane); + const d = fileDot(pane); const lo = @min(@as(usize, d.q0), text.len); const hi = @max(lo, @min(@as(usize, d.q1), text.len)); const off = @min(req.off, hi - lo); const n = @min(hi - lo - off, req.size); + if (layered(pane)) { + var whole = req; + whole.off = 0; + return tree.window(p, whole, text[lo + off ..][0..n]); + } return .{ .tag = req.tag, .payload = .{ .region = .{ .pane = @intCast(id), .serial = pane.serial, @@ -519,7 +571,7 @@ pub fn write(p: *Pardes, req: Req, id: usize, pane: *Pane, file: PaneFile) Reply .body => writeBody(p, req, id, pane), .tag => writeTag(p, req, pane), .ctl => ctl.writePane(p, req, pane), - .addr, .dot, .limit => writeRange(p.settings.tab, req, pane, file), + .addr, .dot, .limit => writeRange(p, req, pane, file), .data, .xdata => writeData(p, req, pane), .sel => writeSel(p, req, pane), .dirty, .mark, .scroll => writeFlag(p, req, pane, file), @@ -603,13 +655,13 @@ pub fn flushBatch(p: *Pardes) void { const id = p.paneBySerial(b.serial) orelse return; const pane = p.panes[id].?; if (fileOf(pane) == null) return; - const before = dotOf(pane); + const before = fileDot(pane); const take = spliceJoined(p, pane, b.at, b.at, b.bytes.items, b.handle) orelse return; - setDot(p.settings.tab, pane, .{ + setFileDot(p.settings.tab, pane, .{ .q0 = shiftOne(before.q0, clip(b.at), 0, clip(take)), .q1 = shiftOne(before.q1, clip(b.at), 0, clip(take)), }); - if (!pane.fs.noscroll) showOffset(p.settings.tab, pane, b.at + take); + if (!pane.fs.noscroll) showFileOffset(p.settings.tab, pane, b.at + take); } /// How many bytes this open's write holds back (`fs.batch`) for its pane. @@ -645,11 +697,11 @@ fn writeBody(p: *Pardes, req: Req, id: usize, pane: *Pane) Reply { p.emitWrite(id, req.data[0..take]); return .{ .tag = req.tag, .written = @intCast(take) }; } - const at = bodyOf(pane).len + heldBytes(p, req, pane); + const at = bodyOf(p, pane).len + heldBytes(p, req, pane); if (holdWrite(p, req, pane, at) catch return Reply.fail(req.tag, E.NOMEM)) |take| return .{ .tag = req.tag, .written = @intCast(take) }; const take = spliceJoined(p, pane, at, at, req.data, req.handle) orelse return Reply.fail(req.tag, E.NOMEM); - if (!pane.fs.noscroll) showOffset(p.settings.tab, pane, at + take); + if (!pane.fs.noscroll) showFileOffset(p.settings.tab, pane, at + take); return .{ .tag = req.tag, .written = @intCast(take) }; } @@ -738,7 +790,7 @@ fn writeData(p: *Pardes, req: Req, pane: *Pane) Reply { if (fileOf(pane) == null) return tree.failText(req.tag, E.INVAL, e_no_text); const pf = &pane.fs; if (pf.addr_failed) return tree.failText(req.tag, E.INVAL, e_addr_failed); - clampAddr(pf, bodyOf(pane).len + heldBytes(p, req, pane)); + clampAddr(pf, bodyOf(p, pane).len + heldBytes(p, req, pane)); const q0: usize = pf.addr.q0; const q1: usize = @max(q0, @as(usize, pf.addr.q1)); // An insert (an empty address) goes on from the open's held bytes. @@ -747,15 +799,15 @@ fn writeData(p: *Pardes, req: Req, pane: *Pane) Reply { return .{ .tag = req.tag, .written = @intCast(take) }; }; flushBatch(p); - const before = dotOf(pane); + const before = fileDot(pane); const take = spliceJoined(p, pane, q0, q1, req.data, req.handle) orelse return Reply.fail(req.tag, E.NOMEM); - setDot(p.settings.tab, pane, .{ + setFileDot(p.settings.tab, pane, .{ .q0 = shiftOne(before.q0, clip(q0), clip(q1 - q0), clip(take)), .q1 = shiftOne(before.q1, clip(q0), clip(q1 - q0), clip(take)), }); pf.addr = .{ .q0 = clip(q0 + take), .q1 = clip(q0 + take) }; - if (!pf.noscroll) showOffset(p.settings.tab, pane, q0 + take); + if (!pf.noscroll) showFileOffset(p.settings.tab, pane, q0 + take); return .{ .tag = req.tag, .written = @intCast(take) }; } @@ -764,7 +816,7 @@ fn writeSel(p: *Pardes, req: Req, pane: *Pane) Reply { const pf = &pane.fs; // The same open's next write follows its last; any other replaces dot. const going_on = req.handle != 0 and pf.wrsel_by == req.handle; - const d = if (going_on) State.Range{ .q0 = pf.wrsel.q1, .q1 = pf.wrsel.q1 } else dotOf(pane); + const d = if (going_on) State.Range{ .q0 = pf.wrsel.q1, .q1 = pf.wrsel.q1 } else fileDot(pane); const q0: usize = d.q0; const q1: usize = @max(q0, @as(usize, d.q1)); const take = spliceBody(p, pane, q0, q1, req.data) orelse @@ -774,7 +826,7 @@ fn writeSel(p: *Pardes, req: Req, pane: *Pane) Reply { const start = if (going_on) pf.wrsel.q0 else clip(q0); pf.wrsel = .{ .q0 = start, .q1 = clip(q0 + take) }; pf.wrsel_by = req.handle; - setDot(p.settings.tab, pane, pf.wrsel); + setFileDot(p.settings.tab, pane, pf.wrsel); return .{ .tag = req.tag, .written = @intCast(take) }; } @@ -796,12 +848,13 @@ pub const e_addr_failed = "no address: the last one written to addr failed"; /// that does not evaluate says why: `bad address syntax`, `no match for /// regexp`, `address out of range`, `bad regular expression`, `addresses /// out of order`. -fn writeRange(tab: u16, req: Req, pane: *Pane, file: PaneFile) Reply { +fn writeRange(p: *Pardes, req: Req, pane: *Pane, file: PaneFile) Reply { + const tab = p.settings.tab; // A terminal, an image or a PDF has no text an address names: refused // alike for addr, dot and limit, before the expression is read. if (fileOf(pane) == null) return tree.failText(req.tag, E.INVAL, e_no_text_address); const pf = &pane.fs; - const text = bodyOf(pane); + const text = bodyOf(p, pane); clampAddr(pf, text.len); const expr = std.mem.trimEnd(u8, req.data, "\n"); // One that goes from the address (`.`, `+`, `-`) has none to go from @@ -842,7 +895,7 @@ fn writeRange(tab: u16, req: Req, pane: *Pane, file: PaneFile) Reply { }, .limit => pf.limit = range, // Setting dot scrolls to it, which is the whole of acme's `show`. - .dot => setDot(tab, pane, range), + .dot => setFileDot(tab, pane, range), else => unreachable, } return .{ .tag = req.tag, .written = @intCast(req.data.len) }; @@ -1011,25 +1064,25 @@ pub fn truncate(p: *Pardes, pane: *Pane, file: PaneFile) tree.Status { .body => if (fileOf(pane) != null) { pf.joined = null; const was = fileOf(pane).?.revision; - _ = spliceBody(p, pane, 0, bodyOf(pane).len, "") orelse return .err; + _ = spliceBody(p, pane, 0, bodyOf(p, pane).len, "") orelse return .err; // An empty body truncated is no edit: the write after it makes // the step, rather than join one that was never pushed. pf.joined = if (fileOf(pane).?.revision != was) fileOf(pane).?.revision else null; pf.joined_by = 0; pf.addr = .{}; - setDot(p.settings.tab, pane, .{}); + setFileDot(p.settings.tab, pane, .{}); }, .data, .xdata => if (fileOf(pane) != null) { - clampAddr(pf, bodyOf(pane).len); + clampAddr(pf, bodyOf(p, pane).len); const q0 = pf.addr.q0; const q1 = @max(q0, pf.addr.q1); - const before = dotOf(pane); + const before = fileDot(pane); pf.joined = null; const was = fileOf(pane).?.revision; _ = spliceBody(p, pane, q0, q1, "") orelse return .err; pf.joined = if (fileOf(pane).?.revision != was) fileOf(pane).?.revision else null; pf.joined_by = 0; - setDot(p.settings.tab, pane, .{ .q0 = shiftOne(before.q0, q0, q1 - q0, 0), .q1 = shiftOne(before.q1, q0, q1 - q0, 0) }); + setFileDot(p.settings.tab, pane, .{ .q0 = shiftOne(before.q0, q0, q1 - q0, 0), .q1 = shiftOne(before.q1, q0, q1 - q0, 0) }); pf.addr = .{ .q0 = q0, .q1 = q0 }; }, // Done with the write after it, which may yet be refused. @@ -1067,7 +1120,7 @@ test "rows through the line index are the ones counting newlines gives, at every const pane = p.panes[0].?; const f = &pane.file.?; _ = try panes.File.lineIndex(p.gpa, f); - const text = bodyOf(pane); + const text = bufferOf(pane); try testing.expect(lineIndex(pane, text) != null); for (0..text.len + 2) |off| { try testing.expectEqual(modal.positionAt(text, off), positionAt(pane, text, off)); diff --git a/core/panes.zig b/core/panes.zig index 4116c3e8..02ee805f 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -31,7 +31,7 @@ pub const Pane = struct { /// it (views.zig). (The 9P server's part of `fs` says so in its type.) pub const replica = .{ .local = .{ "pv", "pv_known" }, - .derived = .{ "wrap_line", "wrap_col", "wrap_pad", "wrap_n", "body_wrapped", "context_rows", "body_rows", "body_visible_rows", "context_row_limit", "geometry_key", "geometry_len", "notices", "pan", "ghosts", "ghost_text" }, + .derived = .{ "wrap_line", "wrap_col", "wrap_pad", "wrap_n", "body_wrapped", "context_rows", "body_rows", "body_visible_rows", "context_row_limit", "geometry_key", "geometry_len", "notices", "pan" }, .len = .{ .{ "msg", "msg_len" }, .{ "msg_older", "msg_older_len" }, .{ "question", "question_len" }, .{ "shell_tail", "shell_tail_len" }, .{ "sel_snap", "nsel_snap" } }, // A picture's memory is its own allocator's (a dump loaded makes // it there). @@ -307,14 +307,6 @@ pub const Pane = struct { wrap_col: [limits.wrap_rows]i32 = undefined, wrap_pad: [limits.wrap_rows]u16 = @splat(0), wrap_n: u16 = 0, - /// The ghost rows of its pinned changes (jj.zig, `Ghost`: lines a - /// change took away, a change's description), the session's answers' - /// (`Pardes.changes`) as its geometry reads them while a view shows - /// them (`layers.lanes`): set by jj.showGhosts. A ghost row's `wrap_col` is - /// negative, `-1 - ` its index here, and its `wrap_line` the line it - /// stands before. - ghosts: []const @import("jj.zig").Ghost = &.{}, - ghost_text: []const u8 = "", /// A row map also exists for sticky headers when soft wrapping is off. body_wrapped: bool = false, context_rows: u16 = 0, @@ -619,13 +611,11 @@ pub const Pane = struct { return @min(pane.scrolled_to orelse output, output); } - /// The line and byte a body row shows from; a ghost row (jj.zig) is no - /// line's: `ghost`, the line below it at its start. - pub fn wrapAt(pane: *Pane, tab: u16, vr: i32) struct { line: i32, at: i32, pad: i32 = 0, ghost: bool = false } { + /// The line and byte a body row shows from. + pub fn wrapAt(pane: *Pane, tab: u16, vr: i32) struct { line: i32, at: i32, pad: i32 = 0 } { File.geometry(tab, pane); if (pane.wrap_n > 0 and vr >= 0 and vr < @as(i32, pane.wrap_n)) { - const at = pane.wrap_col[@intCast(vr)]; - return .{ .line = pane.wrap_line[@intCast(vr)], .at = @max(at, 0), .pad = pane.wrap_pad[@intCast(vr)], .ghost = at < 0 }; + return .{ .line = pane.wrap_line[@intCast(vr)], .at = pane.wrap_col[@intCast(vr)], .pad = pane.wrap_pad[@intCast(vr)] }; } // unwrapped: rows ARE lines, and the byte column a row starts at is the // horizontal scroll (always 0 on a terminal, which never has one) diff --git a/core/root.zig b/core/root.zig index 2f3e4494..a9abee95 100644 --- a/core/root.zig +++ b/core/root.zig @@ -750,7 +750,6 @@ const kept_out = [_]struct { []const u8, []const u8, []const u8 }{ .{ "Event.zig", "native_image_patches", "what this process's shell can take" }, .{ "panes.zig", "pv pv_known", "the views' shares as this process parks them (views.zig)" }, .{ "panes.zig", "wrap_line wrap_col wrap_pad wrap_n body_wrapped context_rows body_rows body_visible_rows context_row_limit geometry_key geometry_len", "File.geometry's, made by whoever asks first (a frame or a step) from everything its key hashes of the step's state; a tab change resets the key" }, - .{ "panes.zig", "ghosts ghost_text", "the session's `Changes` answers' ghost rows (Pardes.changes, in the digest) as the geometry reads them: set by jj.showGhosts in each step while a view shows them and as an answer lands, which resets the geometry's key" }, .{ "panes.zig views.zig", "notices", "made again from the step's state at the top of update and presented, and at sync (Messages.collectNotices); a frame's are its own" }, .{ "panes.zig views.zig", "pan", "written by steps only (sync, a view unparked) from the pane and its terminal" }, .{ "File.zig", "cap line_starts line_cap", "the text's line index, of its bytes" }, diff --git a/dev/Lsp.zig b/dev/Lsp.zig index 4b8bfa03..b799c9f6 100644 --- a/dev/Lsp.zig +++ b/dev/Lsp.zig @@ -43,6 +43,14 @@ pub const Job = struct { } }; +/// A pane's file's text, `0`-ended, owned. +fn fileSource(gpa: std.mem.Allocator, f: ?*const pardes.panes.File.State) ![:0]u8 { + const file = f orelse return gpa.dupeSentinel(u8, "", 0); + const text = try pardes.panes.File.fileText(file, gpa); + defer if (text.ptr != file.content.ptr) gpa.free(text); + return gpa.dupeSentinel(u8, text, 0); +} + // Copy before starting a worker; the editor may replace any source slice afterward. pub fn snapshot(gpa: std.mem.Allocator, core: *const pardes.Pardes, req: Request) !*Job { if (req.pane.index() >= core.panes.len) return error.NoPane; @@ -53,7 +61,9 @@ pub fn snapshot(gpa: std.mem.Allocator, core: *const pardes.Pardes, req: Request const declared_path = if (file) |f| f.path else ""; const path = try gpa.dupe(u8, filesystem.localPath(declared_path) orelse declared_path); errdefer gpa.free(path); - const source = try gpa.dupeSentinel(u8, if (file) |f| f.content else "", 0); + // The file's text (File.fileText: the `Changes` layer's lines are none + // of it), as every position sent with it is. + const source = try fileSource(gpa, if (file) |*f| f else null); errdefer gpa.free(source); const arg = try gpa.dupe(u8, req.arg); errdefer gpa.free(arg); @@ -94,7 +104,7 @@ pub fn snapshot(gpa: std.mem.Allocator, core: *const pardes.Pardes, req: Request copied += f.content.len; const local = filesystem.localPath(f.path) orelse continue; const other_path = try gpa.dupe(u8, local); - const other_source = gpa.dupeSentinel(u8, f.content, 0) catch |err| { + const other_source = fileSource(gpa, &f) catch |err| { gpa.free(other_path); return err; }; diff --git a/dev/file_watch.zig b/dev/file_watch.zig index a0a500d7..d97e1d3d 100644 --- a/dev/file_watch.zig +++ b/dev/file_watch.zig @@ -471,7 +471,7 @@ pub fn reloadPane( } // The pane holds the disk's text already (a Zerox twin saved, its // other twin watching the same file): nothing reloaded, nothing said. - if (std.mem.eql(u8, file.content, bytes)) { + if (pardes.panes.File.fileEql(&file, bytes)) { if (watches[id]) |*live| if (live.serial == watched.serial) { live.generation = .{ .text = hash }; }; @@ -481,7 +481,7 @@ pub fn reloadPane( const current = core.panes[id] orelse return false; if (current.serial != watched.serial) return false; const current_file = current.file orelse return false; - if (!std.mem.eql(u8, current_file.content, bytes)) return false; + if (!pardes.panes.File.fileEql(¤t_file, bytes)) return false; if (watches[id]) |*live| { if (live.serial == watched.serial) live.generation = .{ .text = hash }; @@ -545,7 +545,7 @@ pub fn applyEffect( serial = pane.serial; if (pane.file) |file| { path = file.path; - generation = .{ .text = std.hash.Wyhash.hash(0, file.content) }; + generation = .{ .text = pardes.panes.File.fileHash(&file) }; } else if (kindPath(pane)) |kind_path| { path = kind_path; generation = .{ .kind = null }; diff --git a/test/daemon.py b/test/daemon.py index f456837b..9522153d 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -328,7 +328,7 @@ class Replica: """A replica's connection (abi/wire.zig): length-prefixed messages, a tag byte and a little-endian u32 length. It is a near client: its first word after the hello says so.""" - WIRE = 31 + WIRE = 34 def __init__(self, path, timeout=10): self.path, self.timeout = path, timeout |
