diff options
Diffstat (limited to 'src/doc.zig')
| -rw-r--r-- | src/doc.zig | 800 |
1 files changed, 800 insertions, 0 deletions
diff --git a/src/doc.zig b/src/doc.zig new file mode 100644 index 0000000..3860809 --- /dev/null +++ b/src/doc.zig @@ -0,0 +1,800 @@ +//! The document model and the file format. Pure Zig, no AppKit: `zig build test` covers it. +const std = @import("std"); +const ghost_io = @import("ghost_io.zig"); +const mem = std.mem; +const Allocator = mem.Allocator; + +pub const Scope = enum { word, sentence, paragraph }; + +/// The other ways to say one thing. `variants[active]` mirrors the text showing on the page; +/// there is always at least one variant. +pub const Group = struct { + scope: Scope, + active: usize = 0, + variants: std.ArrayList([]u8) = .empty, + /// Variants deleted this session, so that undoing a delete can put one back. + removed: std.ArrayList([]u8) = .empty, + /// What the AI suggested, by its text. A variant is the AI's while it still reads as + /// suggested; edited, it is the writer's. + ai: std.ArrayList([]u8) = .empty, + + pub fn init(gpa: Allocator, scope: Scope, variants: []const []const u8, active: usize) !Group { + var g: Group = .{ .scope = scope, .active = active }; + for (variants) |v| try g.variants.append(gpa, try gpa.dupe(u8, v)); + return g; + } + + pub fn deinit(g: *Group, gpa: Allocator) void { + for (g.variants.items) |v| gpa.free(v); + for (g.removed.items) |v| gpa.free(v); + for (g.ai.items) |v| gpa.free(v); + g.variants.deinit(gpa); + g.removed.deinit(gpa); + g.ai.deinit(gpa); + } + + pub fn isAI(g: *const Group, text: []const u8) bool { + return indexOf(g.ai.items, text) != null; + } + + pub fn markAI(g: *Group, gpa: Allocator, text: []const u8) !void { + if (g.isAI(text)) return; + try g.ai.ensureUnusedCapacity(gpa, 1); + g.ai.appendAssumeCapacity(try gpa.dupe(u8, text)); + } + + pub fn shown(g: *const Group) []const u8 { + return g.variants.items[g.active]; + } + + /// Bring the model in line with what the page shows. Typing rewrites the active variant. + /// Undo and redo can instead land on another variant, or on one that was deleted. + pub fn sync(g: *Group, gpa: Allocator, on_page: []const u8, undoing: bool) !void { + if (mem.eql(u8, g.shown(), on_page)) return; + if (undoing) { + for (g.variants.items, 0..) |v, i| if (mem.eql(u8, v, on_page)) { + g.active = i; + return; + }; + for (g.removed.items, 0..) |v, i| if (mem.eql(u8, v, on_page)) { + try g.variants.insert(gpa, g.active, v); + _ = g.removed.orderedRemove(i); + return; + }; + } + const copy = try gpa.dupe(u8, on_page); + gpa.free(g.variants.items[g.active]); + g.variants.items[g.active] = copy; + } + + /// The alternatives panel shows a group as text, one variant to a line, and this takes + /// that text back as the variants. Blank lines are rows nothing has been typed in yet. + /// `on` is the variant the panel's caret is on, counting only the lines that hold one, + /// and it shows. From a blank line, what showed before still shows, or else `fallback`. + /// False, and nothing changes, if no line holds anything. + pub fn setRows(g: *Group, gpa: Allocator, text: []const u8, on: ?usize, fallback: []const u8) !bool { + var rows: std.ArrayList([]u8) = .empty; + errdefer { + for (rows.items) |v| gpa.free(v); + rows.deinit(gpa); + } + var lines = mem.splitScalar(u8, text, '\n'); + while (lines.next()) |line| { + if (blank(line)) continue; + try rows.ensureUnusedCapacity(gpa, 1); + rows.appendAssumeCapacity(try gpa.dupe(u8, line)); + } + if (rows.items.len == 0) return false; + const last = rows.items.len - 1; + const active = if (on) |i| @min(i, last) else indexOf(rows.items, g.shown()) orelse indexOf(rows.items, fallback) orelse @min(g.active, last); + for (g.variants.items) |v| gpa.free(v); + g.variants.deinit(gpa); + g.variants = rows; + g.active = active; + return true; + } + + /// Whether the panel's text already says what the group holds. + pub fn sameRows(g: *const Group, text: []const u8) bool { + var n: usize = 0; + var lines = mem.splitScalar(u8, text, '\n'); + while (lines.next()) |line| { + if (blank(line)) continue; + if (n == g.variants.items.len or !mem.eql(u8, line, g.variants.items[n])) return false; + n += 1; + } + return n == g.variants.items.len; + } + + /// Move to a neighbouring variant, wrapping at the ends. + pub fn step(g: *Group, delta: isize) void { + const n: isize = @intCast(g.variants.items.len); + g.active = @intCast(@mod(@as(isize, @intCast(g.active)) + delta, n)); + } + + /// Delete the showing variant; the next one shows. Needs two or more. + pub fn remove(g: *Group, gpa: Allocator) !void { + std.debug.assert(g.variants.items.len > 1); + try g.removed.ensureUnusedCapacity(gpa, 1); + g.removed.appendAssumeCapacity(g.variants.orderedRemove(g.active)); + if (g.active == g.variants.items.len) g.active = 0; + } +}; + +fn indexOf(list: []const []const u8, text: []const u8) ?usize { + for (list, 0..) |v, i| if (mem.eql(u8, v, text)) return i; + return null; +} + +/// A row of the alternatives panel that holds no variant: nothing is typed in it, or it +/// is the "??" that asks the AI for some, or the "?" on the way there. +pub fn blank(line: []const u8) bool { + const typed = mem.trim(u8, line, " \t\r"); + return typed.len == 0 or mem.eql(u8, typed, "?") or asks(line); +} + +pub fn asks(line: []const u8) bool { + return mem.eql(u8, mem.trim(u8, line, " \t\r"), "??"); +} + +/// One line of the AI's answer as an alternative: without the numbering, bullets or +/// quotes a model may add though asked not to. Null if nothing is left. +pub fn suggestion(line: []const u8) ?[]const u8 { + var s = mem.trim(u8, line, " \t\r"); + var digits: usize = 0; + while (digits < s.len and std.ascii.isDigit(s[digits])) digits += 1; + if (digits > 0 and digits + 1 < s.len and (s[digits] == '.' or s[digits] == ')') and s[digits + 1] == ' ') s = s[digits + 2 ..]; + for ([_][]const u8{ "- ", "* ", "• " }) |bullet| { + if (mem.startsWith(u8, s, bullet)) s = s[bullet.len..]; + } + for ([_][2][]const u8{ .{ "\"", "\"" }, .{ "“", "”" } }) |q| { + if (s.len <= q[0].len + q[1].len or !mem.startsWith(u8, s, q[0]) or !mem.endsWith(u8, s, q[1])) continue; + const inner = s[q[0].len .. s.len - q[1].len]; + // One quoted answer, not a sentence that happens to open and close on quotes. + if (mem.find(u8, inner, q[0]) == null and mem.find(u8, inner, q[1]) == null) s = inner; + } + s = mem.trim(u8, s, " \t"); + return if (blank(s)) null else s; +} + +// --- The file ------------------------------------------------------------------------------- +// +// v2 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. Legacy comments were trailers. Offsets always address the full +// editor body, so v2 ghosts must be restored before the alternatives are reanchored. + +const overflow_mark = "<!-- overflow -->"; // legacy +const overflow_open = "<!-- overflow\n("; +const overflow_close = ")-->"; +const meta_open = "<!-- write_away "; +const meta_close = " -->"; +const framing = "\n\n"; +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 Meta = struct { + v: u32 = 1, + groups: []const GroupRec = &.{}, + ghosts: []const GhostRec = &.{}, + visible_sha256: ?[Sha256.digest_length * 2]u8 = null, +}; + +pub const File = struct { + body: []const u8 = "", + overflow: []const u8 = "", + groups: []const GroupRec = &.{}, + ghosts: []const GhostRec = &.{}, +}; + +pub fn serialize(gpa: Allocator, f: File) ![]u8 { + const has_meta = f.groups.len != 0 or f.ghosts.len != 0; + if (!has_meta and f.overflow.len == 0) return gpa.dupe(u8, f.body); + for (f.groups) |g| if (!validGroup(g)) return error.InvalidGroup; + const visible = if (f.ghosts.len != 0) try ghost_io.visible(gpa, f.body, f.ghosts) else f.body; + defer if (f.ghosts.len != 0) gpa.free(visible); + + var out: std.ArrayList(u8) = .empty; + errdefer out.deinit(gpa); + if (f.overflow.len > 0) { + try out.appendSlice(gpa, overflow_open); + // Escape ampersands first conceptually: each input byte is emitted only once. + for (f.overflow) |c| switch (c) { + '&' => try out.appendSlice(gpa, "&"), + '-' => try out.appendSlice(gpa, "-"), + else => try out.append(gpa, c), + }; + try out.appendSlice(gpa, overflow_close); + if (has_meta) try out.append(gpa, '\n'); + } + if (has_meta) { + 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, + }, .{ .emit_null_optional_fields = false }); + defer gpa.free(json); + try out.appendSlice(gpa, meta_open); + for (json) |c| switch (c) { + '>' => try out.appendSlice(gpa, "\\u003e"), + '-' => try out.appendSlice(gpa, "\\u002d"), + else => try out.append(gpa, c), + }; + try out.appendSlice(gpa, meta_close); + } + try out.appendSlice(gpa, framing); + try out.appendSlice(gpa, visible); + return out.toOwnedSlice(gpa); +} + +fn digest(bytes: []const u8) [Sha256.digest_length * 2]u8 { + var hash: [Sha256.digest_length]u8 = undefined; + Sha256.hash(bytes, &hash, .{}); + return std.fmt.bytesToHex(hash, .lower); +} + +/// Everything returned lives in `arena` or in `bytes`. If metadata is unsafe to +/// interpret, keep the entire source in the editor, including the recovery metadata. +pub fn parse(arena: Allocator, bytes: []const u8) !File { + const unchanged: File = .{ .body = bytes }; + var rest = bytes; + var overflow: ?[]const u8 = null; + if (mem.startsWith(u8, rest, overflow_open)) { + const block = splitComment(rest, overflow_open, overflow_close) orelse return unchanged; + if (mem.startsWith(u8, block.rest, framing)) return .{ + .body = block.rest[framing.len..], + .overflow = try decodeOverflow(arena, block.payload), + }; + if (!mem.startsWith(u8, block.rest, "\n" ++ meta_open)) return parseLegacy(arena, bytes); + overflow = block.payload; + rest = block.rest[1..]; + } + if (!mem.startsWith(u8, rest, meta_open)) return parseLegacy(arena, bytes); + 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; + + const visible = 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 groups = (try reanchorGroups(arena, body, meta.groups)) orelse return unchanged; + return .{ + .body = body, + .overflow = if (overflow) |encoded| try decodeOverflow(arena, encoded) else "", + .groups = groups, + .ghosts = meta.ghosts, + }; +} + +const Comment = struct { payload: []const u8, rest: []const u8 }; + +// Only unescaped comment delimiters may frame a block, never interrupt its payload. +fn splitComment(bytes: []const u8, open: []const u8, close: []const u8) ?Comment { + const tail = bytes[open.len..]; + const end = mem.find(u8, tail, close) orelse return null; + const payload = tail[0..end]; + if (mem.find(u8, payload, "--") != null) return null; + return .{ .payload = payload, .rest = tail[end + close.len ..] }; +} + +fn readMeta(arena: Allocator, json: []const u8, legacy: bool) !?Meta { + return std.json.parseFromSliceLeaky(Meta, arena, json, .{ .ignore_unknown_fields = legacy }) catch |err| switch (err) { + error.OutOfMemory => return err, + else => return null, + }; +} + +fn decodeOverflow(arena: Allocator, encoded: []const u8) ![]const u8 { + var decoded: std.ArrayList(u8) = .empty; + var i: usize = 0; + while (i < encoded.len) { + if (mem.startsWith(u8, encoded[i..], "&")) { + try decoded.append(arena, '&'); + i += 5; + } else if (mem.startsWith(u8, encoded[i..], "-")) { + try decoded.append(arena, '-'); + i += 5; + } else { + try decoded.append(arena, encoded[i]); + i += 1; + } + } + return decoded.items; +} + +// Legacy markers are column-zero lines, but those lines can also be fenced Markdown. +fn lineMarker(bytes: []const u8, comptime marker: []const u8, comptime last: bool) ?usize { + var rest = bytes; + var fence: []const u8 = ""; + var found: ?usize = null; + while (rest.len != 0) { + if (fence.len == 0) { + if (mem.startsWith(u8, rest, marker)) { + found = bytes.len - rest.len; + if (!last) return found; + } + // A wrapped Overflow trailer can contain its own unfinished code examples. + if (mem.startsWith(u8, rest, overflow_open)) { + if (splitComment(rest, overflow_open, overflow_close)) |block| { + const end = mem.findScalar(u8, block.rest, '\n') orelse break; + rest = block.rest[end + 1 ..]; + continue; + } + } + } + const end = mem.findScalar(u8, rest, '\n') orelse break; + const line = mem.trimStart(u8, rest[0..end], " "); + if (line.len >= 3 and end - line.len <= 3 and (line[0] == '`' or line[0] == '~')) { + var width: usize = 1; + while (width < line.len and line[width] == line[0]) width += 1; + if (fence.len == 0) { + if (width >= 3 and (line[0] != '`' or mem.findScalar(u8, line[width..], '`') == null)) fence = line[0..width]; + } else if (line[0] == fence[0] and width >= fence.len and mem.trim(u8, line[width..], " \t\r").len == 0) { + fence = ""; + } + } + rest = rest[end + 1 ..]; + } + return found; +} + +fn parseLegacy(arena: Allocator, bytes: []const u8) !File { + const unchanged: File = .{ .body = bytes }; + var meta: Meta = .{}; + var rest = bytes; + if (lineMarker(rest, meta_open, true)) |open| { + const block = splitComment(rest[open..], meta_open, meta_close) orelse return unchanged; + // Only a final comment is a legacy trailer. Otherwise it is body text. + if (mem.trim(u8, block.rest, " \r\n").len == 0) { + meta = (try readMeta(arena, block.payload, true)) orelse return unchanged; + if (meta.v != 1) return unchanged; + rest = rest[0..open]; + } + } + + var f: File = .{ .body = rest }; + if (lineMarker(rest, overflow_open, true)) |open| { + const block = splitComment(rest[open..], overflow_open, overflow_close) orelse return unchanged; + if (mem.trim(u8, block.rest, " \r\n").len == 0) { + f.body = rest[0..open]; + f.overflow = try decodeOverflow(arena, block.payload); + } + } else if (lineMarker(rest, overflow_mark, false)) |open| { + f.body = rest[0..open]; + f.overflow = mem.trim(u8, rest[open + overflow_mark.len ..], "\r\n"); + } + 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; + var ghosts: std.ArrayList(GhostRec) = .empty; + for (meta.ghosts) |g| { + const at = anchor(f.body, g.at, g.text) orelse return unchanged; + try ghosts.append(arena, .{ .at = at, .text = g.text }); + } + // Reanchoring an externally edited v1 file can change the order of its spans. + mem.sort(GhostRec, ghosts.items, {}, struct { + fn lessThan(_: void, a: GhostRec, b: GhostRec) bool { + return a.at < b.at; + } + }.lessThan); + var end: usize = 0; + for (ghosts.items) |g| { + if (g.at < end) return unchanged; + end = g.at + g.text.len; + } + f.ghosts = ghosts.items; + return f; +} + +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; + } + return groups; +} + +/// 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; +} + +// --- Text helpers --------------------------------------------------------------------------- + +/// What a selection inside one paragraph covers: all of a several-sentence paragraph, whole +/// sentences, or something smaller. `start` and `end` are byte offsets into `para`. +pub fn classify(para: []const u8, start: usize, end: usize) Scope { + const space = " \t\r\n"; + const before = mem.trimEnd(u8, para[0..start], space); + const sel = mem.trim(u8, para[start..end], space); + const after = mem.trim(u8, para[end..], space); + if (sel.len == 0) return .word; + + const at_head = mem.trimStart(u8, before, "# ").len == 0; // heading marks do not count + const starts = at_head or isStop(before[before.len - 1]); + const ends = after.len == 0 or isStop(sel[sel.len - 1]); + if (!starts or !ends) return .word; + + if (at_head and after.len == 0) { + for (sel[0 .. sel.len - 1], sel[1..]) |c, next| if (isStop(c) and next == ' ') return .paragraph; + } + return .sentence; +} + +fn isStop(c: u8) bool { + return c == '.' or c == '!' or c == '?'; +} + +/// Whether `word` takes "an" rather than "a". It goes by the sound the word starts with, +/// as far as a few spellings give that away. Null when it does not start with a letter. +pub fn takesAn(word: []const u8) ?bool { + if (word.len == 0 or !std.ascii.isAlphabetic(word[0])) return null; + var buf: [6]u8 = undefined; + const head = std.ascii.lowerString(&buf, word[0..@min(word.len, buf.len)]); + const starts = struct { + fn any(s: []const u8, prefixes: []const []const u8) bool { + for (prefixes) |p| if (mem.startsWith(u8, s, p)) return true; + return false; + } + }.any; + if (starts(head, &.{ "hour", "honest", "honor", "honour", "heir" })) return true; // a silent h + if (starts(head, &.{ "unin", "unim", "unid" })) return true; // "an uninvited", not "a unit" + if (starts(head, &.{ "uni", "use", "usu", "uti", "eu", "one", "once" })) return false; // "you" and "won" + return mem.findScalar(u8, "aeiou", head[0]) != null; +} + +pub fn countWords(s: []const u8) usize { + var n: usize = 0; + var it = mem.tokenizeAny(u8, s, " \t\r\n"); + while (it.next()) |_| n += 1; + return n; +} + +/// Length in UTF-16 units. NSString indexes by UTF-16 unit, the file by byte. +pub fn utf16Len(s: []const u8) usize { + var n: usize = 0; + for (s) |b| { + if (b & 0xC0 != 0x80) n += 1; // start of a codepoint + if (b >= 0xF0) n += 1; // four bytes: a surrogate pair + } + return n; +} + +/// Byte offset of UTF-16 index `index`. +pub fn utf8Index(s: []const u8, index: usize) usize { + var n: usize = 0; + for (s, 0..) |b, at| { + if (b & 0xC0 == 0x80) continue; + if (n >= index) return at; + n += if (b >= 0xF0) 2 else 1; + } + return s.len; +} + +// --- The check ------------------------------------------------------------------------------ + +test "hidden overflow preserves bytes and malformed blocks" { + const t = std.testing; + var state: std.heap.ArenaAllocator = .init(t.allocator); + defer state.deinit(); + const a = state.allocator(); + const text = "\n \r\n<!-- nested --> --!> -- & - \\ )-->\x00\xff\n\n"; + const body = "\r\n```zig\r\nconst x = 1;\r\n\n"; // Deliberately unclosed fence. + const bytes = try serialize(a, .{ .body = body, .overflow = text }); + try t.expect(mem.startsWith(u8, bytes, overflow_open)); + const block = splitComment(bytes, overflow_open, overflow_close).?; + try t.expectEqualStrings(framing ++ body, block.rest); + const back = try parse(a, bytes); + try t.expectEqualStrings(body, back.body); + try t.expectEqualStrings(text, back.overflow); + const legacy = try parse(a, "Body\n\n<!-- overflow -->\n\nOld text.\n"); + try t.expectEqualStrings("Body", legacy.body); + try t.expectEqualStrings("Old text.", legacy.overflow); + const wrapped = try parse(a, "Body\n\n<!-- overflow\n(\n&-\r\n)-->\n"); + try t.expectEqualStrings("Body", wrapped.body); + try t.expectEqualStrings("\n&-\r\n", wrapped.overflow); + for ([_][]const u8{ + "Body\n\n<!-- overflow\n(unclosed -->\nmore\n", + "<!-- overflow\n(a --> leaked)-->\n\nBody\n", + "<!-- 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", + "Body\n\n<!-- overflow\n(stash)-->\n\n<!-- write_away {\"v\":3} -->\n", + "Text.\n\n<!-- write_away {nope -->\n", + }) |bad| { + const f = try parse(a, bad); + try t.expectEqualStrings(bad, f.body); + try t.expectEqualStrings("", f.overflow); + } +} + +fn expectRaw(arena: Allocator, bytes: []const u8) !void { + const t = std.testing; + const f = try parse(arena, bytes); + try t.expectEqualStrings(bytes, f.body); + try t.expectEqualStrings("", f.overflow); + try t.expectEqual(0, f.groups.len); + try t.expectEqual(0, f.ghosts.len); + try t.expectEqualStrings(bytes, try serialize(arena, f)); +} + +test "legacy trailers are not taken from fenced Markdown" { + const t = std.testing; + var state: std.heap.ArenaAllocator = .init(t.allocator); + defer state.deinit(); + const a = state.allocator(); + const bare = "<!-- overflow -->\nSome example text.\n"; + const wrapped = "<!-- overflow\n(Example.)-->\n"; + const meta = "<!-- write_away {\"v\":1} -->\n"; + for ([_][]const u8{ bare, wrapped, meta }) |example| { + try expectRaw(a, try mem.concat(a, u8, &.{ "Body\n\n```md\n", example })); + try expectRaw(a, try mem.concat(a, u8, &.{ "Body\n\n ~~~md\r\n", example, " ~~~~ \r\n" })); + } + try expectRaw(a, "````md\n```\n<!-- overflow -->\n````\n"); + + const closed = "```md\n" ++ bare ++ "```"; + const real = try parse(a, closed ++ "\n\n<!-- overflow -->\nReal overflow.\n"); + try t.expectEqualStrings(closed, real.body); + try t.expectEqualStrings("Real overflow.", real.overflow); + const wrapped_then_meta = try parse(a, "Body\n\n<!-- overflow\n(\n```md\nUnclosed example.)-->\n" ++ meta); + try t.expectEqualStrings("Body", wrapped_then_meta.body); + try t.expectEqualStrings("\n```md\nUnclosed example.", wrapped_then_meta.overflow); +} + +test "v1 ghosts require an exact or unique anchor" { + const t = std.testing; + var state: std.heap.ArenaAllocator = .init(t.allocator); + defer state.deinit(); + const a = state.allocator(); + const trailer = "\n\n<!-- write_away {\"v\":1,\"ghosts\":[{\"at\":4,\"text\":\"ghost\"}]} -->\n"; + try expectRaw(a, "ghost and ghost" ++ trailer); + try expectRaw(a, "no match" ++ trailer); + try expectRaw(a, "ghost\n\n<!-- write_away {\"v\":1,\"ghosts\":[{\"at\":0,\"text\":\"ghost\"},{\"at\":9,\"text\":\"ghost\"}]} -->\n"); + + const exact = try parse(a, "one ghost and ghost" ++ trailer); + try t.expectEqualStrings("one ghost and ghost", exact.body); + try t.expectEqual(1, exact.ghosts.len); + try t.expectEqual(4, exact.ghosts[0].at); +} + +test "v1 and v2 groups preserve all raw metadata if any record cannot be anchored" { + const t = std.testing; + var state: std.heap.ArenaAllocator = .init(t.allocator); + defer state.deinit(); + const a = state.allocator(); + const body = "one banana"; + const first_group = "\"groups\":[{\"at\":0,\"variants\":[\"one\",\"first\"]},"; + for ([_][]const u8{ + "{\"at\":0,\"variants\":[\"ana\",\"missing\"],\"active\":1}", // The inactive variant must not anchor. + "{\"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 })); + } + + const record = "{\"at\":5,\"variants\":[\"ana\",\"other\"]}]"; + const legacy = try mem.concat(a, u8, &.{ body, "\n\n", meta_open, "{\"v\":1,", first_group, record, "}", meta_close }); + const prefixed = try mem.concat(a, u8, &.{ meta_open, "{\"v\":2,", first_group, record, "}", meta_close, framing, body }); + for ([_][]const u8{ legacy, prefixed }) |bytes| { + const exact = try parse(a, bytes); + try t.expectEqual(2, exact.groups.len); + try t.expectEqual(5, exact.groups[1].at); + } +} + +test "v2 hides ghosts and rejects edits or invalid ghost positions without losing the source" { + const t = std.testing; + var arena_state: std.heap.ArenaAllocator = .init(t.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + + // Round trip. The '>' in a variant must not close the comment. + const body = "# Title\n\nThe tension is real. Maybe cut this."; + const file: File = .{ + .body = body, + .overflow = "Kept for later.", + .groups = &.{.{ .scope = .word, .at = 13, .active = 1, .variants = &.{ "pressure", "tension", "a --> b" } }}, + .ghosts = &.{.{ .at = 30, .text = "Maybe cut this." }}, + }; + 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,")); + 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); + const back = try parse(arena, bytes); + try t.expectEqualStrings(body, back.body); + try t.expectEqualStrings("Kept for later.", back.overflow); + try t.expectEqual(13, back.groups[0].at); + 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)); + } +} + +test "v2 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(); + const a = state.allocator(); + const before = "\n\r\n```zig\r\ncafé"; + const first = "👻"; + const second = "<!-- --!> -->"; + const keep = "\r\n終 "; + const last = "\n💤\n"; + const body = before ++ first ++ second ++ keep ++ last; + const file: File = .{ + .body = body, + .groups = &.{ + .{ .at = before.len - "café".len, .variants = &.{ "café" ++ first ++ second, "coffee" } }, + .{ .at = before.len, .variants = &.{ first, "spirit" }, .ai = &.{"spirit"} }, + .{ .at = (before ++ first ++ second).len, .variants = &.{ keep, "end" } }, + }, + .ghosts = &.{ + .{ .at = before.len, .text = first }, + .{ .at = (before ++ first).len, .text = second }, + .{ .at = (before ++ first ++ second ++ keep).len, .text = last }, + }, + }; + const bytes = try serialize(a, file); + try t.expectEqualStrings(framing ++ before ++ keep, splitComment(bytes, meta_open, meta_close).?.rest); + const restored = try parse(a, bytes); + try t.expectEqualStrings(body, restored.body); + try t.expectEqual(file.ghosts.len, restored.ghosts.len); + for (file.ghosts, restored.ghosts) |expected, actual| { + try t.expectEqual(expected.at, actual.at); + try t.expectEqualStrings(expected.text, actual.text); + } + try t.expectEqual(file.groups.len, restored.groups.len); + for (file.groups, restored.groups) |expected, actual| try t.expectEqual(expected.at, actual.at); + try t.expectEqualStrings("spirit", restored.groups[1].ai.?[0]); + + var edited = restored; + edited.body = try mem.concat(a, u8, &.{ restored.body, "new ending\n" }); + const saved = try serialize(a, edited); + try t.expectEqualStrings(framing ++ before ++ keep ++ "new ending\n", splitComment(saved, meta_open, meta_close).?.rest); + try t.expectEqualStrings(edited.body, (try parse(a, saved)).body); + + const all_hidden = try serialize(a, .{ .body = first ++ last, .ghosts = &.{ + .{ .at = 0, .text = first }, + .{ .at = first.len, .text = last }, + } }); + try t.expectEqualStrings(framing, splitComment(all_hidden, meta_open, meta_close).?.rest); + try t.expectEqualStrings(first ++ last, (try parse(a, all_hidden)).body); + try t.expectError(error.InvalidGhost, serialize(a, .{ .body = body, .ghosts = &.{.{ .at = 0, .text = last }} })); +} + +test "plain Markdown is byte-exact; v1 ghosts and ghost-free v2 groups still follow their text" { + const t = std.testing; + var state: std.heap.ArenaAllocator = .init(t.allocator); + defer state.deinit(); + const a = state.allocator(); + for ([_][]const u8{ "", "Just text.", "\n\r\n# Title\r\n", "\n```\n ", "---\nkey: café\n---\n\n" }) |body| { + const bytes = try serialize(a, .{ .body = body }); + try t.expectEqualStrings(body, bytes); + try t.expectEqualStrings(body, (try parse(a, bytes)).body); + } + + const legacy = "# A longer title\n\nThe tension is real. Maybe cut this.\n\n" ++ + "<!-- overflow\n(Old text.)-->\n\n" ++ + "<!-- write_away {\"v\":1,\"groups\":[{\"at\":13,\"variants\":[\"tension\",\"pressure\"]}]," ++ + "\"ghosts\":[{\"at\":30,\"text\":\"Maybe cut this.\"}]} -->\n"; + const old = try parse(a, legacy); + try t.expectEqualStrings("# A longer title\n\nThe tension is real. Maybe cut this.", old.body); + try t.expectEqualStrings("Old text.", old.overflow); + try t.expectEqual(22, old.groups[0].at); + try t.expectEqual(39, old.ghosts[0].at); + const migrated = try serialize(a, old); + try t.expectEqualStrings(old.body, (try parse(a, migrated)).body); + try t.expect(!mem.endsWith(u8, migrated, "Maybe cut this.")); + + const no_ghosts = try serialize(a, .{ + .body = "The tension is real.\r\n\n", + .groups = &.{.{ .at = 4, .variants = &.{ "tension", "strain" } }}, + }); + const edited = try mem.replaceOwned(u8, a, no_ghosts, "The tension is", "Some tension is"); + 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); +} + +test "variants and text helpers" { + const t = std.testing; + var state: std.heap.ArenaAllocator = .init(t.allocator); + defer state.deinit(); + const arena = state.allocator(); + + // Variants. + var g = try Group.init(arena, .word, &.{ "tension", "pressure" }, 0); + g.step(-1); + try t.expectEqualStrings("pressure", g.shown()); + try g.sync(arena, "strain", false); // typing rewrites the active variant + try t.expectEqualStrings("strain", g.variants.items[1]); + try g.sync(arena, "tension", true); // undo lands on the other variant + try t.expectEqual(0, g.active); + try g.remove(arena); + try t.expectEqualStrings("strain", g.shown()); + try g.sync(arena, "tension", true); // undoing the delete brings it back + try t.expectEqual(2, g.variants.items.len); + try t.expectEqualStrings("tension", g.shown()); + + // The panel's rows. A blank row is not a variant, and a caret on one changes nothing. + try t.expect(g.sameRows("tension\nstrain\n")); + try t.expect(!g.sameRows("tension\n")); + try t.expect(try g.setRows(arena, "tension\nstrain\n\nc", 2, "")); + try t.expectEqualStrings("c", g.shown()); // typed on the new row, and showing + try t.expect(try g.setRows(arena, "tension\nstrain\n\n", null, "strain")); + try t.expectEqualStrings("strain", g.shown()); // the row was emptied: back to where the visit began + try t.expect(try g.setRows(arena, "tension\nstrain\n", null, "")); + try t.expectEqualStrings("strain", g.shown()); + + // Asking the AI. The "??" row is not a variant, and neither is the "?" before it. + try t.expect(g.sameRows("tension\nstrain\n?")); + try t.expect(g.sameRows("tension\nstrain\n ??")); + try t.expect(asks("??") and !asks("?") and !asks("what??")); + try t.expectEqualStrings("pull", suggestion("3. pull").?); + try t.expectEqualStrings("pull", suggestion(" - “pull” ").?); + try t.expectEqualStrings("\"no\" and \"yes\"", suggestion("\"no\" and \"yes\"").?); + try t.expectEqual(null, suggestion(" ")); + try g.markAI(arena, "strain"); + try t.expect(g.isAI("strain") and !g.isAI("strains")); + try t.expect(!try g.setRows(arena, " \n", null, "")); + try t.expectEqual(2, g.variants.items.len); + + // a or an. + try t.expectEqual(true, takesAn("eraser")); + try t.expectEqual(false, takesAn("thumbtack")); + try t.expectEqual(true, takesAn("Hour")); + try t.expectEqual(false, takesAn("user")); + try t.expectEqual(true, takesAn("uninvited")); + try t.expectEqual(null, takesAn("“quoted”")); + + // Text helpers. + const para = "# One two. Three four. Five"; + try t.expectEqual(Scope.word, classify(para, 6, 9)); + try t.expectEqual(Scope.sentence, classify(para, 11, 22)); + try t.expectEqual(Scope.sentence, classify(para, 2, 10)); + try t.expectEqual(Scope.paragraph, classify(para, 2, para.len)); + try t.expectEqual(3, countWords(" a b\nc ")); + try t.expectEqual(4, utf16Len("é😀a")); // 1 + 2 + 1 + try t.expectEqual(6, utf8Index("é😀a", 3)); +} |
