From 205b1d26b5be40424eace945a73867bdfefe90ce Mon Sep 17 00:00:00 2001 From: t Date: Wed, 25 Nov 2026 11:25:00 -0700 Subject: 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. --- README.md | 31 ++-- src/doc.zig | 481 ++++++++++++++++++++++++++++++++++++++++++++++++------- src/ghost_io.zig | 7 +- src/lab.zig | 30 +++- src/main.zig | 232 +++++++++++++++++++++++++-- src/markdown.zig | 119 ++++++++++++-- 6 files changed, 797 insertions(+), 103 deletions(-) diff --git a/README.md b/README.md index a48e577..2a382cd 100644 --- a/README.md +++ b/README.md @@ -52,7 +52,7 @@ write_away "my draft.md" # open an existing file | ← → ↑ ↓ with the pointer on underlined text | Flip through its versions. Typing gives the arrows back to the caret. | | Delete with the pointer on underlined text | Throw out the version showing. | | Ctrl+] and Ctrl+[ | Flip the group the caret is in, without the pointer. | -| Ctrl+/ | Ghost the selection or the word. On ghosted text, revive it. | +| Ctrl+/ | Ghost the selection or the word. On ghosted text or an HTML comment, revive it. | | Ctrl+Shift+X | Stash the selection, or the paragraph, in Overflow. | | Ctrl+Shift+D | Show or hide Overflow. Drag its left divider to resize it; closing and reopening keeps the width. | | Ctrl+Return | Move Overflow's selection, or its paragraph, to the caret in the page. | @@ -73,6 +73,8 @@ Fenced code blocks (three or more backticks or tildes, with an optional language YAML frontmatter is shown the same way, with its `---` lines as the fences. It counts only when the first line is `---` and a later line of `---` or `...` closes it; its contents are not parsed. +HTML comments (``) look like ghosts: dimmed, formatted, with the delimiters hidden until the caret is in the comment or against it. Saving leaves them where they are, as they are. Ctrl+/ on one takes its delimiters away, which publishes the text; a selection that touches any comment or ghost brings all of them back rather than ghosting the rest. A comment that starts a line can run over many, blank ones included. Anywhere else, including indented or in a list or a quote, it must close on its own line. What is never closed, or stands in code or frontmatter, stays as written. So do Write_Away’s own comments when it can’t use them. + ## The Lab Choose **Lab** in the bottom bar or press **Ctrl+Shift+L** (also in the Write menu); the shortcut leaves read mode if needed. During a review, use **Ctrl+Shift+N** for Next, **Ctrl+Shift+K** for Keep, **Ctrl+Shift+P** for Apply rest, and **Ctrl+Shift+O** for Discard/Original. The in-window chooser has six editing passes and a row of trim strengths. Use the arrow keys to move, Return to choose, or Escape to go back to the draft. A pass can mark weak, long, or convoluted sentences, changes of tone, or filler. Punctuation and typo fixes are proposals until you apply them. **Next** visits the next passage; **Keep** leaves it alone. @@ -81,7 +83,7 @@ The four trims aim for about 10%, 20%, 30%, or 50%. They ghost proposed cuts usi ## Inference (optional) -Choose **Write_Away → Inference…**, or configure it on your first `??`. For alternatives, the request sends the target, its paragraph and the variants already tried. Choosing a Lab pass sends the numbered draft text (including ghosted words, not Overflow or unselected alternatives). Ordinary editing and saving make no requests. The app asks for five word alternatives or three longer ones. A robot marker identifies suggestions. Anthropic Messages, OpenAI Chat Completions, OpenAI Responses and Google Interactions are available via libpantograph. Use HTTPS for remote endpoints. +Choose **Write_Away → Inference…**, or configure it on your first `??`. For alternatives, the request sends the target, its paragraph and the variants already tried. HTML comments in the paragraph are left out, unless the target is in one or runs over one. Choosing a Lab pass sends the numbered draft text (including ghosted words, not HTML comments, Overflow or unselected alternatives). Ordinary editing and saving make no requests. The app asks for five word alternatives or three longer ones. A robot marker identifies suggestions. Anthropic Messages, OpenAI Chat Completions, OpenAI Responses and Google Interactions are available via libpantograph. Use HTTPS for remote endpoints. The key is **not in Keychain**: it is stored unencrypted in `~/Library/Application Support/Write_Away/inference.json`, mode `0600`. Save an empty key to remove it. The other settings live in the `local.write-away` preferences domain. When upgrading from a differently named build, re-enter your inference settings or copy your existing `inference.json` into this directory with mode `0600`. @@ -90,7 +92,7 @@ The key is **not in Keychain**: it is stored unencrypted in `~/Library/Applicati ```markdown - + # A draft @@ -114,7 +116,7 @@ closes it, and the rest of the draft follows their blank line. --- title: A draft --- - + # A draft @@ -127,11 +129,22 @@ go first as before. Files record UTF-8 byte offsets into the restored editor body. While editing, ghosts are attributes on the text itself; Save computes fresh offsets. A fully ghosted alternative stays ghosted when swapped. If a replacement crosses a ghost boundary, revive the ghosted part first: Write_Away won’t guess which words in another version should be hidden. -If a file has ghosts and its visible -bytes change outside Write_Away (even just a newline), Write_Away opens the original -Markdown as-is, with its comments intact, rather than guessing where to put the ghosts. -Without ghosts, alternatives can still follow matching text after an outside edit. -Legacy Overflow trailers and v1 records are supported. For drafts saved under an earlier app name, change only the identifier on the metadata comment to `write_away` before opening; leave its JSON and the draft text unchanged. +The file can be edited elsewhere. Each ghost and each group of alternatives is saved with up +to 32 bytes of the text on either side, and opens where those still match: at its old offset, +or else in the one place that has both sides, or enough of either to have been the only such +text when it was saved. A group’s showing version is part of what has to match. + +A ghost with no clear place opens in Overflow instead. Overflow opens to show it and the piece +counts as changed; the next save makes the move permanent, even if the old surroundings come +back later. Until then the file is untouched. A group with no clear place, or that shared text +with such a ghost, is dropped without a word: the page keeps what the file says, and the next +save forgets the other versions. + +v1 and v2 files still open, and save as v3, which earlier releases show as plain +Markdown. v2 didn’t save surroundings, so if its visible bytes were changed elsewhere all its +ghosts open in Overflow, and a group follows its showing version only to the same offset or the +only place it occurs. v1 files whose ghosts no longer fit, and any file whose comments are +malformed, open as they are. Legacy Overflow trailers are supported. For drafts saved under an earlier app name, change only the identifier on the metadata comment to `write_away` before opening; leave its JSON and the draft text unchanged. ## Not here yet 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 = ""; // legacy const overflow_open = " leaked)-->\n\nBody\n", "\n\n\nBody\n", "\n\n\nBody\n", - "\n\n\nBody\n", + "\n\n\nBody\n", "Body\n\n\n\n\n", "Text.\n\n\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\nNotes\n", meta_open, "{\"v\":1,", first_group, bad, "]}", meta_close })); - try expectRaw(a, try mem.concat(a, u8, &.{ "\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\nNotes\n", meta_open, "{\"v\":1,", first_group, bad, "]}", meta_close }), + try mem.concat(a, u8, &.{ "\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"), - "\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, "\n\nBody"); + + // [was] is a ghost, and 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(); + // 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 .", "So, the end of the story is the end.", "So, the end of the story is the ." }, + .{ "The of the story is the end.", "So, the end of the tale is the end.", "So, the of the tale is the end." }, + .{ "The of the story is the end.", "At the end of a story comes the end.", "At the of a story comes the end." }, + // Its own was rewritten, and the other is not it. + .{ "The of the story is the end.", "The close of the story is the end.", "The close of the story is the end." }, + .{ "One here.", "One more tension there, and a tension here.", "One more tension there, and a here." }, + .{ "", "More. All of it.", "More. " }, + .{ "", "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 thing.\n\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** here, ``.\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, "\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, "`.\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** here, ``.\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{ .{ "ab", "ab" }, .{ "ab", "ab" }, .{ "", "" }, .{ "\r\nB", "A\r\nB" }, .{ "", "" }, .{ "", "A\n" }, .{ "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 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 "" + +/// 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..], "" 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{ "" }) |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\nc e\n", &.{ "", "", "", "" } }, + .{ " c -->", &.{""} }, + // Only its own line can close one in a paragraph, a list or a quote. + .{ "a \n- \n> \n ", &.{""} }, + .{ "```\n\n```\n`` ``c ` `` ` ", &.{""} }, + .{ "\\ \\\\\n"} }, + .{ "---\nx: 1\n\n---\n", &.{""} }, + .{ "\n\n\n\n", &.{""} }, + }; + 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 = .{}; -- cgit v1.3