summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authort <t@tjp.lol>2026-11-25 11:25:00 -0700
committert <t@tjp.lol>2026-11-25 11:25:13 -0700
commit205b1d26b5be40424eace945a73867bdfefe90ce (patch)
tree74f51369662d6d065b218f8ba32bf32760eb4596 /src
parentd85d5e98868a4ee0dda6d3faf666996cdb18f998 (diff)
Anchor ghosts and alternatives to surrounding text, not byte offsets
Ghosted text and alternatives are saved with context from the text around them, so an outside edit no longer sends the whole file to raw Markdown. A ghost with no clear place goes to Overflow. An alternatives group that cannot be matched is dropped; its text is not kept. HTML comments show dimmed in place, with their delimiters hidden until the caret enters them. Ctrl+/ on a comment uncomments it. Comments are left out of Lab and AI requests, except the one an alternatives target sits in. The metadata moves to format v3. Builds before this one show v3 files as raw Markdown, so install this build before saving.
Diffstat (limited to 'src')
-rw-r--r--src/doc.zig481
-rw-r--r--src/ghost_io.zig7
-rw-r--r--src/lab.zig30
-rw-r--r--src/main.zig232
-rw-r--r--src/markdown.zig119
5 files changed, 775 insertions, 94 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" {
diff --git a/src/ghost_io.zig b/src/ghost_io.zig
index e5061ff..ff9f612 100644
--- a/src/ghost_io.zig
+++ b/src/ghost_io.zig
@@ -37,11 +37,8 @@ pub fn visible(allocator: Allocator, body: []const u8, ghosts: anytype) ![]const
/// owns the returned slice. On failure, keep the original Markdown and metadata
/// intact rather than continuing with a partially decoded document.
///
-/// Offset-only records cannot detect edits that leave all insertion points in
-/// bounds and on codepoint boundaries. In that case restore inserts all text at
-/// the recorded positions, without guessing new ones. To reject such edits,
-/// the caller must verify a separately stored digest of the visible bytes and
-/// fall back to the original Markdown on mismatch.
+/// Offsets alone cannot say whether the visible bytes were edited: the caller
+/// must already know where each ghost belongs in these.
pub fn restore(allocator: Allocator, body_visible: []const u8, ghosts: anytype) ![]const u8 {
if (ghosts.len != 0 and !std.unicode.utf8ValidateSlice(body_visible)) return error.InvalidUtf8;
var removed: usize = 0;
diff --git a/src/lab.zig b/src/lab.zig
index 3750d80..84ab9d1 100644
--- a/src/lab.zig
+++ b/src/lab.zig
@@ -2,6 +2,7 @@
const std = @import("std");
const Allocator = std.mem.Allocator;
const mem = std.mem;
+const doc = @import("doc.zig");
const Json = std.json.Value;
pub const Pass = enum {
@@ -159,9 +160,11 @@ const Sentences = struct {
};
/// Pair with pass.prompt(). The same UTF-8 snapshot must be used for parse().
-/// Input is plain text with paragraphs on separate lines and Markdown # headings.
-pub fn question(arena: Allocator, pass: Pass, body: []const u8) ![]const u8 {
- if (!std.unicode.utf8ValidateSlice(body)) return error.InvalidUtf8;
+/// Input is plain text with paragraphs on separate lines and Markdown # headings. Its
+/// comments are nobody else's to read.
+pub fn question(arena: Allocator, pass: Pass, draft: []const u8) ![]const u8 {
+ if (!std.unicode.utf8ValidateSlice(draft)) return error.InvalidUtf8;
+ const body = try doc.withoutComments(arena, draft);
var buf: std.ArrayList(u8) = .empty;
var blocks: Blocks = .{ .lines = .{ .text = body } };
var n: usize = 0;
@@ -183,12 +186,14 @@ pub fn question(arena: Allocator, pass: Pass, body: []const u8) ![]const u8 {
return buf.toOwnedSlice(arena);
}
-/// `text` borrows body. The array and replacements live in arena, independent of answer.
-/// Invalid JSON is an error; invalid individual entries are ignored.
-pub fn parse(arena: Allocator, pass: Pass, body: []const u8, answer: []const u8) ![]Finding {
- if (!std.unicode.utf8ValidateSlice(body) or !std.unicode.utf8ValidateSlice(answer)) return error.InvalidUtf8;
+/// Everything returned lives in arena, independent of answer. A finding can run over a
+/// comment, which is blank in its text. Invalid JSON is an error; invalid individual entries
+/// are ignored.
+pub fn parse(arena: Allocator, pass: Pass, draft: []const u8, answer: []const u8) ![]Finding {
+ if (!std.unicode.utf8ValidateSlice(draft) or !std.unicode.utf8ValidateSlice(answer)) return error.InvalidUtf8;
const root = try std.json.parseFromSliceLeaky(Json, arena, answer, .{ .allocate = .alloc_always });
if (root != .array) return error.InvalidAnswer;
+ const body = try doc.withoutComments(arena, draft);
return if (pass.isTrim()) trims(arena, pass, body, root.array.items) else parseMarks(arena, pass, body, root.array.items);
}
@@ -581,6 +586,17 @@ test "Lab numbers the snapshot consistently and anchors only unique exact quotes
try std.testing.expect(findings[0].replacement == null and findings[1].replacement == null);
}
+test "Lab reads around comments, and its offsets still address the draft" {
+ var a = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer a.deinit();
+ const arena = a.allocator();
+ const body = "One <!-- sécret --> thing.\n\n<!--\nPrivate.\n-->\nLast fuzzy.";
+ try std.testing.expectEqualStrings("[1] One" ++ " " ** 18 ++ "thing.\n[2] Last fuzzy.\n", try question(arena, .hedges, body));
+ const found = try parse(arena, .hedges, body, "[{\"paragraph\":2,\"text\":\"fuzzy\"},{\"paragraph\":1,\"text\":\"cret\"}]");
+ try std.testing.expectEqual(@as(usize, 1), found.len);
+ try std.testing.expectEqual(mem.indexOf(u8, body, "fuzzy").?, found[0].at);
+}
+
test "Lab typo fixes reject rewrites, conflicts and line separators" {
var a = std.heap.ArenaAllocator.init(std.testing.allocator);
defer a.deinit();
diff --git a/src/main.zig b/src/main.zig
index 9854bf5..369df16 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -82,6 +82,7 @@ var key_group: id = null;
var key_ghost: id = null;
var key_lab_keep: id = null;
var key_fence: id = null; // on a paragraph that leaves a code fence open: `markdown.fenceLine`'s state after it
+var key_comment: id = null; // on an HTML comment: `yes` on what it says, 2 on its delimiters
var key_rule: id = null; // on a "---" or "***" or "___" that is drawn as a rule, and on
var key_quote: id = null; // a quoted line that has a bar for its ">": neither while the caret is there
var key_picture: id = null; // on a line that is all one image, the NSImage drawn in its place: likewise
@@ -98,6 +99,7 @@ var markdown_dirty: ?NSRange = null;
var markdown_caret: ?usize = null;
var markdown_rendering = false;
var markdown_front = false; // the piece opens with YAML frontmatter: see `doc.frontmatter`
+var markdown_comments: std.ArrayList(markdown.Span) = .empty; // as of the last `scanComments`
var markdown_units: std.ArrayList(u16) = .empty;
var markdown_parser: markdown.Parser = .{};
var markdown_line: id = null; // a single line, struck through the text or under a link
@@ -464,6 +466,8 @@ fn refresh() void {
drawReview();
it = .{ .key = key_ghost };
while (it.next()) |run| tint(NSForegroundColorAttributeName, color.ghost, run.range);
+ it = .{ .key = key_comment };
+ while (it.next()) |run| if (idOf(run.value) == 1) tint(NSForegroundColorAttributeName, color.ghost, run.range);
msg(void, page, "setNeedsDisplay:", .{true});
status();
@@ -533,6 +537,11 @@ fn markdownRefresh() void {
defer markdown_rendering = false;
msg(void, storage, "beginEditing", .{});
defer msg(void, storage, "endEditing", .{});
+ // A comment can open or close by what is typed far from what it hides.
+ if (changed != null) if (markComments()) |r| {
+ const lines = paragraphOf(page, r);
+ dirty = markdownRange(@min(dirty.location, lines.location), @max(end(dirty), end(lines)));
+ };
var open = fenceBefore(dirty.location);
var i = dirty.location;
while (i < end(dirty)) {
@@ -557,6 +566,7 @@ fn markdownRefresh() void {
last = para.location;
};
markdownFences(caret);
+ markdownDelimiters(caret);
// A change of attributes alone does not get every line it touched drawn again.
msg(void, page, "setNeedsDisplay:", .{true});
}
@@ -590,24 +600,78 @@ fn markdownFences(caret: ?usize) void {
}
}
+fn scanComments() void {
+ markdown_comments.clearRetainingCapacity();
+ const all: NSRange = .{ .length = len() };
+ markdown_units.resize(gpa, all.length) catch return;
+ msg(void, string(page), "getCharacters:range:", .{ markdown_units.items.ptr, all });
+ var it: markdown.Comments(u16) = .{ .text = markdown_units.items, .front = markdown_front };
+ while (it.next()) |c| markdown_comments.append(gpa, c) catch return;
+}
+
+/// A comment's two delimiters. One too short for both is all the first.
+fn delimiters(c: markdown.Span) [2]NSRange {
+ if (c.hi - c.lo < markdown.comment_open + markdown.comment_close) return .{ markdownRange(c.lo, c.hi), markdownRange(c.hi, c.hi) };
+ return .{ markdownRange(c.lo, c.lo + markdown.comment_open), markdownRange(c.hi - markdown.comment_close, c.hi) };
+}
+
+/// Bring `key_comment` in line with the text. Returns what that changed, if anything.
+fn markComments() ?NSRange {
+ scanComments();
+ var changed: ?NSRange = null;
+ var at: usize = 0;
+ for (markdown_comments.items) |c| {
+ const tags = delimiters(c);
+ markComment(markdownRange(at, c.lo), null, &changed);
+ markComment(tags[0], number(2), &changed);
+ markComment(markdownRange(end(tags[0]), tags[1].location), yes, &changed);
+ markComment(tags[1], number(2), &changed);
+ at = c.hi;
+ }
+ markComment(markdownRange(at, len()), null, &changed);
+ return changed;
+}
+
+fn markComment(r: NSRange, want: id, changed: *?NSRange) void {
+ if (r.length == 0 or uniform(r, key_comment, want)) return;
+ setMarkdownAttribute(r, key_comment, want);
+ changed.* = markdownRange(if (changed.*) |was| was.location else r.location, end(r));
+}
+
+/// A comment's delimiters show only while the caret is in it or against it.
+fn markdownDelimiters(caret: ?usize) void {
+ for (markdown_comments.items) |c| {
+ const show = if (caret) |at| at >= c.lo and at <= c.hi else false;
+ for (delimiters(c)) |tag| {
+ if (tag.length == 0) continue;
+ setMarkdownAttribute(tag, NSFontAttributeName, if (show) font else hidden);
+ setMarkdownAttribute(tag, NSForegroundColorAttributeName, if (show) color.dim else color.clear);
+ setMarkdownAttribute(tag, NSStrikethroughStyleAttributeName, null);
+ setMarkdownAttribute(tag, NSUnderlineStyleAttributeName, null);
+ }
+ }
+}
+
/// `open` is the fence state the paragraph starts in, and is left as the next will find it.
fn markdownParagraph(para: NSRange, caret: ?usize, open: *u32) void {
if (para.length == 0) return;
markdown_units.resize(gpa, para.length) catch return;
msg(void, string(page), "getCharacters:range:", .{ markdown_units.items.ptr, para });
const units = markdown_units.items;
- const kind = markdown.fenceLine(units, open, markdown_front and para.location == 0);
+ // In a comment there is formatting, as in a ghost, but nothing is drawn at full strength.
+ const commented = msg(id, storage, "attribute:atIndex:effectiveRange:", .{ key_comment, para.location, @as(?*NSRange, null) }) != null;
+ const kind = if (commented) .text else markdown.fenceLine(u16, units, open, markdown_front and para.location == 0);
setMarkdownAttribute(para, key_fence, if (open.* != 0) number(open.*) else null);
// What stands for a paragraph's own marks gives way to them while the caret is in it.
const here = if (caret) |at| paragraphOf(page, .{ .location = at }).location == para.location else false;
- const prefix = if (kind == .text) marker(para) else 0;
+ const prefix = if (kind == .text and !(commented and units[0] == '>')) marker(para) else 0;
const quote = prefix != 0 and units[0] == '>';
- const rule = kind == .text and switch (markdown.rule(units)) {
+ const rule = kind == .text and !commented and switch (markdown.rule(units)) {
.no => false,
.yes => true,
.hyphens => !underlines(para.location),
};
- const picture = if (kind == .text and !here) pictureAt(markdown.image(units) orelse &.{}) else null;
+ const picture = if (kind == .text and !commented and !here) pictureAt(markdown.image(units) orelse &.{}) else null;
setMarkdownAttribute(para, key_rule, if (rule and !here) yes else null);
setMarkdownAttribute(para, key_quote, if (quote and !here) yes else null);
setMarkdownAttribute(para, key_picture, picture);
@@ -709,11 +773,16 @@ fn markdownPaint(r: NSRange, style: markdown.Style, heading: bool, hide: bool) v
setMarkdownAttribute(r, NSUnderlineStyleAttributeName, if (link) markdown_line else null);
}
-fn setMarkdownAttribute(r: NSRange, key: id, want: id) void {
+/// Whether all of `r` has `want` for its `key`. Not by identity alone: text storage may hold
+/// its own copy of a paragraph style.
+fn uniform(r: NSRange, key: id, want: id) bool {
var run: NSRange = .{};
const have = msg(id, storage, "attribute:atIndex:longestEffectiveRange:inRange:", .{ key, r.location, &run, r });
- // Not by identity alone: text storage may hold its own copy of a paragraph style.
- if (run.length == r.length and (have == want or (want != null and msg(bool, have, "isEqual:", .{want})))) return;
+ return run.length == r.length and (have == want or (want != null and msg(bool, have, "isEqual:", .{want})));
+}
+
+fn setMarkdownAttribute(r: NSRange, key: id, want: id) void {
+ if (uniform(r, key, want)) return;
if (want != null) {
msg(void, storage, "addAttribute:value:range:", .{ key, want, r });
} else {
@@ -786,7 +855,8 @@ fn flipHere(delta: isize) void {
flip(gid, delta);
}
-/// Ctrl+/. Dim the selection or the word at the caret; on ghosted text, bring all of it back.
+/// Ctrl+/. Dim the selection or the word at the caret; on ghosted text, or in a comment,
+/// bring all of it back.
fn ghost(_: id, _: SEL, _: id) callconv(.c) void {
settle();
const r = ghostable();
@@ -798,15 +868,50 @@ fn ghost(_: id, _: SEL, _: id) callconv(.c) void {
return labKeep(null, null, null);
};
};
- const revive = ghostIn(r);
+ const commented = commentIn(r);
+ const revive = commented or ghostIn(r);
var it: Runs = .{ .key = key_ghost };
while (it.next()) |run| {
if (reading) |j| if (run.value == j.owner) continue;
if (overlap(run.range, r)) mark(run.range, key_ghost, null);
}
+ if (commented) uncomment(r);
if (!revive) mark(r, key_ghost, yes);
}
+fn commentIn(r: NSRange) bool {
+ var it: Runs = .{ .key = key_comment };
+ while (it.next()) |run| if (overlap(run.range, r)) return true;
+ return false;
+}
+
+/// Make prose of every comment `r` touches, by taking its delimiters out of the text: with
+/// the line, if one has a line to itself, or else with the space that sets it off.
+fn uncomment(r: NSRange) void {
+ scanComments();
+ const found = gpa.dupe(markdown.Span, markdown_comments.items) catch return; // each change scans again
+ defer gpa.free(found);
+ const um = msg(id, page, "undoManager", .{});
+ msg(void, page, "breakUndoCoalescing", .{});
+ msg(void, um, "beginUndoGrouping", .{});
+ defer msg(void, um, "endUndoGrouping", .{});
+ var i = found.len;
+ while (i > 0) {
+ i -= 1;
+ if (!overlap(markdownRange(found[i].lo, found[i].hi), r)) continue;
+ var tags = delimiters(found[i]);
+ for (&tags) |*tag| if (tag.length > 0) {
+ const line = paragraphOf(page, tag.*);
+ if (std.meta.eql(trimmed(line), tag.*)) tag.* = line;
+ };
+ const inner = markdownRange(end(tags[0]), @max(end(tags[0]), tags[1].location));
+ if (inner.length > 0 and charAt(end(tags[0])) == ' ') tags[0].length += 1;
+ if (end(tags[0]) < tags[1].location and charAt(tags[1].location - 1) == ' ') tags[1] = markdownRange(tags[1].location - 1, end(tags[1]));
+ replace(tags[1], "", null);
+ replace(tags[0], "", null);
+ }
+}
+
/// What Ctrl+/ is about: the selection, or the word at the caret.
fn ghostable() NSRange {
const sel = selection();
@@ -837,8 +942,7 @@ fn stash(_: id, _: SEL, _: id) callconv(.c) void {
if (sel.length == 0 and end(r) < len() and charAt(end(r)) == '\n') r.length += 1; // and the blank line after it
const have = objc.utf8(string(over));
- const gap = if (have.len == 0 or std.mem.endsWith(u8, have, "\n\n")) "" else if (have[have.len - 1] == '\n') "\n" else "\n\n";
- const entry = std.mem.concat(gpa, u8, &.{ gap, text }) catch return;
+ const entry = std.mem.concat(gpa, u8, &.{ doc.overflowGap(have), text }) catch return;
defer gpa.free(entry);
insert(over, entry, .{ .location = msg(usize, string(over), "length", .{}) });
insert(page, "", r);
@@ -1197,6 +1301,22 @@ fn wanted(scope: doc.Scope) usize {
return if (scope == .word) 5 else 3;
}
+/// The paragraph `r` is in, without its comments unless `r` is in one or runs over one.
+fn proseAround(arena: std.mem.Allocator, r: NSRange) []const u8 {
+ const para = paragraphOf(page, r);
+ if (commentIn(r)) return textOf(para);
+ var out: std.ArrayList(u8) = .empty;
+ var at = para.location;
+ var it: Runs = .{ .key = key_comment, .at = at };
+ while (it.next()) |run| {
+ if (run.range.location >= end(para)) break;
+ out.appendSlice(arena, textOf(markdownRange(at, run.range.location))) catch {};
+ at = @min(end(run.range), end(para));
+ }
+ out.appendSlice(arena, textOf(markdownRange(at, end(para)))) catch {};
+ return out.items;
+}
+
/// Send the question the panel's "??" row is asking.
fn askAI() void {
const g = groups.getPtr(target) orelse return;
@@ -1219,7 +1339,7 @@ fn askAI() void {
};
var q: std.ArrayList(u8) = .empty;
q.print(arena, "The paragraph it stands in:\n{s}\n\nThe {s} to say another way:\n{s}\n\nAlready tried:\n", .{
- std.mem.trim(u8, textOf(paragraphOf(page, r)), "\n"), what, g.shown(),
+ std.mem.trim(u8, proseAround(arena, r), "\n"), what, g.shown(),
}) catch {};
for (g.variants.items) |v| q.print(arena, "{s}\n", .{v}) catch {};
q.print(arena, "\nGive {d} alternatives.", .{wanted(g.scope)}) catch {};
@@ -1387,7 +1507,8 @@ fn propose(j: *Job, pass: lab.Pass, answer: []const u8) ?[]const u8 {
var mapped: std.ArrayList(Hit) = .empty;
findings: for (found) |f| {
const r = utf16Range(j.draft, f.at, f.text.len);
- // Skip the whole cut if it intersects a manual ghost or a kept span.
+ // Skip the whole cut if it intersects a comment, a manual ghost or a kept span.
+ if (commentIn(r)) continue;
var it: Runs = .{ .key = key_ghost, .at = r.location };
while (it.next()) |run| {
if (run.range.location >= end(r)) break;
@@ -1765,12 +1886,20 @@ fn load(bytes: []const u8) void {
msg(void, msg(id, page, "undoManager", .{}), "removeAllActions", .{});
select(.{});
msg(void, page, "scrollPoint:", .{NSPoint{}});
- setDirty(false);
+ // A ghost that went to Overflow goes there in the file too, with the next save.
+ setDirty(f.displaced);
+ if (f.displaced) {
+ overflow_open = true;
+ tools = true;
+ finishReview(displaced_note);
+ }
panels();
typing();
refresh();
}
+const displaced_note = "The file was edited elsewhere: ghosts with no clear place are now in Overflow";
+
fn utf16Range(body: []const u8, at: usize, byte_len: usize) NSRange {
return .{ .location = doc.utf16Len(body[0..at]), .length = doc.utf16Len(body[at..][0..byte_len]) };
}
@@ -1874,6 +2003,7 @@ fn save(ask: bool) bool {
}
setPath(to);
setDirty(false);
+ if (std.mem.eql(u8, lab_message.items, displaced_note)) finishReview("");
return true;
}
@@ -2054,7 +2184,7 @@ fn contextMenu(self: id, _: SEL, event: id) callconv(.c) id {
lab_ui.openWritingMenu(point, .{
menuTitle(&buf[0], "Alternatives"),
menuTitle(&buf[1], "AI alternatives"),
- if (ghostIn(ghostable())) "Revive it" else "Ghost it",
+ if (ghostIn(ghostable()) or commentIn(ghostable())) "Revive it" else "Ghost it",
"Stash this in Overflow",
});
// Leaving an edited alternatives panel can settle it and move the page selection.
@@ -2383,6 +2513,7 @@ fn setup(app: id) void {
key_ghost = msg(id, str("WriteAwayGhost"), "retain", .{});
key_lab_keep = msg(id, str("WriteAwayLabKeep"), "retain", .{});
key_fence = msg(id, str("WriteAwayFence"), "retain", .{});
+ key_comment = msg(id, str("WriteAwayComment"), "retain", .{});
key_rule = msg(id, str("WriteAwayRule"), "retain", .{});
key_quote = msg(id, str("WriteAwayQuote"), "retain", .{});
key_picture = msg(id, str("WriteAwayPicture"), "retain", .{});
@@ -3070,6 +3201,23 @@ fn selftest() void {
removeShown(mixed);
t.expect(groups.get(mixed).?.active == 0 and groups.get(mixed).?.variants.items.len == 2 and !msg(bool, alts, "isEditable", .{}), "a mixed ghost cannot be overwritten by flipping, removing, or typing a variant");
t.expect(std.mem.endsWith(u8, snapshot(arena) catch unreachable, "\n\necho eo end"), "a blocked swap leaves the original ghost intact");
+
+ // A ghost whose place was edited away goes to Overflow, and the next save makes that so.
+ const placed = doc.serialize(arena, .{ .body = "The tension is real. Maybe cut this. And more to come.", .ghosts = &.{.{ .at = 21, .text = "Maybe cut this. " }} }) catch unreachable;
+ load(std.mem.replaceOwned(u8, arena, placed, "\n\nThe tension", "\n\nThe whole tension") catch unreachable);
+ t.expect(std.mem.eql(u8, textOf(runAt(key_ghost, 27).?.range), "Maybe cut this. ") and !msg(bool, window, "isDocumentEdited", .{}), "a ghost keeps its place through an edit elsewhere in the file");
+ const away = std.mem.replaceOwned(u8, arena, placed, "The tension is real. And more to come.", "Something else altogether.") catch unreachable;
+ load(away);
+ t.expect(std.mem.eql(u8, objc.utf8(string(page)), "Something else altogether.") and std.mem.eql(u8, objc.utf8(string(over)), "Maybe cut this. "), "one with no place left is in Overflow, and the rest opens as usual");
+ t.expect(overflow_open and msg(bool, window, "isDocumentEdited", .{}) and std.mem.eql(u8, lab_message.items, displaced_note), "in sight, and waiting to be saved");
+ const resaved = snapshot(arena) catch unreachable;
+ const healed = std.mem.replaceOwned(u8, arena, resaved, "Something else altogether.", "The tension is real. And more to come.") catch unreachable;
+ load(healed);
+ t.expect(std.mem.eql(u8, objc.utf8(string(over)), "Maybe cut this. ") and std.mem.eql(u8, objc.utf8(string(page)), "The tension is real. And more to come.") and runAt(key_ghost, 21) == null, "once saved it stays there, though its place comes back");
+ t.expect(!msg(bool, window, "isDocumentEdited", .{}) and lab_message.items.len == 0 and std.mem.eql(u8, healed, snapshot(arena) catch unreachable), "as any stashed text does");
+ toggleOverflow(null, null, null);
+ _ = msg(bool, window, "makeFirstResponder:", .{page});
+
// Markdown changes display attributes without changing the draft or its annotations.
const raw_md = "💤 **bold _and italic_** `*code*` ~~cut~~\n__second__\n\\*literal*";
const bold_at = doc.utf16Len("💤 **");
@@ -3178,6 +3326,60 @@ fn selftest() void {
msg(void, um, "undo", .{});
t.expect(md_style.at(NSFontAttributeName, 4) == code_font and md_style.at(key_rule, 0) == null and md_style.at(NSFontAttributeName, 0) == hidden, "and Undo makes frontmatter of it again");
+ // A comment shows as a ghost does, its delimiters out of sight, and the file keeps it as it is.
+ const noted = "Live **text** <!-- aside --> here, `<!-- code -->`.\n\n<!--\n## Cut _part_\n\n```\n> said\n---\n-->\nAfter.\n";
+ const ink = struct {
+ fn at(i: usize) id {
+ return msg(id, layout, "temporaryAttribute:atCharacterIndex:effectiveRange:", .{ NSForegroundColorAttributeName, i, @as(?*NSRange, null) });
+ }
+ };
+ const aside_at = find(noted, "aside");
+ const open_at = find(noted, "<!--\n");
+ const cut_head = find(noted, "Cut");
+ const shut_at = find(noted, "-->\nAfter");
+ load(noted);
+ select(.{ .location = len() });
+ t.expect(ink.at(aside_at) == color.ghost and ink.at(cut_head) == color.ghost and ink.at(0) == null and ink.at(shut_at + 4) == null, "a comment is as dim as a ghost, and what is around it is not");
+ t.expect(md_style.at(NSFontAttributeName, aside_at - 3) == hidden and md_style.at(NSFontAttributeName, open_at) == hidden and md_style.at(NSFontAttributeName, shut_at) == hidden, "its delimiters are out of sight");
+ t.expect(md_style.at(NSFontAttributeName, cut_head) == bold and md_style.at(NSFontAttributeName, find(noted, "part")) == bold_italic and md_style.at(NSFontAttributeName, find(noted, "## Cut")) == hidden, "it is formatted");
+ t.expect(md_style.at(key_fence, find(noted, "```")) == null and md_style.at(key_quote, find(noted, "> said")) == null and md_style.at(key_rule, find(noted, "---\n-->")) == null and md_style.at(NSFontAttributeName, find(noted, "---\n-->")) == font, "but opens no code, and draws no bar or rule");
+ t.expect(md_style.at(NSFontAttributeName, find(noted, "<!-- code")) == code_font, "one in code is code");
+ select(.{ .location = cut_head });
+ t.expect(md_style.at(NSFontAttributeName, open_at) == font and md_style.at(NSFontAttributeName, shut_at) == font and ink.at(open_at) == null and md_style.at(NSFontAttributeName, aside_at - 3) == hidden, "the caret anywhere in one shows both its delimiters, and no other's");
+ select(.{ .location = shut_at + 3 });
+ t.expect(md_style.at(NSFontAttributeName, open_at) == font, "as it does against one");
+ t.expect(!msg(bool, um, "canUndo", .{}) and std.mem.eql(u8, snapshot(arena) catch unreachable, noted), "none of which is an edit, or in the file");
+ t.expect(std.mem.eql(u8, proseAround(arena, .{ .length = 4 }), "Live **text** here, `<!-- code -->`.\n") and std.mem.indexOf(u8, proseAround(arena, .{ .location = aside_at, .length = 5 }), "aside") != null, "a question about other text leaves it out");
+ stub.beginEvent();
+ insert(page, "x", .{ .location = cut_head });
+ stub.endEvent();
+ t.expect(ink.at(cut_head) == color.ghost, "what is typed in one is in it");
+ msg(void, um, "undo", .{});
+ stub.beginEvent();
+ insert(page, "", .{ .location = shut_at, .length = 3 });
+ stub.endEvent();
+ t.expect(ink.at(cut_head) == null and md_style.at(key_comment, cut_head) == null and md_style.at(NSFontAttributeName, open_at) == font and md_style.at(NSFontAttributeName, cut_head) == bold and md_style.at(key_fence, find(noted, "> said")) != null, "one that is not closed is only text, all the way back");
+ msg(void, um, "undo", .{});
+ select(.{ .location = len() });
+ t.expect(ink.at(cut_head) == color.ghost and md_style.at(NSFontAttributeName, open_at) == hidden and md_style.at(key_fence, find(noted, "> said")) == null, "and Undo makes a comment of it again");
+ select(.{ .location = cut_head + 1 });
+ ghost(null, null, null);
+ t.expect(std.mem.eql(u8, objc.utf8(string(page)), "Live **text** <!-- aside --> here, `<!-- code -->`.\n\n## Cut _part_\n\n```\n> said\n---\nAfter.\n") and runAt(key_ghost, open_at) == null, "reviving one takes its delimiters away, and their lines");
+ msg(void, um, "undo", .{});
+ t.expect(std.mem.eql(u8, objc.utf8(string(page)), noted) and ink.at(cut_head) == color.ghost, "and one Undo puts both back");
+ select(.{ .location = aside_at, .length = 12 }); // on past the end of it
+ ghost(null, null, null);
+ t.expect(std.mem.startsWith(u8, objc.utf8(string(page)), "Live **text** aside here, ") and runAt(key_ghost, 0) == null and runAt(key_ghost, aside_at) == null, "in a line, only the spaces that set it off go too, and nothing is ghosted");
+ for ([_][2][]const u8{ .{ "a<!---->b", "ab" }, .{ "a<!-- -->b", "ab" }, .{ "<!-->", "" }, .{ "<!--\r\nA\r\n-->\r\nB", "A\r\nB" }, .{ "<!--\n-->", "" }, .{ "<!--\nA\n-->", "A\n" }, .{ "<!-- A\nB -->C", "A\nBC" } }) |c| {
+ load(c[0]);
+ select(.{ .length = len() });
+ ghost(null, null, null);
+ t.expect(std.mem.eql(u8, objc.utf8(string(page)), c[1]), c[0]);
+ }
+ load("We really <!-- note --> need this today. Keep my note.");
+ landed(stub.reply(.slight, "[{\"sentence\":1,\"shortened\":\"We need this today.\",\"importance\":5}]"));
+ t.expect(runAt(key_ghost, find("We really", "really")) == null, "a cut that would run over a comment is not proposed");
+
// A line that is all one image is its picture, in a line made tall enough to hold it.
t.expect(msg(bool, fm, "createDirectoryAtPath:withIntermediateDirectories:attributes:error:", .{ path, false, @as(id, null), @as(?*id, null) }), "a folder for a piece and its picture");
const bitmap = msg(id, msg(id, objc.class("NSBitmapImageRep"), "alloc", .{}), "initWithBitmapDataPlanes:pixelsWide:pixelsHigh:bitsPerSample:samplesPerPixel:hasAlpha:isPlanar:colorSpaceName:bytesPerRow:bitsPerPixel:", .{
diff --git a/src/markdown.zig b/src/markdown.zig
index 253cd94..b4d2ab6 100644
--- a/src/markdown.zig
+++ b/src/markdown.zig
@@ -58,12 +58,12 @@ pub const Parser = struct {
continue;
}
const at = i;
- i = runEnd(text, at, c);
+ i = runEnd(u16, text, at, c);
const width = i - at;
if (c == '`') {
if (width > ticks.len) continue;
// Each cursor moves only forward, even when a backtick run is unmatched.
- const close = nextTicks(text, @max(i, ticks[width - 1]), width);
+ const close = nextTicks(u16, text, @max(i, ticks[width - 1]), width);
ticks[width - 1] = close;
if (close == text.len or close == i) continue;
const first = p.marks.items.len;
@@ -150,13 +150,13 @@ pub const front: u32 = 1;
/// and character; it is left as the next line will find it. An unclosed block runs to the end.
/// Frontmatter is a block too, fenced by its delimiters. Only the caller can know that the
/// piece's first line `opens_front`: that takes a line further on to close it.
-pub fn fenceLine(line: []const u16, open: *u32, opens_front: bool) Line {
+pub fn fenceLine(comptime T: type, line: []const T, open: *u32, opens_front: bool) Line {
if (opens_front) {
open.* = front;
return .fence;
}
if (open.* == front) {
- if (!frontDelimiter(u16, line, false)) return .code;
+ if (!frontDelimiter(T, line, false)) return .code;
open.* = 0;
return .fence;
}
@@ -165,16 +165,16 @@ pub fn fenceLine(line: []const u16, open: *u32, opens_front: bool) Line {
if (i < line.len and (line[i] == '`' or line[i] == '~')) {
const c = line[i];
const tilde = @intFromBool(c == '~');
- const stop = runEnd(line, i, c);
+ const stop = runEnd(T, line, i, c);
const width: u32 = @intCast(stop - i);
const rest = line[stop..];
if (open.* == 0) {
// A backtick fence's info string has no backticks: that would be inline code.
- if (width >= 3 and (c == '~' or std.mem.indexOfScalar(u16, rest, '`') == null)) {
+ if (width >= 3 and (c == '~' or std.mem.indexOfScalar(T, rest, '`') == null)) {
open.* = width << 1 | tilde;
return .fence;
}
- } else if (open.* & 1 == tilde and width >= open.* >> 1 and std.mem.indexOfNone(u16, rest, &.{ ' ', '\t', '\r', '\n' }) == null) {
+ } else if (open.* & 1 == tilde and width >= open.* >> 1 and std.mem.indexOfNone(T, rest, &.{ ' ', '\t', '\r', '\n' }) == null) {
open.* = 0;
return .fence;
}
@@ -182,6 +182,71 @@ pub fn fenceLine(line: []const u16, open: *u32, opens_front: bool) Line {
return if (open.* == 0) .text else .code;
}
+pub const Span = struct { lo: usize, hi: usize };
+
+pub const comment_open = 4; // how long "<!--" is,
+pub const comment_close = 3; // and "-->"
+
+/// The HTML comments of a whole piece, in order. What is not surely a comment is prose: to
+/// hide text that Markdown then publishes would be the worse mistake. So one that starts a
+/// line may run over any others, but elsewhere (and in a list or a quote) it has to close on
+/// its own line; and code, frontmatter and what is never closed have none. The file's own
+/// records, if they could not be read, stay in sight too.
+pub fn Comments(comptime T: type) type {
+ return struct {
+ text: []const T,
+ front: bool, // it opens with frontmatter: see `fenceLine`
+ at: usize = 0,
+ open: u32 = 0,
+
+ pub fn next(it: *@This()) ?Span {
+ const text = it.text;
+ lines: while (it.at < text.len) {
+ const stop = if (std.mem.indexOfScalarPos(T, text, it.at, '\n')) |nl| nl + 1 else text.len;
+ var i = it.at;
+ if (starts(text, i) and fenceLine(T, text[i..stop], &it.open, it.front and i == 0) != .text) i = stop;
+ while (i < stop) switch (text[i]) {
+ '\\' => i += 2,
+ '`' => {
+ const body = runEnd(T, text[0..stop], i, '`');
+ const close = nextTicks(T, text[0..stop], body, body - i);
+ i = if (close == stop) body else close + (body - i);
+ },
+ '<' => {
+ const lo = i;
+ i += 1;
+ if (!has(text[lo..], "<!--")) continue;
+ // "<!-->" is a whole comment.
+ const close = find(text[0..if (starts(text, lo)) text.len else stop], lo + 2, "-->") orelse continue;
+ it.at = close + comment_close;
+ for ([_][]const u8{ "<!-- write_away ", "<!-- overflow\n(", "<!-- overflow -->" }) |record| if (has(text[lo..], record)) continue :lines;
+ return .{ .lo = lo, .hi = it.at };
+ },
+ else => i += 1,
+ };
+ it.at = stop;
+ }
+ return null;
+ }
+
+ fn starts(text: []const T, i: usize) bool {
+ return i == 0 or text[i - 1] == '\n';
+ }
+
+ fn has(text: []const T, what: []const u8) bool {
+ if (text.len < what.len) return false;
+ for (text[0..what.len], what) |a, b| if (a != b) return false;
+ return true;
+ }
+
+ fn find(text: []const T, from: usize, what: []const u8) ?usize {
+ var i = from;
+ while (i + what.len <= text.len) : (i += 1) if (has(text[i..], what)) return i;
+ return null;
+ }
+ };
+}
+
fn blanks(comptime T: type) []const T {
return &.{ ' ', '\t', '\r', '\n' };
}
@@ -261,20 +326,20 @@ fn punctuation(c: u16) bool {
};
}
-fn runEnd(text: []const u16, start: usize, c: u16) usize {
+fn runEnd(comptime T: type, text: []const T, start: usize, c: T) usize {
var i = start + 1;
while (i < text.len and text[i] == c) i += 1;
return i;
}
-fn nextTicks(text: []const u16, start: usize, width: usize) usize {
+fn nextTicks(comptime T: type, text: []const T, start: usize, width: usize) usize {
var i = start;
while (i < text.len) {
if (text[i] != '`') {
i += 1;
continue;
}
- const stop = runEnd(text, i, '`');
+ const stop = runEnd(T, text, i, '`');
if (stop - i == width) return i;
i = stop;
}
@@ -298,7 +363,7 @@ test "fences open, hold what looks like Markdown, and close only on their own ki
.{ L("~~~ a`b\n"), .fence },
.{ L("unclosed"), .code },
};
- for (lines) |l| try std.testing.expectEqual(l[1], fenceLine(l[0], &open, false));
+ for (lines) |l| try std.testing.expectEqual(l[1], fenceLine(u16, l[0], &open, false));
try std.testing.expectEqual(@as(u32, 3 << 1 | 1), open);
}
@@ -313,7 +378,7 @@ test "frontmatter is a block between its delimiters, and a rule is not one of th
.{ L("...\r\n"), .fence },
.{ L("---\n"), .text },
};
- for (lines, 0..) |l, i| try std.testing.expectEqual(l[1], fenceLine(l[0], &open, i == 0));
+ for (lines, 0..) |l, i| try std.testing.expectEqual(l[1], fenceLine(u16, l[0], &open, i == 0));
try std.testing.expectEqual(@as(u32, 0), open);
try std.testing.expect(frontDelimiter(u8, "---\n", true) and !frontDelimiter(u8, "...\n", true) and !frontDelimiter(u8, " ---", false));
for ([_][]const u16{ L("---\n"), L(" ----- \r\n") }) |line| try std.testing.expectEqual(Rule.hyphens, rule(line));
@@ -321,6 +386,36 @@ test "frontmatter is a block between its delimiters, and a rule is not one of th
for ([_][]const u16{ L(""), L("\n"), L("--"), L("--- a\n"), L(" ---\n"), L("\t---"), L("**_"), L("-*-\n"), L("* * item"), L("===") }) |line| try std.testing.expectEqual(Rule.no, rule(line));
}
+test "comments: one that starts a line runs on, and nothing Markdown might publish is one" {
+ const cases = [_]struct { []const u8, []const []const u8 }{
+ .{ "a\n<!--\n# b\n\n```\n-->\nc <!-- d --> e<!--f--><!-->\n", &.{ "<!--\n# b\n\n```\n-->", "<!-- d -->", "<!--f-->", "<!-->" } },
+ .{ "<!-- a <!-- b --> c -->", &.{"<!-- a <!-- b -->"} },
+ // Only its own line can close one in a paragraph, a list or a quote.
+ .{ "a <!-- b\n\nc -->\n- <!-- d\ne -->\n> <!-- f -->\n <!-- g\n-->", &.{"<!-- f -->"} },
+ .{ "```\n<!-- a -->\n```\n`<!-- b -->` ``c ` <!-- d -->`` ` <!-- e -->", &.{"<!-- e -->"} },
+ .{ "\\<!-- a --> \\\\<!-- b -->\n<!-- c\n", &.{"<!-- b -->"} },
+ .{ "---\nx: 1\n<!-- a -->\n---\n<!-- b -->", &.{"<!-- b -->"} },
+ .{ "<!-- overflow\n(a)-->\n<!-- write_away {} -->\n\n<!-- overflow -->\n<!-- overflowing -->", &.{"<!-- overflowing -->"} },
+ };
+ for (cases) |c| {
+ const front_matter = std.mem.startsWith(u8, c[0], "---");
+ var it: Comments(u8) = .{ .text = c[0], .front = front_matter };
+ for (c[1]) |want| {
+ const got = it.next().?;
+ try std.testing.expectEqualStrings(want, c[0][got.lo..got.hi]);
+ }
+ try std.testing.expectEqual(@as(?Span, null), it.next());
+
+ // The page reads the same ones, in UTF-16.
+ var units: [256]u16 = undefined;
+ const n = try std.unicode.utf8ToUtf16Le(&units, c[0]);
+ var wide: Comments(u16) = .{ .text = units[0..n], .front = front_matter };
+ it = .{ .text = c[0], .front = front_matter };
+ while (it.next()) |want| try std.testing.expectEqual(want, wide.next().?);
+ try std.testing.expectEqual(@as(?Span, null), wide.next());
+ }
+}
+
test "links: the text is marked, the target is not read, and an image is left alone" {
const alloc = std.testing.allocator;
var p: Parser = .{};