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. --- src/main.zig | 232 +++++++++++++++++++++++++++++++++++++++++++++++++++++++---- 1 file changed, 217 insertions(+), 15 deletions(-) (limited to 'src/main.zig') 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:", .{ -- cgit v1.3