diff options
Diffstat (limited to 'src/doc.zig')
| -rw-r--r-- | src/doc.zig | 481 |
1 files changed, 426 insertions, 55 deletions
diff --git a/src/doc.zig b/src/doc.zig index 2320a6a..1964159 100644 --- a/src/doc.zig +++ b/src/doc.zig @@ -160,12 +160,19 @@ pub fn suggestion(line: []const u8) ?[]const u8 { // --- The file ------------------------------------------------------------------------------- // -// v2 puts optional Overflow and write_away comments before the visible Markdown. One LF +// v3 puts optional Overflow and write_away comments before the visible Markdown. One LF // separates the comments when both are present; two LFs separate the last comment from // the exact visible bytes. YAML frontmatter is those bytes' one exception: it stays on the // file's first line and the comments follow it. Legacy comments were trailers. Offsets -// always address the full editor body, so v2 ghosts must be restored before the -// alternatives are reanchored. +// always address the full editor body, so ghosts must be restored before the alternatives +// are reanchored. +// +// The file may have been edited elsewhere. A ghost's text is not among the visible bytes, so +// it is found by the text that was on either side of it: see `Near`. One with no clear +// place goes to Overflow and is a ghost no more. v2 had only the offsets, and a digest of the +// visible bytes to say whether they still held. A group's showing +// version is there to be found, but may be there twice, so its surroundings tell it apart in +// the same way. One with no clear place is dropped. const overflow_mark = "<!-- overflow -->"; // legacy const overflow_open = "<!-- overflow\n("; @@ -177,10 +184,104 @@ const Sha256 = std.crypto.hash.sha2.Sha256; pub const GroupRec = struct { scope: Scope = .word, at: usize, active: usize = 0, variants: []const []const u8, ai: ?[]const []const u8 = null }; pub const GhostRec = struct { at: usize, text: []const u8 }; +const around = 32; // how many bytes of the text on either side of a ghost or a group are kept with it +const enough = 12; // and the fewest, blanks aside, that can place a ghost without the other side's + +/// What is around something, to find it by when the file has been edited elsewhere. If some of +/// that was in the text twice, an edit to the right copy would leave the wrong one the only +/// match. So with it goes the least of each side that made this the only one, or null if all +/// of it did not, and whether the two together did. +const Near = struct { + before: []const u8 = "", + after: []const u8 = "", + alone: [2]?usize = .{ null, null }, + together: bool = false, + + /// Around the `len` bytes at `at`. A ghost's text is not in `bytes`, so it has none. + fn of(bytes: []const u8, at: usize, len: usize) Near { + const stop = at + len; + var lo = at -| around; + while (lo < at and bytes[lo] & 0xc0 == 0x80) lo += 1; + var hi = @min(bytes.len, stop + around); + while (hi > stop and hi < bytes.len and bytes[hi] & 0xc0 == 0x80) hi -= 1; + var near: Near = .{ .before = bytes[lo..at], .after = bytes[stop..hi] }; + const whole = bytes[lo..hi]; + near.together = whole.len != 0 and only(bytes, whole) != null; + for (&near.alone, [_]usize{ near.before.len, near.after.len }, 0..) |*least, most, side| { + least.* = for (0..most + 1) |n| { + const part = near.piece(whole, side, n); + if (len == 0 and mem.trim(u8, part, " \t\r\n").len < enough) continue; + if (only(bytes, part) != null) break n; + } else null; + } + return near; + } + + fn from(saved: anytype) Near { + return .{ .before = saved.before, .after = saved.after, .alone = saved.alone, .together = saved.together }; + } + + /// Saved before this was. + fn unknown(near: Near) bool { + return near.before.len + near.after.len == 0 and !near.together; + } + + /// Of `whole`, which is everything around with what it is around in the middle: the middle, + /// and the `n` bytes nearest it on one side. + fn piece(near: Near, whole: []const u8, side: usize, n: usize) []const u8 { + const stop = whole.len - near.after.len; + return if (side == 0) whole[near.before.len - n .. stop] else whole[near.before.len .. stop + n]; + } + + /// Where `text` (a ghost's is "") belongs in `bytes`: where it was, if both sides are still + /// there, or else the one place that has both. Failing that, where one side leads. + fn find(near: Near, arena: Allocator, bytes: []const u8, was: ?usize, text: []const u8) !?usize { + const whole = try mem.concat(arena, u8, &.{ near.before, text, near.after }); + if (whole.len == 0) return if (bytes.len == 0) 0 else null; + if (was) |at| if (at >= near.before.len and at <= bytes.len and mem.startsWith(u8, bytes[at - near.before.len ..], whole)) return at; + if (near.together) if (only(bytes, whole)) |at| return at + near.before.len; + + // As much of a side as is still somewhere, down to what was the only one. + var spots: [2]?usize = .{ null, null }; + var found: [2]usize = .{ 0, 0 }; + for (near.alone, [_]usize{ near.before.len, near.after.len }, 0..) |alone, most, side| { + const least = alone orelse continue; + if (least == 0 and text.len == 0) continue; + for (0..(most + 1) -| least) |cut| { + const part = near.piece(whole, side, most - cut); + if (mem.find(u8, bytes, part) == null) continue; + found[side] = most - cut; + if (only(bytes, part)) |at| spots[side] = if (side == 0) at + found[0] else at; + break; + } + } + const left = spots[0] orelse return spots[1]; + const right = spots[1] orelse return left; + if (left == right) return left; + if (text.len == 0) { + // New text may have come between the two, but not if they have changed order. + return if (left > right) null else if (found[1] > found[0]) right else left; + } + return if (found[0] == found[1]) null else if (found[1] > found[0]) right else left; + } +}; + +const SavedGhost = struct { at: usize, text: []const u8, before: []const u8 = "", after: []const u8 = "", alone: [2]?usize = .{ null, null }, together: bool = false }; +const SavedGroup = struct { + scope: Scope = .word, + at: usize, + active: usize = 0, + variants: []const []const u8, + ai: ?[]const []const u8 = null, + before: []const u8 = "", + after: []const u8 = "", + alone: [2]?usize = .{ null, null }, + together: bool = false, +}; const Meta = struct { v: u32 = 1, - groups: []const GroupRec = &.{}, - ghosts: []const GhostRec = &.{}, + groups: []const SavedGroup = &.{}, + ghosts: []const SavedGhost = &.{}, visible_sha256: ?[Sha256.digest_length * 2]u8 = null, }; @@ -189,6 +290,7 @@ pub const File = struct { overflow: []const u8 = "", groups: []const GroupRec = &.{}, ghosts: []const GhostRec = &.{}, + displaced: bool = false, // a ghost had no clear place, and is in Overflow: the file does not say so yet }; pub fn serialize(gpa: Allocator, f: File) ![]u8 { @@ -217,11 +319,27 @@ pub fn serialize(gpa: Allocator, f: File) ![]u8 { if (has_meta) try out.append(gpa, '\n'); } if (has_meta) { + const ghosts = try gpa.alloc(SavedGhost, f.ghosts.len); + defer gpa.free(ghosts); + var removed: usize = 0; + for (f.ghosts, ghosts) |g, *saved| { + const near: Near = .of(visible, g.at - removed, 0); + removed += g.text.len; + saved.* = .{ .at = g.at, .text = g.text, .before = near.before, .after = near.after, .alone = near.alone, .together = near.together }; + } + // A group's surroundings are the whole body's: a ghost it is in or beside is found first. + const groups = try gpa.alloc(SavedGroup, f.groups.len); + defer gpa.free(groups); + for (f.groups, groups) |g, *saved| { + const text = g.variants[g.active]; + const there = g.at <= f.body.len and mem.startsWith(u8, f.body[g.at..], text); + const near: Near = if (there) .of(f.body, g.at, text.len) else .{}; + saved.* = .{ .scope = g.scope, .at = g.at, .active = g.active, .variants = g.variants, .ai = g.ai, .before = near.before, .after = near.after, .alone = near.alone, .together = near.together }; + } const json = try std.json.Stringify.valueAlloc(gpa, Meta{ - .v = 2, - .groups = f.groups, - .ghosts = f.ghosts, - .visible_sha256 = if (f.ghosts.len != 0) digest(visible) else null, + .v = 3, + .groups = groups, + .ghosts = ghosts, }, .{ .emit_null_optional_fields = false }); defer gpa.free(json); try out.appendSlice(gpa, meta_open); @@ -251,6 +369,16 @@ pub fn frontmatter(bytes: []const u8) usize { return 0; } +/// `body` with blanks for its comments: every other byte, and every line, where it was. +pub fn withoutComments(gpa: Allocator, body: []const u8) ![]u8 { + const prose = try gpa.dupe(u8, body); + var it: markdown.Comments(u8) = .{ .text = body, .front = frontmatter(body) != 0 }; + while (it.next()) |c| for (prose[c.lo..c.hi]) |*b| { + if (b.* != '\n' and b.* != '\r') b.* = ' '; + }; + return prose; +} + fn digest(bytes: []const u8) [Sha256.digest_length * 2]u8 { var hash: [Sha256.digest_length]u8 = undefined; Sha256.hash(bytes, &hash, .{}); @@ -280,27 +408,85 @@ pub fn parse(arena: Allocator, bytes: []const u8) !File { const block = splitComment(rest, meta_open, meta_close) orelse return unchanged; const meta = (try readMeta(arena, block.payload, false)) orelse return unchanged; if (meta.v == 1 and overflow == null) return parseLegacy(arena, bytes); - if (meta.v != 2 or !mem.startsWith(u8, block.rest, framing)) return unchanged; - if ((meta.ghosts.len != 0) != (meta.visible_sha256 != null)) return unchanged; + if ((meta.v != 2 and meta.v != 3) or !mem.startsWith(u8, block.rest, framing)) return unchanged; + if ((meta.v == 2 and meta.ghosts.len != 0) != (meta.visible_sha256 != null)) return unchanged; const visible = try mem.concat(arena, u8, &.{ head, block.rest[framing.len..] }); - const body = if (meta.ghosts.len == 0) visible else body: { - const expected = meta.visible_sha256 orelse return unchanged; - if (!mem.eql(u8, &expected, &digest(visible))) return unchanged; - break :body ghost_io.restore(arena, visible, meta.ghosts) catch |err| switch (err) { - error.OutOfMemory => return err, - else => return unchanged, - }; + const moves = try arena.alloc(Move, meta.ghosts.len); + const ghosts = try placeGhosts(arena, visible, meta, moves); + const body = ghost_io.restore(arena, visible, ghosts) catch |err| switch (err) { + error.OutOfMemory => return err, + else => return unchanged, }; - const groups = (try reanchorGroups(arena, body, meta.groups)) orelse return unchanged; + var stowed: std.ArrayList(u8) = .empty; + if (overflow) |encoded| try stowed.appendSlice(arena, try decodeOverflow(arena, encoded)); + for (moves) |m| if (m.to == null) try stow(arena, &stowed, m.was.text); + const groups = (try placeGroups(arena, body, meta.groups, moves)) orelse return unchanged; return .{ .body = body, - .overflow = if (overflow) |encoded| try decodeOverflow(arena, encoded) else "", .groups = groups, - .ghosts = meta.ghosts, + .ghosts = ghosts, + .displaced = ghosts.len != moves.len, + .overflow = stowed.items, }; } +/// Where a ghost was in the body, and where it is now, if it has a place there. +const Move = struct { was: GhostRec, to: ?usize = null }; + +/// The ghosts that have a place, as `ghost_io.restore` wants them. Fills in `moves`. +fn placeGhosts(arena: Allocator, visible: []const u8, meta: Meta, moves: []Move) ![]const GhostRec { + const trusted = if (meta.visible_sha256) |sum| mem.eql(u8, &sum, &digest(visible)) else false; + const Spot = struct { + at: usize, // among the visible bytes + move: *Move, + + fn lessThan(_: void, a: @This(), b: @This()) bool { + return a.at < b.at; + } + }; + var spots: std.ArrayList(Spot) = .empty; + var removed: usize = 0; + for (meta.ghosts, moves) |g, *m| { + m.* = .{ .was = .{ .at = g.at, .text = g.text } }; + const was = if (g.at >= removed) g.at - removed else null; + removed +|= g.text.len; + const at = (if (trusted) was else try Near.from(g).find(arena, visible, was, "")) orelse continue; + const inside = at < visible.len and visible[at] & 0xc0 == 0x80; // a character + if (g.text.len == 0 or at > visible.len or inside) continue; + try spots.append(arena, .{ .at = at, .move = m }); + } + mem.sort(Spot, spots.items, {}, Spot.lessThan); // stable: ghosts side by side stay in order + const ghosts = try arena.alloc(GhostRec, spots.items.len); + removed = 0; + for (spots.items, ghosts) |spot, *g| { + g.* = .{ .at = spot.at + removed, .text = spot.move.was.text }; + spot.move.to = g.at; + removed += g.text.len; + } + return ghosts; +} + +/// Where `text` is, if it is in one place. +fn only(bytes: []const u8, text: []const u8) ?usize { + if (text.len == 0) return null; + const first = mem.find(u8, bytes, text) orelse return null; + return if (mem.find(u8, bytes[first + 1 ..], text) == null) first else null; +} + +fn stow(arena: Allocator, overflow: *std.ArrayList(u8), text: []const u8) !void { + const entry = mem.trim(u8, text, "\r\n"); + if (blank(entry)) return; + try overflow.appendSlice(arena, overflowGap(overflow.items)); + try overflow.appendSlice(arena, entry); +} + +/// What goes between what Overflow has and the next thing put in it. +pub fn overflowGap(have: []const u8) []const u8 { + if (have.len == 0 or mem.endsWith(u8, have, "\n\n")) return ""; + return if (have[have.len - 1] == '\n') "\n" else "\n\n"; +} + const Comment = struct { payload: []const u8, rest: []const u8 }; // Only unescaped comment delimiters may frame a block, never interrupt its payload. @@ -401,7 +587,7 @@ fn parseLegacy(arena: Allocator, bytes: []const u8) !File { if (f.body.len == bytes.len) return unchanged; // Legacy trailers did not distinguish body line endings from their separators. f.body = mem.trimEnd(u8, f.body, "\r\n"); - f.groups = (try reanchorGroups(arena, f.body, meta.groups)) orelse return unchanged; + f.groups = (try placeGroups(arena, f.body, meta.groups, &.{})) orelse return unchanged; var ghosts: std.ArrayList(GhostRec) = .empty; for (meta.ghosts) |g| { const at = anchor(f.body, g.at, g.text) orelse return unchanged; @@ -426,22 +612,55 @@ fn validGroup(g: GroupRec) bool { return g.variants.len >= 2 and g.active < g.variants.len; } -fn reanchorGroups(arena: Allocator, body: []const u8, records: []const GroupRec) !?[]const GroupRec { - const groups = try arena.alloc(GroupRec, records.len); - for (records, groups) |g, *kept| { - if (!validGroup(g)) return null; - kept.* = g; - kept.at = anchor(body, g.at, g.variants[g.active]) orelse return null; +/// The groups that have a place in the body. Any other is let go: what it was about has been +/// settled elsewhere. Null if one makes no sense. +fn placeGroups(arena: Allocator, body: []const u8, records: []const SavedGroup, moves: []const Move) !?[]const GroupRec { + var groups: std.ArrayList(GroupRec) = .empty; + var origins: std.ArrayList(usize) = .empty; // where each of those was + for (records) |g| { + var rec: GroupRec = .{ .scope = g.scope, .at = g.at, .active = g.active, .variants = g.variants, .ai = g.ai }; + if (!validGroup(rec)) return null; + const text = g.variants[g.active]; + var spot = try groupSpot(arena, body, g, moves); + // Two that stood apart must not end up on the same text. + if (spot) |at| for (groups.items, origins.items) |other, origin| { + const n = other.variants[other.active].len; + if (overlaps(at, text.len, other.at, n) and !overlaps(g.at, text.len, origin, n)) spot = null; + }; + rec.at = spot orelse continue; + try groups.append(arena, rec); + try origins.append(arena, g.at); + } + return groups.items; +} + +fn groupSpot(arena: Allocator, body: []const u8, g: SavedGroup, moves: []const Move) !?usize { + const text = g.variants[g.active]; + if (text.len == 0) return null; + var was = g.at; + for (moves) |m| { + const shared = overlaps(g.at, text.len, m.was.at, m.was.text.len); + if (m.to) |to| { + if (!shared or g.at < m.was.at) continue; + const at = to + (g.at - m.was.at); // it goes where the ghost it starts in goes + if (mem.startsWith(u8, body[at..], text)) return at; + } else if (shared) { + return null; // some of its text is in Overflow + } else if (m.was.at < g.at) was -|= m.was.text.len; } - return groups; + const near: Near = .from(g); + return if (near.unknown()) anchor(body, was, text) else near.find(arena, body, was, text); +} + +fn overlaps(a: usize, a_len: usize, b: usize, b_len: usize) bool { + return a < b +| b_len and b < a +| a_len; } /// Trust a matching offset even when repeated; a stale offset needs one unique match. fn anchor(body: []const u8, at: usize, text: []const u8) ?usize { if (text.len == 0) return null; if (at <= body.len and mem.startsWith(u8, body[at..], text)) return at; - const first = mem.find(u8, body, text) orelse return null; - return if (mem.find(u8, body[first + 1 ..], text) == null) first else null; + return only(body, text); } // --- Text helpers --------------------------------------------------------------------------- @@ -544,7 +763,7 @@ test "hidden overflow preserves bytes and malformed blocks" { "<!-- overflow\n(a --!> leaked)-->\n\nBody\n", "<!-- overflow\n(stash)-->\n<!-- write_away {nope -->\n\nBody\n", "<!-- overflow\n(stash)-->\n<!-- write_away {\"v\":2,\"ghsts\":[]} -->\n\nBody\n", - "<!-- overflow\n(stash)-->\n<!-- write_away {\"v\":3} -->\n\nBody\n", + "<!-- overflow\n(stash)-->\n<!-- write_away {\"v\":4} -->\n\nBody\n", "Body\n\n<!-- overflow\n(stash)-->\n\n<!-- write_away {\"v\":3} -->\n", "Text.\n\n<!-- write_away {nope -->\n", }) |bad| { @@ -603,7 +822,7 @@ test "v1 ghosts require an exact or unique anchor" { try t.expectEqual(4, exact.ghosts[0].at); } -test "v1 and v2 groups preserve all raw metadata if any record cannot be anchored" { +test "groups without surroundings need an exact or unique anchor, or are dropped" { const t = std.testing; var state: std.heap.ArenaAllocator = .init(t.allocator); defer state.deinit(); @@ -615,9 +834,20 @@ test "v1 and v2 groups preserve all raw metadata if any record cannot be anchore "{\"at\":0,\"variants\":[\"ana\",\"other\"]}", // Two overlapping matches. "{\"at\":5,\"variants\":[\"ana\"]}", // Not a persistent group. "{\"at\":5,\"variants\":[\"ana\",\"other\"],\"active\":2}", - }) |bad| { - try expectRaw(a, try mem.concat(a, u8, &.{ body, "\n\n<!-- overflow -->\nNotes\n", meta_open, "{\"v\":1,", first_group, bad, "]}", meta_close })); - try expectRaw(a, try mem.concat(a, u8, &.{ "<!-- overflow\n(Notes)-->\n", meta_open, "{\"v\":2,", first_group, bad, "]}", meta_close, framing, body })); + }, [_]bool{ true, true, false, false }) |bad, sensible| { + for ([_][]const u8{ + try mem.concat(a, u8, &.{ body, "\n\n<!-- overflow -->\nNotes\n", meta_open, "{\"v\":1,", first_group, bad, "]}", meta_close }), + try mem.concat(a, u8, &.{ "<!-- overflow\n(Notes)-->\n", meta_open, "{\"v\":2,", first_group, bad, "]}", meta_close, framing, body }), + }) |bytes| { + if (!sensible) { // not something an edit elsewhere could do + try expectRaw(a, bytes); + continue; + } + const f = try parse(a, bytes); + try t.expectEqualStrings(body, f.body); + try t.expectEqualStrings("Notes", f.overflow); + try t.expect(f.groups.len == 1 and !f.displaced); + } } const record = "{\"at\":5,\"variants\":[\"ana\",\"other\"]}]"; @@ -630,7 +860,7 @@ test "v1 and v2 groups preserve all raw metadata if any record cannot be anchore } } -test "v2 hides ghosts and rejects edits or invalid ghost positions without losing the source" { +test "ghosts are hidden, and found again after edits elsewhere or left in Overflow" { const t = std.testing; var arena_state: std.heap.ArenaAllocator = .init(t.allocator); defer arena_state.deinit(); @@ -646,7 +876,7 @@ test "v2 hides ghosts and rejects edits or invalid ghost positions without losin }; const bytes = try serialize(arena, file); const overflow = splitComment(bytes, overflow_open, overflow_close).?; - try t.expect(mem.startsWith(u8, overflow.rest, "\n" ++ meta_open ++ "{\"v\":2,")); + try t.expect(mem.startsWith(u8, overflow.rest, "\n" ++ meta_open ++ "{\"v\":3,")); const block = splitComment(overflow.rest[1..], meta_open, meta_close).?; try t.expectEqualStrings("\n\n# Title\n\nThe tension is real. ", block.rest); try t.expect(mem.find(u8, bytes, "a -->") == null); @@ -657,24 +887,117 @@ test "v2 hides ghosts and rejects edits or invalid ghost positions without losin try t.expectEqualStrings("a --> b", back.groups[0].variants[2]); try t.expectEqual(30, back.ghosts[0].at); - // Even a same-length edit with all offsets still valid cannot relocate a ghost. - for ([_][]const u8{ - try mem.replaceOwned(u8, arena, bytes, "# Title", "# A Longer Title"), - try mem.replaceOwned(u8, arena, bytes, "# Title", "# Other"), - try mem.concat(arena, u8, &.{ bytes, "\n" }), - try mem.replaceOwned(u8, arena, bytes, "\"at\":30", "\"at\":3000"), - "<!-- write_away {\"v\":2,\"ghosts\":[{\"at\":0,\"text\":\"ghost\"}]} -->\n\nBody", - }) |edited| { - const f = try parse(arena, edited); - try t.expectEqualStrings(edited, f.body); - try t.expectEqual(0, f.ghosts.len); - try t.expectEqual(0, f.groups.len); - try t.expectEqualStrings("", f.overflow); - try t.expectEqualStrings(edited, try serialize(arena, f)); + try t.expect(!back.displaced); + try t.expectEqualStrings(bytes, try serialize(arena, back)); + // A ghost with no text around it on record, and nothing to vouch for its offset. + try expectRaw(arena, "<!-- write_away {\"v\":2,\"ghosts\":[{\"at\":0,\"text\":\"ghost\"}]} -->\n\nBody"); + + // [was] is a ghost, and <word> a group. What the visible text became, and how that opens. + const cases = [_][3][]const u8{ + // Edits before it, after it, and on one side right up against it. + .{ "# Title\n\nThe tension is real.[ Maybe cut this.]", "# A longer title\n\nThe tension is real.", "# A longer title\n\nThe tension is real.[ Maybe cut this.]" }, + .{ "# Title\n\nThe tension is real.[ Maybe cut this.]", "# Title\n\nThe tension is real. And more.", "# Title\n\nThe tension is real.[ Maybe cut this.] And more." }, + .{ "One thing. [Cut. ]The rest of it goes on from there.", "Changed! The rest of it goes on from there.", "Changed! [Cut. ]The rest of it goes on from there." }, + // New text at the very spot stands after it. + .{ "The tension is real.[ Cut.] The rest goes on.", "The tension is real. New. The rest goes on.", "The tension is real.[ Cut.] New. The rest goes on." }, + // The same text twice: only an offset that still holds can tell which. + .{ "Same line here.\nSame line here.[ Cut.]\nSame line here.\n", "Same line here.\nSame line here.\nSame line here.\n", "Same line here.\nSame line here.[ Cut.]\nSame line here.\n" }, + .{ "echo echo echo [Cut]echo echo echo echo", "echo echo echo echo echo echo echo echo", "echo echo echo [Cut]echo echo echo echo echo" }, + .{ "a\nA line.\nA line.[ Cut.]\nA line.\nA line.\nA line.\nA line.\nA line.\n", "abc\nA line.\nA line.\nA line.\nA line.\nA line.\nA line.\nA line.\n", "abc\nA line.\nA line.\nA line.\nA line.\nA line.\nA line.\nA line.\n| Cut." }, + // Both sides rewritten, or changed about. + .{ "The tension is real.[ Cut.] And so on.", "Nothing like it.", "Nothing like it.| Cut." }, + .{ "First this came.[ Cut.]Then that went.", "Then that went. First this came.", "Then that went. First this came.| Cut." }, + .{ "[All of it.]", "New.", "New.|All of it." }, + // Each goes its own way, and those side by side stay in order. UTF-8 is kept whole. + .{ "終終終終終終終終終終終終é[👻][ a]é終終終終終終終終終終終終. Then [gone]. The end is near now.", "New 終終終終終終終終終終終終éé終終終終終終終終終終終終.", "New 終終終終終終終終終終終終é[👻][ a]é終終終終終終終終終終終終.|gone" }, + // They follow their text past one another. + .{ "First paragraph is here.[ One.]\n\nSecond paragraph follows.[ Two.]\n\nThird.", "Second paragraph follows.\n\nFirst paragraph is here.\n\nThird.", "Second paragraph follows.[ Two.]\n\nFirst paragraph is here.[ One.]\n\nThird." }, + }; + for (cases) |c| { + const saved = try serialize(arena, try bracketed(arena, c[0])); + const visible = splitComment(saved, meta_open, meta_close).?.rest; + const f = try parse(arena, try mem.concat(arena, u8, &.{ saved[0 .. saved.len - visible.len], framing, c[1] })); + var want = mem.splitScalar(u8, c[2], '|'); + const opened = try bracketed(arena, want.first()); + try t.expectEqualStrings(opened.body, f.body); + try t.expectEqualStrings(want.next() orelse "", f.overflow); + try t.expectEqual(f.overflow.len != 0, f.displaced); + try t.expectEqual(opened.ghosts.len, f.ghosts.len); + for (opened.ghosts, f.ghosts) |a, b| { + try t.expectEqual(a.at, b.at); + try t.expectEqualStrings(a.text, b.text); + } + // What is saved next opens the same, with nothing left to place. + const again = try parse(arena, try serialize(arena, f)); + try t.expectEqualStrings(f.body, again.body); + try t.expectEqualStrings(f.overflow, again.overflow); + try t.expectEqual(f.ghosts.len, again.ghosts.len); + try t.expect(!again.displaced); } + + // Text already in Overflow stays first. Once there, a ghost does not come back with its place. + const gone = try parse(arena, try mem.replaceOwned(u8, arena, bytes, "\n\nThe tension is real. ", "\n\nNo tension at all.")); + try t.expectEqualStrings("Kept for later.\n\nMaybe cut this.", gone.overflow); + try t.expectEqual(1, gone.groups.len); + const stowed = try mem.replaceOwned(u8, arena, try serialize(arena, gone), "\n\nNo tension at all.", "\n\nThe tension is real. "); + const back_again = try parse(arena, stowed); + try t.expectEqualStrings("Kept for later.\n\nMaybe cut this.", back_again.overflow); + try t.expectEqual(0, back_again.ghosts.len); } -test "v2 restores adjacent UTF-8 ghosts and overlapping groups after an editor edit" { +/// A file whose ghosts are the bracketed parts of `text`. +fn bracketed(arena: Allocator, text: []const u8) !File { + var body: std.ArrayList(u8) = .empty; + var ghosts: std.ArrayList(GhostRec) = .empty; + var parts = mem.splitScalar(u8, text, '['); + try body.appendSlice(arena, parts.first()); + while (parts.next()) |part| { + const close = mem.findScalar(u8, part, ']').?; + try ghosts.append(arena, .{ .at = body.items.len, .text = part[0..close] }); + try body.appendSlice(arena, part[0..close]); + try body.appendSlice(arena, part[close + 1 ..]); + } + return .{ .body = body.items, .ghosts = ghosts.items }; +} + +test "alternatives go where their ghost goes" { + const t = std.testing; + var state: std.heap.ArenaAllocator = .init(t.allocator); + defer state.deinit(); + const a = state.allocator(); + const group: GroupRec = .{ .at = 5, .variants = &.{ "echo", "other" }, .ai = &.{"other"} }; + const saved = try serialize(a, .{ .body = "echo echo and then the end.", .groups = &.{group}, .ghosts = &.{.{ .at = 5, .text = "echo" }} }); + // The first "echo" reads the same, but it is not the one. + const moved = try parse(a, try mem.replaceOwned(u8, a, saved, "\n\necho and", "\n\nAn echo and")); + try t.expectEqualStrings("An echo echo and then the end.", moved.body); + try t.expectEqual(8, moved.groups[0].at); + const lost = try parse(a, try mem.replaceOwned(u8, a, saved, "\n\necho and then the end.", "\n\necho only")); + try t.expectEqualStrings("echo only", lost.body); + try t.expectEqual(0, lost.groups.len); + try t.expectEqualStrings("echo", lost.overflow); +} + +test "v2 offsets hold while the visible bytes do; after that its ghosts are in Overflow" { + const t = std.testing; + var state: std.heap.ArenaAllocator = .init(t.allocator); + defer state.deinit(); + const a = state.allocator(); + const visible = "# A draft\n\nThe tension is real.\n"; + for ([_]usize{ 31, 3000 }, [_][]const u8{ "# A draft\n\nThe tension is real. Cut this.\n", visible }, [_][]const u8{ "", " Cut this." }) |at, body, over| { + const old = try mem.concat(a, u8, &.{ try std.fmt.allocPrint(a, "{s}{{\"v\":2,\"groups\":[{{\"at\":15,\"variants\":[\"tension\",\"strain\"]}}],\"ghosts\":[{{\"at\":{d},\"text\":\" Cut this.\"}}],\"visible_sha256\":\"{s}\"}}{s}", .{ meta_open, at, &digest(visible), meta_close }), framing, visible }); + const f = try parse(a, old); + try t.expectEqualStrings(body, f.body); + try t.expectEqualStrings(over, f.overflow); + try t.expectEqual(1, f.groups.len); + const edited = try parse(a, try mem.replaceOwned(u8, a, old, "# A draft", "# My draft")); + try t.expectEqualStrings("# My draft\n\nThe tension is real.\n", edited.body); + try t.expectEqualStrings(" Cut this.", edited.overflow); + try t.expectEqual(16, edited.groups[0].at); + try t.expect(edited.displaced); + } +} + +test "restores adjacent UTF-8 ghosts and overlapping groups after an editor edit" { const t = std.testing; var state: std.heap.ArenaAllocator = .init(t.allocator); defer state.deinit(); @@ -803,8 +1126,56 @@ test "plain Markdown is byte-exact; v1 ghosts and ghost-free v2 groups still fol const moved = try parse(a, edited); try t.expectEqualStrings("Some tension is real.\r\n\n", moved.body); try t.expectEqual(5, moved.groups[0].at); - const gone = try mem.replaceOwned(u8, a, no_ghosts, "The tension is", "The strain is"); - try expectRaw(a, gone); + const gone = try parse(a, try mem.replaceOwned(u8, a, no_ghosts, "\n\nThe tension is", "\n\nThe strain is")); + try t.expectEqualStrings("The strain is real.\r\n\n", gone.body); + try t.expect(gone.groups.len == 0 and gone.overflow.len == 0 and !gone.displaced); + try t.expectEqualStrings(gone.body, try serialize(a, gone)); +} + +test "a group on a word that is there twice keeps its own, or is dropped" { + const t = std.testing; + var state: std.heap.ArenaAllocator = .init(t.allocator); + defer state.deinit(); + const a = state.allocator(); + // <word> is a group with "other". What the text became, and how that opens. + const cases = [_][3][]const u8{ + .{ "The end of the story is the <end>.", "So, the end of the story is the end.", "So, the end of the story is the <end>." }, + .{ "The <end> of the story is the end.", "So, the end of the tale is the end.", "So, the <end> of the tale is the end." }, + .{ "The <end> of the story is the end.", "At the end of a story comes the end.", "At the <end> of a story comes the end." }, + // Its own was rewritten, and the other is not it. + .{ "The <end> of the story is the end.", "The close of the story is the end.", "The close of the story is the end." }, + .{ "One <tension> here.", "One more tension there, and a tension here.", "One more tension there, and a <tension> here." }, + .{ "<All of it.>", "More. All of it.", "More. <All of it.>" }, + .{ "<All of it.>", "None.", "None." }, + }; + for (cases) |c| { + const saved = try serialize(a, try angled(a, c[0])); + const was = splitComment(saved, meta_open, meta_close).?.rest; + const f = try parse(a, try mem.concat(a, u8, &.{ saved[0 .. saved.len - was.len], framing, c[1] })); + const want = try angled(a, c[2]); + try t.expectEqualStrings(want.body, f.body); + try t.expectEqual(want.groups.len, f.groups.len); + for (want.groups, f.groups) |x, y| try t.expectEqual(x.at, y.at); + try t.expect(f.overflow.len == 0 and !f.displaced); + } + + // Two on the same word, one of which is gone, do not share the other. + const two = try serialize(a, .{ .body = "echo echo", .groups = &.{ + .{ .at = 0, .variants = &.{ "echo", "first" } }, + .{ .at = 5, .variants = &.{ "echo", "second" } }, + } }); + const f = try parse(a, try mem.replaceOwned(u8, a, two, "\n\necho echo", "\n\necho")); + try t.expect(f.groups.len < 2); +} + +/// A file in which the part of `text` in angle brackets is a group. +fn angled(arena: Allocator, text: []const u8) !File { + const lo = mem.findScalar(u8, text, '<') orelse return .{ .body = text }; + const hi = mem.findScalar(u8, text, '>').?; + const groups = try arena.alloc(GroupRec, 1); + const variants = try arena.dupe([]const u8, &.{ text[lo + 1 .. hi], "other" }); + groups[0] = .{ .at = lo, .variants = variants }; + return .{ .body = try mem.concat(arena, u8, &.{ text[0..lo], variants[0], text[hi + 1 ..] }), .groups = groups }; } test "variants and text helpers" { |
