summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authort <t@tjp.lol>2026-11-24 22:30:27 -0700
committert <t@tjp.lol>2026-11-24 22:45:56 -0700
commit17e3a3589d8482f545bb5956a4f7ea01c646698f (patch)
treea828c6dd2138e7cb9e4b1bfa810e89f50ab5eed9
parent3594d230f5368d4200e590654aad040432bee82e (diff)
Expand writing app interface and add Markdown support
-rw-r--r--README.md11
-rw-r--r--build.zig14
-rw-r--r--src/lab_ui.zig514
-rw-r--r--src/main.zig509
-rw-r--r--src/markdown.zig217
5 files changed, 1122 insertions, 143 deletions
diff --git a/README.md b/README.md
index f626388..4d40581 100644
--- a/README.md
+++ b/README.md
@@ -24,6 +24,8 @@ zig build run -- piece.md # open a piece, or start one at that path
zig build test # the document model, then the app driven with no window
```
+A normal launch reopens the last file you had open, using its current contents on disk. On the first launch, after **File → New**, or if the file can’t be read, you get an empty **Untitled** draft instead. Opening a file explicitly takes precedence. Unsaved text is not restored.
+
## Using it
| Keys | What happens |
@@ -41,11 +43,15 @@ zig build test # the document model, then the app driven with no
| Ctrl+Shift+R, or click the word count | Put the tools away and read. |
| ⌘N ⌘O ⌘S ⇧⌘S ⌘Z ⇧⌘Z | New, Open, Save, Save As, Undo, Redo. |
-Right-click the page for alternatives, AI alternatives, ghost/revive, or Overflow. While the panel is open, the surrounding text dims. A word’s versions have a wavy violet underline; a sentence’s have a pink one. Paragraphs get a bar in the margin. Dots show the active version, and a lower tick marks a return to the version you started on. Flipping a word adjusts a preceding *a/an* where the pronunciation can be guessed. Heading hashes stay in the file, not on the screen.
+Right-click the page for alternatives, AI alternatives, ghost/revive, or Overflow. While the panel is open, the surrounding text dims. A word’s versions have a wavy violet underline; a sentence’s have a pink one. Paragraphs get a bar in the margin. Dots show the active version, and a lower tick marks a return to the version you started on. Flipping a word adjusts a preceding *a/an* where the pronunciation can be guessed. Heading hashes (`#` through `######`) appear while the caret is on that heading so you can edit its level. They hide again when the caret leaves.
+
+Matched `**strong**`, `_emphasis_`, `***both***`, `~~strikethrough~~`, and inline code spans render on the page. Move the caret inside a span to see and edit its delimiters. Saving keeps the Markdown source, not a rich-text conversion.
+
+Fenced code blocks (three or more backticks or tildes, with an optional language) sit on a darker panel, and nothing inside one is read as Markdown. The fence lines show while the caret is in the block. A block with no closing fence runs to the end of the piece.
## The Lab
-Choose **Lab** in the bottom bar. 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.
+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.
The four trims aim for about 10%, 20%, 30%, or 50%. They ghost proposed cuts using the same ghosts you can make yourself. **Save** at that point to publish without the ghosted words and still recover them in Write_Away. **Original** revives the pass’s remaining proposals, not your manual ghosts. **Apply rest** removes the remaining cuts from the editor too; Undo brings them back. Editing the draft closes the review, leaving existing ghosts in place.
@@ -93,6 +99,7 @@ A separate Markdown view, source-stripped public export, sharing/posting, deleti
## The code
- `src/doc.zig` and `src/ghost_io.zig`: variants, recoverable ghosts, and the Markdown format.
+- `src/markdown.zig`: matches inline formatting delimiters in the editor’s UTF-16 text.
- `src/lab.zig` and `src/lab_ui.zig`: map model suggestions to draft passages and present them for review.
- `src/main.zig`: the app. The page is an `NSTextView`; two custom text attributes mark
groups and ghosts, and everything drawn is derived from them.
diff --git a/build.zig b/build.zig
index 2fe0069..0c52f42 100644
--- a/build.zig
+++ b/build.zig
@@ -25,17 +25,13 @@ pub fn build(b: *std.Build) void {
if (b.args) |args| run.addArgs(args);
b.step("run", "Run the editor (zig build run -- file.md)").dependOn(&run.step);
- // The checks: the document model on its own, then the real app driven through its
- // commands with no window shown.
- const unit = b.addTest(.{ .root_module = b.createModule(.{
- .root_source_file = b.path("src/doc.zig"),
- .target = target,
- }) });
+ // Format/model checks plus the real app driven through its commands with no window shown.
const smoke = b.addRunArtifact(exe);
smoke.setEnvironmentVariable("WRITE_AWAY_SELFTEST", "1");
const test_step = b.step("test", "Run the checks");
- const lab_tests = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("src/lab.zig"), .target = target }) });
- test_step.dependOn(&b.addRunArtifact(lab_tests).step);
- test_step.dependOn(&b.addRunArtifact(unit).step);
+ for ([_][]const u8{ "src/doc.zig", "src/markdown.zig", "src/lab.zig", "src/lab_ui.zig" }) |path| {
+ const unit = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path(path), .target = target }) });
+ test_step.dependOn(&b.addRunArtifact(unit).step);
+ }
test_step.dependOn(&smoke.step);
}
diff --git a/src/lab_ui.zig b/src/lab_ui.zig
index a66513a..c92c2c2 100644
--- a/src/lab_ui.zig
+++ b/src/lab_ui.zig
@@ -1,6 +1,5 @@
-//! The Lab's native controls: the strip along the bottom (Save, Open, Overflow, Lab), the
-//! menu the Lab button opens, and the card shown while a trim or pass is being reviewed.
-//! Nothing here knows what a pass does: every control targets the controller's selectors.
+//! The Lab's bottom strip, in-window chooser and guide, and review card.
+//! Nothing here knows what a pass does: the controls invoke the controller's selectors.
const std = @import("std");
const objc = @import("objc.zig");
const msg = objc.msg;
@@ -11,9 +10,11 @@ const NSPoint = objc.NSPoint;
const NSSize = objc.NSSize;
extern const NSViewFrameDidChangeNotification: id;
+extern const NSWindowDidResignKeyNotification: id;
+extern const NSFontAttributeName: id;
+extern const NSForegroundColorAttributeName: id;
/// The trim level on show, as its `labPass:` tag (6…9), or null when nothing is proposed.
-/// The menu ticks it; set it whenever a proposal starts or ends.
pub var pending: ?u8 = null;
const strip_h = 40; // the bar the word count lives in (main's status_h)
@@ -56,12 +57,9 @@ const passes = [_]struct { title: []const u8, tag: isize }{
.{ .title = "Mark words that don’t fit the tone", .tag = 4 },
.{ .title = "Mark hedges and filler", .tag = 5 },
};
-const trims = [_]struct { title: []const u8, tag: isize }{
- .{ .title = "Slight trim ~10%", .tag = 6 },
- .{ .title = "Tighten more ~20%", .tag = 7 },
- .{ .title = "Even sharper ~30%", .tag = 8 },
- .{ .title = "Cut in half ~50%", .tag = 9 },
-};
+const trims = [_][]const u8{ "Original", "Slight trim", "Tighten more", "Even sharper", "Cut in half" };
+const percents = [_][]const u8{ "", "~10%", "~20%", "~30%", "~50%" };
+const privacy = "Your draft is sent only when you pick a pass.";
const guide =
\\Each idea asks the AI about your draft and only marks or fades words. It never rewrites.
@@ -158,7 +156,7 @@ pub fn state(dirty: bool, overflow: bool) void {
fn tint() void {
for (bar, tracking, 0..) |b, area, i| {
if (b == null) continue;
- const active = (i == 0 and saved_dirty) or (i == 2 and overflow_open) or (i == 3 and has_note);
+ const active = (i == 0 and saved_dirty) or (i == 2 and overflow_open) or (i == 3 and (has_note or (chooser_open and writing_at == null)));
msg(void, b, "setContentTintColor:", .{if (hovering != null and hovering == area) bright else if (active) accent else ink});
}
}
@@ -180,9 +178,13 @@ pub fn update(tools_on: bool, note: []const u8, review_on: bool, can_apply: bool
if (content == null) return;
tools = tools_on;
review = review_on;
- if (!tools) hovering = null;
+ if (!tools) {
+ closePanel();
+ hovering = null;
+ }
has_note = note.len != 0;
tint();
+ tintPanel();
msg(void, note_field, "setToolTip:", .{objc.str(note)});
msg(void, hint_field, "setStringValue:", .{objc.str(if (!review) "" else if (can_apply) "Keep skips this change · Apply rest edits the draft" else "Next visits a mark · Keep clears it")});
msg(void, note_field, "setStringValue:", .{objc.str(note)});
@@ -190,56 +192,458 @@ pub fn update(tools_on: bool, note: []const u8, review_on: bool, can_apply: bool
relayout();
}
-// --- The Lab menu ---------------------------------------------------------------------------
+// --- The Lab chooser ------------------------------------------------------------------------
+
+const panel_w = 620;
+const panel_margin = 10;
+const panel_bottom = 50; // just above the trigger, so LAB can also close it
+const row_h = 32.5;
+const trim_h = 44;
+const trim_gap = 4;
+const first_trim = 1 + passes.len;
+const done_index = first_trim + trims.len;
-fn item(menu: id, title: []const u8, action: [*:0]const u8, tag: isize, on: bool, target: id) void {
- const it = msg(id, msg(id, objc.class("NSMenuItem"), "alloc", .{}), "initWithTitle:action:keyEquivalent:", .{ objc.str(title), if (target != null) objc.sel(action) else null, objc.str("") });
- msg(void, it, "setTarget:", .{target});
- msg(void, it, "setTag:", .{tag});
- msg(void, it, "setEnabled:", .{target != null}); // no target: a note, not a command
- msg(void, it, "setState:", .{@as(isize, if (on) 1 else 0)});
- msg(void, menu, "addItem:", .{it});
- msg(void, it, "release", .{});
+var chooser_open = false;
+var guide_open = false;
+var shield: id = null;
+var panel: id = null;
+var panel_scroll: id = null;
+var paper: id = null;
+var panel_btn: [done_index + 1]id = .{null} ** (done_index + 1);
+var rules: [2]id = .{ null, null };
+var privacy_note: id = null;
+var guide_text: id = null;
+var panel_font: id = null;
+var compact_font: id = null;
+var surface: id = null;
+var edge: id = null;
+var highlight: id = null;
+var draft_view: id = null;
+var return_focus: id = null;
+var click_focus: id = null;
+var hover_row: id = null;
+var trim_cols: usize = trims.len;
+
+const writing_actions = [_][*:0]const u8{ "alternative:", "aiAlternative:", "ghost:", "stash:" };
+const writing_keys = [_][]const u8{ "a", "g", "/", "x" };
+const writing_shortcuts = [_][]const u8{ "Ctrl+Shift+A", "Ctrl+Shift+G", "Ctrl+/", "Ctrl+Shift+X" };
+var writing_btn: [4]id = .{null} ** 4;
+var writing_at: ?NSPoint = null;
+
+fn rect(x: f64, y: f64, w: f64, h: f64) NSRect {
+ return .{ .origin = .{ .x = x, .y = y }, .size = .{ .width = w, .height = h } };
}
-fn rule(menu: id) void {
- msg(void, menu, "addItem:", .{msg(id, objc.class("NSMenuItem"), "separatorItem", .{})});
+fn number(i: usize) f64 {
+ return @floatFromInt(i);
}
-/// The Lab's menu, popped up at `sender` (the Lab button if null).
-pub fn openMenu(sender: id) void {
- if (content == null) return;
- const menu = msg(id, msg(id, objc.class("NSMenu"), "alloc", .{}), "initWithTitle:", .{objc.str("Lab")});
- defer msg(void, menu, "release", .{});
- msg(void, menu, "setAutoenablesItems:", .{false});
+fn panelWindow() id {
+ return msg(id, content, "window", .{});
+}
+
+fn triggerMouseDown(self: id, _: SEL, event: id) callconv(.c) void {
+ click_focus = msg(id, panelWindow(), "firstResponder", .{});
+ defer click_focus = null;
+ objc.msgSuper(void, self, "NSButton", "mouseDown:", .{event});
+}
+
+pub fn togglePanel() void {
+ if (chooser_open) {
+ if (writing_at == null) return closePanel();
+ closePanel();
+ }
+ if (content == null or !tools) return;
+ guide_open = false;
+ openPanel(click_focus);
+ tint();
+}
+
+pub fn canOpenWritingMenu() bool {
+ return content != null and tools and !chooser_open;
+}
+
+pub fn openWritingMenu(point: NSPoint, titles: [4][]const u8) void {
+ writing_at = msg(NSPoint, content, "convertPoint:fromView:", .{ point, @as(id, null) });
+ for (writing_btn, titles) |b, title| msg(void, b, "setTitle:", .{objc.str(title)});
+ openPanel(null);
+}
+
+fn openPanel(prior: id) void {
+ const win = panelWindow();
+ return_focus = prior orelse msg(id, win, "firstResponder", .{});
+ if (return_focus == bar[3] or return_focus == win) return_focus = draft_view;
+ chooser_open = true;
+ msg(void, panel_scroll, "setHidden:", .{writing_at != null});
+ for (writing_btn) |b| msg(void, b, "setHidden:", .{writing_at == null});
+ msg(void, msg(id, panel, "layer", .{}), "setCornerRadius:", .{@as(f64, if (writing_at != null) 12 else 8)});
+ msg(void, shield, "setHidden:", .{false});
+ layoutPanel();
+ focusRow(0);
+}
+
+fn closePanel() void {
+ if (!chooser_open) return;
+ const win = panelWindow();
+ const first = msg(id, win, "firstResponder", .{});
+ const owns_focus = msg(bool, first, "isKindOfClass:", .{objc.class("NSView")}) and msg(bool, first, "isDescendantOf:", .{shield});
+ const was_writing = writing_at != null;
+ chooser_open = false;
+ writing_at = null;
+ hover_row = null;
+ msg(void, shield, "setHidden:", .{true});
+ if (owns_focus) {
+ const sel = if (was_writing) msg(objc.NSRange, draft_view, "selectedRange", .{}) else objc.NSRange{};
+ const available = msg(id, return_focus, "window", .{}) == win and !msg(bool, return_focus, "isHiddenOrHasHiddenAncestor", .{});
+ if (!available or !msg(bool, win, "makeFirstResponder:", .{return_focus})) {
+ _ = msg(bool, win, "makeFirstResponder:", .{draft_view});
+ }
+ if (was_writing and !std.meta.eql(sel, msg(objc.NSRange, draft_view, "selectedRange", .{})))
+ msg(void, draft_view, "setSelectedRange:", .{sel});
+ }
+ return_focus = null;
+ tint();
+}
+
+fn dismiss(_: id, _: SEL, _: id) callconv(.c) void {
+ closePanel();
+}
+
+fn panelIndex(b: id) usize {
+ return std.mem.indexOfScalar(id, &panel_btn, b).?;
+}
+
+fn choose(_: id, _: SEL, sender: id) callconv(.c) void {
+ if (!chooser_open) return;
+ if (writing_at != null) {
+ const i = std.mem.indexOfScalar(id, &writing_btn, sender) orelse return;
+ closePanel();
+ return msg(void, ctl, writing_actions[i], .{sender});
+ }
+ const i = panelIndex(sender);
+ if (i == 0) {
+ guide_open = true;
+ hover_row = null;
+ layoutPanel();
+ focusRow(done_index);
+ return;
+ }
+ closePanel();
+ if (i == done_index) return;
+ if (i == first_trim) return msg(void, ctl, "labOriginal:", .{sender});
+ msg(void, ctl, "labPass:", .{sender});
+}
+
+fn focusRow(i: usize) void {
+ const b = if (writing_at != null) writing_btn[i] else panel_btn[i];
+ _ = msg(bool, panelWindow(), "makeFirstResponder:", .{b});
+ _ = msg(bool, b, "scrollRectToVisible:", .{msg(NSRect, b, "bounds", .{})});
+ tintPanel();
+}
+
+fn acceptsFocus(_: id, _: SEL) callconv(.c) bool {
+ return true;
+}
+
+fn panelKeys(self: id, _: SEL, event: id) callconv(.c) void {
+ const mods = msg(usize, event, "modifierFlags", .{});
+ const code = msg(u16, event, "keyCode", .{});
+ if (mods & (0x40000 | 0x80000 | 0x100000) == 0) { // Control, Option, Command
+ hover_row = null;
+ switch (code) {
+ 53 => return closePanel(), // Escape
+ 36, 49, 76 => return msg(void, self, "performClick:", .{self}), // Return, Space, keypad Enter
+ else => {},
+ }
+ if (writing_at != null) {
+ const i = std.mem.indexOfScalar(id, &writing_btn, self).?;
+ const n = writing_btn.len;
+ switch (code) {
+ 123, 126 => return focusRow((i + n - 1) % n),
+ 124, 125 => return focusRow((i + 1) % n),
+ 48 => return focusRow((i + if (mods & 0x20000 != 0) n - 1 else @as(usize, 1)) % n),
+ else => {},
+ }
+ } else switch (code) {
+ 48, 123...126 => {
+ if (guide_open) return focusRow(done_index);
+ const i = panelIndex(self);
+ const next = switch (code) {
+ 48 => if (mods & 0x20000 != 0) (i + done_index - 1) % done_index else (i + 1) % done_index, // Tab
+ 123 => if (i == 0) done_index - 1 else i - 1,
+ 124 => (i + 1) % done_index,
+ 125 => if (i < first_trim) i + 1 else if (i + trim_cols < done_index) i + trim_cols else 0,
+ 126 => if (i == 0) done_index - 1 else if (i < first_trim) i - 1 else if (i >= first_trim + trim_cols) i - trim_cols else first_trim - 1,
+ else => unreachable,
+ };
+ return focusRow(next);
+ },
+ else => {},
+ }
+ }
+ objc.msgSuper(void, self, "NSButton", "keyDown:", .{event});
+}
+
+fn cg(color: id) id {
+ return msg(id, color, "CGColor", .{});
+}
+
+fn activeTrim(i: usize) bool {
+ if (i < first_trim or i >= done_index) return false;
+ return if (pending) |p| i == @as(usize, p) + 2 else i == first_trim;
+}
+
+fn tintPanel() void {
+ if (!chooser_open) return;
+ if (writing_at != null) {
+ for (writing_btn) |b| msg(void, b, "setNeedsDisplay:", .{true});
+ return;
+ }
+ for (panel_btn, 0..) |b, i| {
+ msg(void, b, "setNeedsDisplay:", .{true});
+ if (i >= first_trim and i < done_index) msg(void, b, "setAccessibilityValue:", .{objc.str(if (activeTrim(i)) "Selected" else "Not selected")});
+ }
+}
+
+fn panelEnter(self: id, _: SEL, _: id) callconv(.c) void {
+ if (writing_at != null) return focusRow(std.mem.indexOfScalar(id, &writing_btn, self) orelse return);
+ hover_row = self;
+ tintPanel();
+}
+
+fn panelExit(self: id, _: SEL, _: id) callconv(.c) void {
+ if (hover_row != self) return;
+ hover_row = null;
+ tintPanel();
+}
+
+const Align = enum { left, center, right };
+fn drawString(title: id, font: id, color: id, box: NSRect, alignment: Align) void {
+ const attrs = msg(id, objc.class("NSDictionary"), "dictionaryWithObjects:forKeys:count:", .{
+ &[_]id{ font, color }, &[_]id{ NSFontAttributeName, NSForegroundColorAttributeName }, @as(usize, 2),
+ });
+ const size = msg(NSSize, title, "sizeWithAttributes:", .{attrs});
+ const w = @min(size.width, box.size.width);
+ var frame = box;
+ frame.size.width = w + 0.5; // leave room for the final glyph's fractional advance
+ frame.origin.x += switch (alignment) {
+ .left => 0,
+ .center => (box.size.width - w) / 2,
+ .right => box.size.width - w,
+ };
+ msg(void, title, "drawInRect:withAttributes:", .{ frame, attrs });
+}
+
+fn drawPanelButton(self: id, _: SEL, _: NSRect) callconv(.c) void {
+ const writing = std.mem.indexOfScalar(id, &writing_btn, self);
+ const i = writing orelse panelIndex(self);
+ const trim = writing == null and i >= first_trim and i < done_index;
+ const active = trim and activeTrim(i);
+ const focused = msg(id, panelWindow(), "firstResponder", .{}) == self;
+ const hot = self == hover_row or msg(bool, self, "isHighlighted", .{});
+ const bounds = msg(NSRect, self, "bounds", .{});
+ const w = bounds.size.width;
+ const h = bounds.size.height;
+ if (w <= 1 or h <= 1) return;
+ const radius: f64 = if (writing != null) 8 else 5;
+ const path = msg(id, objc.class("NSBezierPath"), "bezierPathWithRoundedRect:xRadius:yRadius:", .{ rect(0.5, 0.5, w - 1, h - 1), radius, radius });
+ if (hot or focused) {
+ msg(void, highlight, "setFill", .{});
+ msg(void, path, "fill", .{});
+ }
+ if (trim or (focused and hover_row != null and !hot)) {
+ msg(void, if (active or focused) accent else edge, "setStroke", .{});
+ msg(void, path, "stroke", .{});
+ }
+ const title = msg(id, self, "title", .{});
+ if (writing) |j| {
+ const y = (h - 20) / 2;
+ drawString(title, compact_font, bright, rect(10, y, @max(1, w - 130), 20), .left);
+ drawString(objc.str(writing_shortcuts[j]), compact_font, ink, rect(@max(10, w - 119), y, @min(109, @max(1, w - 20)), 20), .right);
+ } else if (trim) {
+ const percent = percents[i - first_trim];
+ // NSButton drawing coordinates are flipped: smaller y comes first.
+ drawString(title, panel_font, if (active) accent else bright, rect(3, 6, w - 6, 21), .center);
+ if (percent.len != 0) drawString(objc.str(percent), small, ink, rect(3, 26, w - 6, 15), .center);
+ } else if (i == done_index) {
+ drawString(objc.str("The Lab"), panel_font, bright, rect(10, (h - 20) / 2, w - 20, 20), .left);
+ drawString(title, panel_font, accent, rect(10, (h - 20) / 2, w - 20, 20), .right);
+ } else {
+ const compact = w < 305;
+ const text_h: f64 = if (w < 288) h else 20;
+ drawString(title, if (compact) compact_font else panel_font, bright, rect(10, (h - text_h) / 2, w - 20, text_h), .left);
+ if (i == 0 and w >= 340) drawString(objc.str("what each idea does"), small, ink, rect(10, (h - 15) / 2, w - 20, 15), .right);
+ }
+}
+
+fn fitLabel(f: id, w: f64) f64 {
+ msg(void, f, "setPreferredMaxLayoutWidth:", .{w});
+ return @ceil(msg(NSSize, msg(id, f, "cell", .{}), "cellSizeForBounds:", .{rect(0, 0, w, 10000)}).height) + 2;
+}
- item(menu, "The Lab guide…", "labGuide:", 0, false, me);
- rule(menu);
- for (passes) |p| item(menu, p.title, "labPass:", p.tag, false, ctl);
- rule(menu);
- item(menu, "Original", "labOriginal:", 0, pending == null, ctl);
- for (trims) |t| {
- item(menu, t.title, "labPass:", t.tag, pending != null and pending.? == t.tag, ctl);
+fn layoutPanel() void {
+ const bounds = msg(NSRect, content, "bounds", .{});
+ if (writing_at) |p| {
+ const w = @min(376, bounds.size.width);
+ const h = @min(136, bounds.size.height);
+ const rh = @max(1, (h - 12) / 4);
+ msg(void, shield, "setFrame:", .{bounds});
+ msg(void, panel, "setFrame:", .{rect(std.math.clamp(p.x, 0, bounds.size.width - w), std.math.clamp(p.y - h, 0, bounds.size.height - h), w, h)});
+ for (writing_btn, 0..) |b, i| msg(void, b, "setFrame:", .{rect(5, h - 6 - rh * number(i + 1), @max(1, w - 10), rh)});
+ return tintPanel();
}
- rule(menu);
- item(menu, "Your draft is sent only when you pick a pass.", "", 0, false, null);
+ const w = @max(1, @min(panel_w, bounds.size.width - 2 * panel_margin));
+ const trim_w = @max(1, w - 26);
+ // Keep all trim settings reachable rather than dropping buttons on small windows.
+ trim_cols = if (trim_w >= 546) 5 else if (trim_w >= 326) 3 else if (trim_w >= 216) 2 else 1;
+ const trim_rows = (trims.len + trim_cols - 1) / trim_cols;
+ const note_h = fitLabel(privacy_note, @max(1, w - 32));
+ const guide_h = fitLabel(guide_text, @max(1, w - 32));
+ const menu_h = 10 + row_h + 13 + number(passes.len) * row_h + 14 + number(trim_rows) * (trim_h + trim_gap) + note_h + 12;
+ const doc_h = if (guide_open) 10 + row_h + 12 + guide_h + 12 else menu_h;
+ const bottom = @min(panel_bottom, @max(panel_margin, bounds.size.height - 100));
+ const h = @max(1, @min(doc_h, bounds.size.height - bottom - panel_margin));
+ msg(void, shield, "setFrame:", .{bounds});
+ msg(void, panel, "setFrame:", .{rect(@round((bounds.size.width - w) / 2), bottom, w, h)});
+ msg(void, panel_scroll, "setFrame:", .{rect(1, 1, @max(1, w - 2), @max(1, h - 2))});
+ const paper_w = @max(1, w - 2);
+ msg(void, paper, "setFrame:", .{rect(0, 0, paper_w, doc_h - 2)});
+ for (panel_btn, 0..) |b, i| msg(void, b, "setHidden:", .{guide_open != (i == done_index)});
+ for (rules) |line| msg(void, line, "setHidden:", .{guide_open});
+ msg(void, privacy_note, "setHidden:", .{guide_open});
+ msg(void, guide_text, "setHidden:", .{!guide_open});
- const view = if (sender != null) sender else bar[3];
- const h = msg(NSRect, view, "bounds", .{}).size.height;
- _ = msg(bool, menu, "popUpMenuPositioningItem:atLocation:inView:", .{ @as(id, null), NSPoint{ .x = 0, .y = h }, view });
+ var y = doc_h - 12 - row_h;
+ if (guide_open) {
+ msg(void, panel_btn[done_index], "setFrame:", .{rect(6, y, @max(1, paper_w - 12), row_h)});
+ msg(void, guide_text, "setFrame:", .{rect(15, y - 9 - guide_h, @max(1, paper_w - 30), guide_h)});
+ } else {
+ msg(void, panel_btn[0], "setFrame:", .{rect(6, y, @max(1, paper_w - 12), row_h)});
+ y -= 7;
+ msg(void, rules[0], "setFrame:", .{rect(16, y, @max(1, paper_w - 32), 1)});
+ y -= 6;
+ for (panel_btn[1..first_trim]) |b| {
+ y -= row_h;
+ msg(void, b, "setFrame:", .{rect(6, y, @max(1, paper_w - 12), row_h)});
+ }
+ y -= 6;
+ msg(void, rules[1], "setFrame:", .{rect(16, y, @max(1, paper_w - 32), 1)});
+ y -= 8 + trim_h;
+ const cell_w = @max(1, @floor((trim_w - number(trim_cols - 1) * trim_gap) / number(trim_cols)));
+ for (panel_btn[first_trim..done_index], 0..) |b, i| {
+ msg(void, b, "setFrame:", .{rect(12 + number(i % trim_cols) * (cell_w + trim_gap), y - number(i / trim_cols) * (trim_h + trim_gap), cell_w, trim_h)});
+ }
+ y -= number(trim_rows - 1) * (trim_h + trim_gap);
+ msg(void, privacy_note, "setFrame:", .{rect(15, y - 6 - note_h, @max(1, paper_w - 30), note_h)});
+ }
+ const first = msg(id, panelWindow(), "firstResponder", .{});
+ for (panel_btn) |b| if (first == b and !msg(bool, b, "isHidden", .{})) {
+ _ = msg(bool, b, "scrollRectToVisible:", .{msg(NSRect, b, "bounds", .{})});
+ break;
+ };
+ tintPanel();
}
-fn labGuide(_: id, _: SEL, _: id) callconv(.c) void {
- const a = objc.new("NSAlert");
- defer msg(void, a, "release", .{});
- msg(void, a, "setMessageText:", .{objc.str("The Lab")});
- msg(void, a, "setInformativeText:", .{objc.str(guide)});
- _ = msg(id, a, "addButtonWithTitle:", .{objc.str("Done")});
- _ = msg(isize, a, "runModal", .{});
+fn colorRGB(rgb: u24) id {
+ return msg(id, objc.class("NSColor"), "colorWithSRGBRed:green:blue:alpha:", .{
+ number((rgb >> 16) & 255) / 255, number((rgb >> 8) & 255) / 255, number(rgb & 255) / 255, @as(f64, 1),
+ });
+}
+
+fn view(cls: id, parent: id) id {
+ const v = msg(id, msg(id, cls, "alloc", .{}), "initWithFrame:", .{NSRect{}});
+ msg(void, parent, "addSubview:", .{v});
+ msg(void, v, "release", .{});
+ return v;
+}
+
+fn fillView(v: id, color: id) id {
+ msg(void, v, "setWantsLayer:", .{true});
+ const layer = msg(id, v, "layer", .{});
+ msg(void, layer, "setBackgroundColor:", .{cg(color)});
+ return layer;
+}
+
+fn wrapLabel(parent: id, text: []const u8, font: id, color: id) id {
+ const f = msg(id, objc.class("NSTextField"), "wrappingLabelWithString:", .{objc.str(text)});
+ msg(void, f, "setFont:", .{font});
+ msg(void, f, "setTextColor:", .{color});
+ msg(void, parent, "addSubview:", .{f});
+ return f;
+}
+
+fn setupPanel() void {
+ // Write_On frame at 5:00: ink on #121522, two hairlines, one accent outline.
+ surface = colorRGB(0x121522);
+ edge = colorRGB(0x272a38);
+ highlight = colorRGB(0x252532);
+ panel_font = msg(id, objc.class("NSFont"), "monospacedSystemFontOfSize:weight:", .{ @as(f64, 14), @as(f64, 0) });
+ compact_font = msg(id, objc.class("NSFont"), "monospacedSystemFontOfSize:weight:", .{ @as(f64, 13), @as(f64, 0) });
+ const shield_class = objc.subclass("NSView", "ROLabShield", &.{
+ .{ .name = "mouseDown:", .imp = @ptrCast(&dismiss), .types = "v@:@" },
+ .{ .name = "rightMouseDown:", .imp = @ptrCast(&dismiss), .types = "v@:@" },
+ .{ .name = "otherMouseDown:", .imp = @ptrCast(&dismiss), .types = "v@:@" },
+ });
+ const btn_class = objc.subclass("NSButton", "ROLabChoice", &.{
+ .{ .name = "acceptsFirstResponder", .imp = @ptrCast(&acceptsFocus), .types = "B@:" },
+ .{ .name = "keyDown:", .imp = @ptrCast(&panelKeys), .types = "v@:@" },
+ .{ .name = "drawRect:", .imp = @ptrCast(&drawPanelButton), .types = "v@:{CGRect={CGPoint=dd}{CGSize=dd}}" },
+ .{ .name = "mouseEntered:", .imp = @ptrCast(&panelEnter), .types = "v@:@" },
+ .{ .name = "mouseExited:", .imp = @ptrCast(&panelExit), .types = "v@:@" },
+ });
+ const nsview = objc.class("NSView");
+ shield = view(shield_class, content);
+ msg(void, shield, "setHidden:", .{true});
+ panel = view(nsview, shield);
+ const layer = fillView(panel, surface);
+ msg(void, layer, "setCornerRadius:", .{@as(f64, 8)});
+ msg(void, layer, "setBorderWidth:", .{@as(f64, 1)});
+ msg(void, layer, "setBorderColor:", .{cg(edge)});
+ msg(void, layer, "setMasksToBounds:", .{true});
+ panel_scroll = view(objc.class("NSScrollView"), panel);
+ msg(void, panel_scroll, "setDrawsBackground:", .{false});
+ msg(void, panel_scroll, "setHasVerticalScroller:", .{true});
+ msg(void, panel_scroll, "setScrollerStyle:", .{@as(isize, 1)}); // overlay, no reserved width
+ msg(void, panel_scroll, "setAutohidesScrollers:", .{true});
+ paper = msg(id, msg(id, nsview, "alloc", .{}), "initWithFrame:", .{NSRect{}});
+ msg(void, panel_scroll, "setDocumentView:", .{paper});
+ msg(void, paper, "release", .{});
+ for (&rules) |*line| {
+ line.* = view(nsview, paper);
+ _ = fillView(line.*, edge);
+ }
+ for (&panel_btn, 0..) |*b, i| {
+ const title = if (i == 0) "The Lab guide…" else if (i < first_trim) passes[i - 1].title else if (i < done_index) trims[i - first_trim] else "Done";
+ b.* = msg(id, btn_class, "buttonWithTitle:target:action:", .{ objc.str(title), me, objc.sel("choose:") });
+ const tag: isize = if (i == 0 or i == first_trim or i == done_index) -1 else if (i < first_trim) passes[i - 1].tag else @intCast(i - 2);
+ msg(void, b.*, "setTag:", .{tag});
+ if (i > first_trim and i < done_index) msg(void, b.*, "setAccessibilityHelp:", .{objc.str(percents[i - first_trim])});
+ installRow(paper, b.*);
+ }
+ for (&writing_btn, writing_keys, writing_shortcuts, 0..) |*b, key, shortcut, i| {
+ b.* = msg(id, btn_class, "buttonWithTitle:target:action:", .{ objc.str(""), me, objc.sel("choose:") });
+ msg(void, b.*, "setKeyEquivalent:", .{objc.str(key)});
+ msg(void, b.*, "setKeyEquivalentModifierMask:", .{@as(usize, if (i == 2) 0x40000 else 0x60000)});
+ msg(void, b.*, "setAccessibilityHelp:", .{objc.str(shortcut)});
+ installRow(panel, b.*);
+ }
+ privacy_note = wrapLabel(paper, privacy, small, ink);
+ guide_text = wrapLabel(paper, guide, panel_font, bright);
+ msg(void, msg(id, objc.class("NSNotificationCenter"), "defaultCenter", .{}), "addObserver:selector:name:object:", .{ me, objc.sel("dismiss:"), NSWindowDidResignKeyNotification, panelWindow() });
+}
+
+fn installRow(parent: id, b: id) void {
+ msg(void, b, "setBordered:", .{false});
+ msg(void, b, "setFocusRingType:", .{@as(usize, 1)}); // theme draws focus
+ msg(void, parent, "addSubview:", .{b});
+ const area = msg(id, msg(id, objc.class("NSTrackingArea"), "alloc", .{}), "initWithRect:options:owner:userInfo:", .{ NSRect{}, @as(usize, 1 | 0x20 | 0x200), b, @as(id, null) });
+ msg(void, b, "addTrackingArea:", .{area});
+ msg(void, area, "release", .{});
}
fn relaid(_: id, _: SEL, _: id) callconv(.c) void {
relayout();
+ if (chooser_open) layoutPanel();
}
// --- Setup ----------------------------------------------------------------------------------
@@ -266,7 +670,8 @@ fn label(parent: id, font: id, color: id) id {
/// Call once, after the page, the status bar and the count are in `content_view`. `small` is
/// the 11 pt face and `dim_ink` the quiet color the app already uses.
-pub fn setup(content_view: id, controller: id, small_font: id, dim_ink: id, accent_ink: id, hot_ink: id) void {
+pub fn setup(content_view: id, controller: id, editor: id, small_font: id, dim_ink: id, accent_ink: id, hot_ink: id) void {
+ draft_view = editor;
accent = accent_ink;
bright = hot_ink;
content = content_view;
@@ -274,7 +679,8 @@ pub fn setup(content_view: id, controller: id, small_font: id, dim_ink: id, acce
small = small_font;
ink = dim_ink;
const cls = objc.subclass("NSObject", "ROLabUI", &.{
- .{ .name = "labGuide:", .imp = @ptrCast(&labGuide), .types = "v@:@" },
+ .{ .name = "choose:", .imp = @ptrCast(&choose), .types = "v@:@" },
+ .{ .name = "dismiss:", .imp = @ptrCast(&dismiss), .types = "v@:@" },
.{ .name = "mouseEntered:", .imp = @ptrCast(&entered), .types = "v@:@" },
.{ .name = "mouseExited:", .imp = @ptrCast(&exited), .types = "v@:@" },
.{ .name = "relaid:", .imp = @ptrCast(&relaid), .types = "v@:@" },
@@ -292,10 +698,13 @@ pub fn setup(content_view: id, controller: id, small_font: id, dim_ink: id, acce
const titles = [_][]const u8{ "Save", "Open", "Overflow", "Lab" };
const tips = [_][]const u8{ "Save (⌘S)", "Open (⌘O)", "Overflow (⌃⇧D)", "Lab — mark or trim the draft" };
const actions = [_][*:0]const u8{ "saveDoc:", "openDoc:", "toggleOverflow:", "labMenu:" };
- for (&bar, &tracking, titles, tips, actions, glyphs) |*b, *area, title, tip, action, svg| {
+ const trigger_class = objc.subclass("NSButton", "ROLabTrigger", &.{
+ .{ .name = "mouseDown:", .imp = @ptrCast(&triggerMouseDown), .types = "v@:@" },
+ });
+ for (&bar, &tracking, titles, tips, actions, glyphs, 0..) |*b, *area, title, tip, action, svg, i| {
const data = msg(id, objc.class("NSData"), "dataWithBytes:length:", .{ svg.ptr, svg.len });
const image = msg(id, msg(id, objc.class("NSImage"), "alloc", .{}), "initWithData:", .{data});
- b.* = msg(id, objc.class("NSButton"), "buttonWithTitle:target:action:", .{ objc.str(title), ctl, objc.sel(action) });
+ b.* = msg(id, if (i == 3) trigger_class else objc.class("NSButton"), "buttonWithTitle:target:action:", .{ objc.str(title), ctl, objc.sel(action) });
msg(void, b.*, "setBordered:", .{false});
if (image != null) {
msg(void, image, "setTemplate:", .{true});
@@ -336,6 +745,7 @@ pub fn setup(content_view: id, controller: id, small_font: id, dim_ink: id, acce
card_btn[3] = button(card, "Apply rest", "labApply:", ctl, "Apply every remaining finding");
msg(void, content, "addSubview:", .{card}); // last, so it is above the page
+ setupPanel(); // last in the stack, above both the editor and review card
msg(void, content, "setPostsFrameChangedNotifications:", .{true});
msg(void, msg(id, objc.class("NSNotificationCenter"), "defaultCenter", .{}), "addObserver:selector:name:object:", .{ me, objc.sel("relaid:"), NSViewFrameDidChangeNotification, content });
relayout();
diff --git a/src/main.zig b/src/main.zig
index e1adb05..e8e4c21 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -10,6 +10,7 @@
//! group: see `pull`, `fill` and `settle`.
const std = @import("std");
const objc = @import("objc.zig");
+const markdown = @import("markdown.zig");
const doc = @import("doc.zig");
const ai = @import("ai.zig");
const lab = @import("lab.zig");
@@ -28,6 +29,7 @@ const gpa = std.heap.c_allocator;
extern const NSFontAttributeName: id;
extern const NSForegroundColorAttributeName: id;
extern const NSUnderlineStyleAttributeName: id;
+extern const NSStrikethroughStyleAttributeName: id;
extern const NSUnderlineColorAttributeName: id;
extern const NSBackgroundColorAttributeName: id;
extern const NSParagraphStyleAttributeName: id;
@@ -77,18 +79,31 @@ var tabs: [3]id = undefined; // Word, Sentence, Paragraph
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 yes: id = null;
var font: id = null;
var bold: id = null;
var small: id = null;
-var hidden: id = null; // the font of a heading's marker: too small to see
+var hidden: id = null; // Markdown punctuation: too small to see
+var italic: id = null;
+var bold_italic: id = null;
+var code_font: id = null;
+var markdown_dirty: ?NSRange = null;
+var markdown_caret: ?usize = null;
+var markdown_rendering = false;
+var markdown_units: std.ArrayList(u16) = .empty;
+var markdown_parser: markdown.Parser = .{};
+var markdown_strike: id = null;
var script: id = null; // the hand the panel's tabs are written in
var base_attrs: id = null;
-var color: struct { bg: id, panel: id, text: id, near: id, far: id, ghost: id, clear: id, dim: id, word: id, word_line: id, sentence: id, sentence_line: id, paragraph: id, bar: id, ring: id, hover: id, selection: id } = undefined;
+var color: struct { bg: id, panel: id, text: id, near: id, far: id, ghost: id, clear: id, dim: id, word: id, word_line: id, sentence: id, sentence_line: id, paragraph: id, bar: id, ring: id, hover: id, selection: id, code: id } = undefined;
var groups: std.AutoArrayHashMapUnmanaged(u32, doc.Group) = .empty;
var next_id: u32 = 1;
var file_path: ?[]u8 = null;
+var document_defaults: id = null;
+const last_document = "LastDocumentPath";
+var received_open = false; // Finder can send openFile: before didFinishLaunching:
var tools = true; // off is read mode: just the text
var overflow_open = false;
var hover: u32 = 0; // the group under the pointer
@@ -97,7 +112,6 @@ var target: u32 = 0; // the group the alternatives panel is on, when it is open
var home: std.ArrayList(u8) = .empty; // what the target showed when the page's undo last heard: see `settle`
var quiet = false; // the panel is changing the page, and undo is not to be told yet
var filling = false; // the panel's text is being set from its group, not typed
-var last_caret: usize = 0;
var threaded: std.Io.Threaded = undefined;
var io: std.Io = undefined; // for libpantograph: the AI's network and the key's file
@@ -426,7 +440,7 @@ fn refresh() void {
tint(NSForegroundColorAttributeName, color.near, paragraphOf(page, r));
msg(void, layout, "removeTemporaryAttribute:forCharacterRange:", .{ NSForegroundColorAttributeName, r });
};
- headings();
+ markdownRefresh();
const um = msg(id, page, "undoManager", .{});
const undoing = msg(bool, um, "isUndoing", .{}) or msg(bool, um, "isRedoing", .{});
@@ -458,32 +472,169 @@ fn scopeColor(scope: doc.Scope) id {
};
}
-/// The only Markdown rendered so far: a line that opens with "# " is a heading, in bold,
-/// and its marker is out of sight. The marker stays in the text, in a font too small to
-/// see. A font cannot be a temporary attribute, so these go into the storage, and only
-/// where they are wrong.
-fn headings() void {
+/// Record the post-edit range; don't mutate storage while it is processing an edit.
+fn markdownEdited(_: id, _: SEL, _: id, _: usize, changed: NSRange, delta: isize) callconv(.c) void {
+ if (markdown_rendering) return;
+ const old_end: usize = @intCast(@as(isize, @intCast(end(changed))) - delta);
+ if (markdown_caret) |i| markdown_caret = afterEdit(i, changed, old_end);
+ markdown_dirty = if (markdown_dirty) |r| markdownRange(
+ @min(changed.location, afterEdit(r.location, changed, old_end)),
+ @max(end(changed), afterEdit(end(r), changed, old_end)),
+ ) else changed;
+}
+
+fn afterEdit(i: usize, changed: NSRange, old_end: usize) usize {
+ if (i < changed.location) return i;
+ if (i < old_end) return changed.location;
+ return end(changed) + (i - old_end);
+}
+
+fn markdownRange(start: usize, stop: usize) NSRange {
+ return .{ .location = start, .length = stop - start };
+}
+
+/// Fonts must be in storage, not temporary attributes. Style only the edited paragraphs
+/// and the ones whose active inline syntax might change. No character edits or undo entries.
+fn markdownRefresh() void {
+ if (markdown_rendering or msg(bool, page, "hasMarkedText", .{})) return;
+ // The layout manager moves the selection while it is still hearing about an edit, and a
+ // font changed under it then keeps the old font's glyphs. `textDidChange` comes after.
+ if (msg(usize, storage, "editedMask", .{}) != 0) return;
+ const sel = selection();
+ const caret = if (sel.length == 0) sel.location else null;
+ if (markdown_dirty == null and caret == markdown_caret) return;
const n = len();
- var i: usize = 0;
- while (i < n) {
+ const previous = markdown_caret;
+ const changed = markdown_dirty;
+ markdown_caret = caret;
+ markdown_dirty = null;
+ if (n == 0) return;
+
+ const dirty = if (changed) |r| markdownRange(
+ paragraphOf(page, .{ .location = @min(r.location, n) }).location,
+ end(paragraphOf(page, .{ .location = @min(end(r), n) })),
+ ) else NSRange{};
+ markdown_rendering = true;
+ defer markdown_rendering = false;
+ msg(void, storage, "beginEditing", .{});
+ defer msg(void, storage, "endEditing", .{});
+ var open = fenceBefore(dirty.location);
+ var i = dirty.location;
+ while (i < end(dirty)) {
+ const para = paragraphOf(page, .{ .location = i });
+ markdownParagraph(para, caret, &open);
+ i = end(para);
+ }
+ // A fence that came or went changes the lines after it, up to one it leaves as it found.
+ while (changed != null and i < n) {
const para = paragraphOf(page, .{ .location = i });
- const mark_r: NSRange = .{ .location = para.location, .length = marker(para) };
- setFont(mark_r, hidden);
- setFont(.{ .location = end(mark_r), .length = para.length - mark_r.length }, if (mark_r.length > 0) bold else font);
- if (mark_r.length > 0) tint(NSForegroundColorAttributeName, color.clear, mark_r);
+ const was = fenceAt(i);
+ markdownParagraph(para, caret, &open);
i = end(para);
+ if (open == was) break;
+ }
+ var last: ?usize = null;
+ for ([_]?usize{ previous, caret }) |pos| if (pos) |at| {
+ const para = paragraphOf(page, .{ .location = @min(at, n) });
+ if (para.length == 0 or (para.location >= dirty.location and para.location < i) or last == para.location) continue;
+ open = fenceBefore(para.location);
+ markdownParagraph(para, caret, &open);
+ last = para.location;
+ };
+ markdownFences(caret);
+ // A change of attributes alone does not get every line it touched drawn again.
+ msg(void, page, "setNeedsDisplay:", .{true});
+}
+
+/// The fence state the paragraph at `i` leaves behind it: see `key_fence`.
+fn fenceAt(i: usize) u32 {
+ return idOf(msg(id, storage, "attribute:atIndex:effectiveRange:", .{ key_fence, i, @as(?*NSRange, null) }));
+}
+
+fn fenceBefore(para_start: usize) u32 {
+ return if (para_start == 0 or para_start > len()) 0 else fenceAt(para_start - 1);
+}
+
+/// A block's fences show only while the caret is in the block, like any other marker. A
+/// run of `key_fence` is one block, less the line that closes it.
+fn markdownFences(caret: ?usize) void {
+ const n = len();
+ const at = if (caret) |c| paragraphOf(page, .{ .location = c }).location else n + 1;
+ var it: Runs = .{ .key = key_fence };
+ while (it.next()) |run| {
+ const close = paragraphOf(page, .{ .location = end(run.range) });
+ const closed = close.location == end(run.range) and close.length > 0;
+ const show = at >= run.range.location and at < if (closed) end(close) else n + 1;
+ for ([_]NSRange{ paragraphOf(page, .{ .location = run.range.location }), if (closed) close else .{} }) |line| {
+ if (line.length == 0) continue;
+ setMarkdownAttribute(line, NSFontAttributeName, if (show) code_font else hidden);
+ setMarkdownAttribute(line, NSForegroundColorAttributeName, if (show) color.dim else color.clear);
+ setMarkdownAttribute(line, NSStrikethroughStyleAttributeName, null);
+ }
}
}
-fn setFont(r: NSRange, want: id) void {
+/// `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 kind = markdown.fenceLine(markdown_units.items, open);
+ setMarkdownAttribute(para, key_fence, if (open.* != 0) number(open.*) else null);
+ switch (kind) {
+ .fence => return, // `markdownFences` shows or hides it
+ .code => return markdownPaint(para, .{ .code = true }, false, false),
+ .text => {},
+ }
+ const prefix = marker(para);
+ const body = markdownRange(para.location + prefix, end(para));
+ if (prefix != 0) {
+ const active_heading = if (caret) |at| paragraphOf(page, .{ .location = at }).location == para.location else false;
+ markdownPaint(markdownRange(para.location, body.location), .{}, false, !active_heading);
+ }
+ const marks = markdown_parser.parse(gpa, markdown_units.items[prefix..]) catch return markdownPaint(body, .{}, prefix != 0, false);
+ var active: markdown.Active = .{};
+ var at = body.location;
+ for (marks, 0..) |mark_, idx| {
+ const partner = mark_.partner orelse continue;
+ const tag = markdownRange(body.location + mark_.at, body.location + mark_.at + mark_.width);
+ markdownPaint(markdownRange(at, tag.location), active.style(), prefix != 0, false);
+ const first = body.location + marks[@min(idx, partner)].at;
+ const closing = marks[@max(idx, partner)];
+ const stop = body.location + closing.at + closing.width;
+ const reveal = if (caret) |c| c > first and c < stop else false;
+ markdownPaint(tag, .{}, prefix != 0, !reveal);
+ active.toggle(mark_);
+ at = end(tag);
+ }
+ markdownPaint(markdownRange(at, end(body)), active.style(), prefix != 0, false);
+}
+
+fn markdownPaint(r: NSRange, style: markdown.Style, heading: bool, hide: bool) void {
if (r.length == 0) return;
+ const strong = heading or style.strong;
+ const face = if (hide) hidden else if (style.code) code_font else if (style.emphasis)
+ (if (strong) bold_italic else italic)
+ else if (strong) bold else font;
+ setMarkdownAttribute(r, NSFontAttributeName, face);
+ setMarkdownAttribute(r, NSForegroundColorAttributeName, if (hide) color.clear else color.text);
+ setMarkdownAttribute(r, NSStrikethroughStyleAttributeName, if (style.strike) markdown_strike else null);
+}
+
+fn setMarkdownAttribute(r: NSRange, key: id, want: id) void {
var run: NSRange = .{};
- const have = msg(id, storage, "attribute:atIndex:longestEffectiveRange:inRange:", .{ NSFontAttributeName, r.location, &run, r });
- if (have != want or run.length < r.length) msg(void, storage, "addAttribute:value:range:", .{ NSFontAttributeName, want, r });
+ const have = msg(id, storage, "attribute:atIndex:longestEffectiveRange:inRange:", .{ key, r.location, &run, r });
+ if (have == want and run.length == r.length) return;
+ if (want != null) {
+ msg(void, storage, "addAttribute:value:range:", .{ key, want, r });
+ } else {
+ msg(void, storage, "removeAttribute:range:", .{ key, r });
+ }
}
/// How much of a paragraph is a heading's marker: three characters of "## Title".
fn marker(para: NSRange) usize {
+ if (fenceBefore(para.location) != 0) return 0; // code, not a heading
var hashes: usize = 0;
while (hashes < para.length and charAt(para.location + hashes) == '#') hashes += 1;
if (hashes == 0 or hashes > 6 or hashes == para.length or charAt(para.location + hashes) != ' ') return 0;
@@ -1047,8 +1198,26 @@ fn showLab() void {
lab_ui.update(tools, line, true, p.isTrim() or p == .typos);
}
-fn labMenu(_: id, _: SEL, sender: id) callconv(.c) void {
- lab_ui.openMenu(sender);
+fn labMenu(_: id, _: SEL, _: id) callconv(.c) void {
+ if (!tools) {
+ tools = true;
+ panels();
+ refresh();
+ }
+ lab_ui.togglePanel();
+}
+
+fn validateMenuItem(_: id, _: SEL, menu_item: id) callconv(.c) bool {
+ const action = msg(SEL, menu_item, "action", .{});
+ if (action == objc.sel("labOriginal:")) return tools and reading != null;
+ if (action == objc.sel("labNext:") or action == objc.sel("labKeep:") or action == objc.sel("labApply:")) {
+ if (!tools) return false;
+ const j = reading orelse return false;
+ const hits = j.hits orelse return false;
+ if (hits.items.len == 0) return false;
+ return action != objc.sel("labApply:") or j.pass.?.isTrim() or j.pass.? == .typos;
+ }
+ return true;
}
fn labPass(_: id, _: SEL, sender: id) callconv(.c) void {
@@ -1500,7 +1669,6 @@ fn load(bytes: []const u8) void {
msg(void, msg(id, page, "undoManager", .{}), "removeAllActions", .{});
select(.{});
- keepOut();
msg(void, page, "scrollPoint:", .{NSPoint{}});
setDirty(false);
panels();
@@ -1544,29 +1712,46 @@ fn setPath(path: ?[]const u8) void {
file_path = new;
if (new) |p| {
msg(void, window, "setTitleWithRepresentedFilename:", .{str(p)});
+ msg(void, document_defaults, "setObject:forKey:", .{ str(p), str(last_document) });
} else {
+ msg(void, document_defaults, "removeObjectForKey:", .{str(last_document)});
msg(void, window, "setRepresentedFilename:", .{str("")});
msg(void, window, "setTitle:", .{str("Untitled")});
}
}
-fn openPath(path: []const u8) bool {
- const data = msg(id, objc.class("NSData"), "dataWithContentsOfFile:", .{str(path)});
- if (data == null) {
- alert("That file could not be read.", path);
- return false;
- }
+fn readPath(path: []const u8) error{ Unreadable, NotUtf8 }!void {
+ const data = msg(id, objc.class("NSData"), "dataWithContentsOfFile:", .{str(path)}) orelse return error.Unreadable;
const n = msg(usize, data, "length", .{});
const bytes: []const u8 = if (n == 0) "" else msg([*]const u8, data, "bytes", .{})[0..n];
- if (!std.unicode.utf8ValidateSlice(bytes)) {
- alert("That file is not UTF-8 text.", path);
- return false;
- }
+ if (!std.unicode.utf8ValidateSlice(bytes)) return error.NotUtf8;
load(bytes);
setPath(path);
+}
+
+fn openPath(path: []const u8) bool {
+ readPath(path) catch |err| {
+ alert(switch (err) {
+ error.Unreadable => "That file could not be read.",
+ error.NotUtf8 => "That file is not UTF-8 text.",
+ }, path);
+ return false;
+ };
return true;
}
+fn startDraft() void {
+ // An explicit Open is authoritative, even if AppKit delivered it during launch.
+ if (!received_open) {
+ const path = objc.utf8(msg(id, document_defaults, "stringForKey:", .{str(last_document)}));
+ if (path.len != 0) {
+ if (readPath(path)) return else |_| {} // A stale preference isn't an Open error.
+ }
+ } else if (file_path != null) return;
+ load("");
+ setPath(null);
+}
+
fn save(ask: bool) bool {
var to: []const u8 = file_path orelse "";
if (ask or to.len == 0) {
@@ -1646,7 +1831,7 @@ fn selectionDidChange(_: id, _: SEL, note: id) callconv(.c) void {
const view = msg(id, note, "object", .{});
if (view == alts) return pull();
if (view != page) return;
- keepOut();
+ markdownRefresh();
typing();
status();
}
@@ -1671,19 +1856,6 @@ fn undoFor(_: id, _: SEL, view: id) callconv(.c) id {
return if (view == alts) alts_undo else null; // null: the window's, as ever
}
-/// A heading's marker is out of sight, and the caret stays out of it. Stepping left from a
-/// heading's first letter goes to the end of the line above.
-fn keepOut() void {
- defer last_caret = selection().location;
- const sel = selection();
- if (sel.length > 0) return;
- const para = paragraphOf(page, sel);
- const first = para.location + marker(para);
- if (sel.location >= first) return;
- const stepped_left = last_caret == first and sel.location + 1 == first and para.location > 0;
- select(.{ .location = if (stepped_left) para.location - 1 else first });
-}
-
/// Keep the 65-character column centered in whatever width there is. It narrows, and the
/// text reflows, only when the window is too small for it, and it steps aside only when
/// the alternatives panel would otherwise lie over it.
@@ -1716,6 +1888,7 @@ fn quitWithWindow(_: id, _: SEL, _: id) callconv(.c) bool {
/// Finder, `open` and a path on the command line all arrive here, the last by AppKit's own
/// reading of the arguments. A path with no file yet starts a piece that will save there.
fn openFile(_: id, _: SEL, _: id, path: id) callconv(.c) bool {
+ received_open = true;
if (!mayDiscard()) return false;
const full = msg(id, msg(id, objc.class("NSURL"), "fileURLWithPath:", .{path}), "path", .{});
if (msg(bool, msg(id, objc.class("NSFileManager"), "defaultManager", .{}), "fileExistsAtPath:", .{full})) return openPath(objc.utf8(full));
@@ -1752,11 +1925,6 @@ fn keyDown(self: id, _: SEL, event: id) callconv(.c) void {
armed = false;
if (hover != 0) refresh();
}
- if (plain and key == Key.backspace and sel.length == 0) { // before a heading's first letter: no longer a heading
- const para = paragraphOf(page, sel);
- const m = marker(para);
- if (m > 0 and sel.location == para.location + m) return insert(page, "", .{ .location = para.location, .length = m });
- }
objc.msgSuper(void, self, "NSTextView", "keyDown:", .{event});
}
@@ -1770,16 +1938,25 @@ fn mouseDown(self: id, _: SEL, event: id) callconv(.c) void {
/// else it puts the caret there and is about the word under it.
fn contextMenu(self: id, _: SEL, event: id) callconv(.c) id {
if (!tools) return objc.msgSuper(id, self, "NSTextView", "menuForEvent:", .{event});
- const sel = selection();
- if (charUnder(event)) |i| if (i < sel.location or i >= end(sel)) select(.{ .location = i });
- const cs = Mod.ctrl | Mod.shift;
- const menu = msg(id, objc.new("NSMenu"), "autorelease", .{});
+ if (!lab_ui.canOpenWritingMenu()) return null;
+ const point = msg(NSPoint, event, "locationInWindow", .{});
+ const hit = charUnder(event);
+ const before = selection();
+ if (hit == null or hit.? < before.location or hit.? >= end(before)) {
+ const local = msg(NSPoint, self, "convertPoint:fromView:", .{ point, @as(id, null) });
+ select(.{ .location = hit orelse msg(usize, self, "characterIndexForInsertionAtPoint:", .{local}) });
+ }
+ const subject = selection();
var buf: [2][160]u8 = undefined;
- item(menu, menuTitle(&buf[0], "Alternatives"), "alternative:", "a", cs, ctl);
- item(menu, menuTitle(&buf[1], "AI alternatives"), "aiAlternative:", "g", cs, ctl);
- item(menu, if (ghostIn(ghostable())) "Revive it" else "Ghost it", "ghost:", "/", Mod.ctrl, ctl);
- item(menu, "Stash this in Overflow", "stash:", "x", cs, ctl);
- return menu;
+ lab_ui.openWritingMenu(point, .{
+ menuTitle(&buf[0], "Alternatives"),
+ menuTitle(&buf[1], "AI alternatives"),
+ if (ghostIn(ghostable())) "Revive it" else "Ghost it",
+ "Stash this in Overflow",
+ });
+ // Leaving an edited alternatives panel can settle it and move the page selection.
+ if (!std.meta.eql(selection(), subject)) select(subject);
+ return null;
}
fn menuTitle(buf: []u8, lead: []const u8) []const u8 {
@@ -1825,9 +2002,26 @@ fn paste(self: id, _: SEL, sender: id) callconv(.c) void {
/// group, the showing one filled in.
fn drawBackground(self: id, _: SEL, dirty: NSRect) callconv(.c) void {
objc.msgSuper(void, self, "NSTextView", "drawViewBackgroundInRect:", .{dirty});
- if (!tools) return;
const origin = msg(NSPoint, self, "textContainerOrigin", .{});
const container = msg(id, self, "textContainer", .{});
+ // Behind each fenced block, from its opening fence to its closing one, a panel as wide
+ // as the column. The fences' own lines are its padding while they are out of sight.
+ var fences: Runs = .{ .key = key_fence };
+ while (fences.next()) |run| {
+ const stop = end(paragraphOf(page, .{ .location = end(run.range) }));
+ const glyphs = msg(NSRange, layout, "glyphRangeForCharacterRange:actualCharacterRange:", .{ markdownRange(run.range.location, stop), @as(?*NSRange, null) });
+ if (glyphs.length == 0) continue;
+ const top = msg(NSRect, layout, "lineFragmentRectForGlyphAtIndex:effectiveRange:", .{ glyphs.location, @as(?*NSRange, null) });
+ const bottom = msg(NSRect, layout, "lineFragmentRectForGlyphAtIndex:effectiveRange:", .{ end(glyphs) - 1, @as(?*NSRange, null) });
+ const pad = 14;
+ const box: NSRect = .{
+ .origin = .{ .x = origin.x + top.origin.x - pad, .y = origin.y + top.origin.y - line_gap / 2 },
+ .size = .{ .width = top.size.width + 2 * pad, .height = bottom.origin.y + bottom.size.height - top.origin.y },
+ };
+ msg(void, color.code, "setFill", .{});
+ msg(void, msg(id, objc.class("NSBezierPath"), "bezierPathWithRoundedRect:xRadius:yRadius:", .{ box, @as(f64, 8), @as(f64, 8) }), "fill", .{});
+ }
+ if (!tools) return;
var it: Runs = .{ .key = key_group };
while (it.next()) |run| {
const g = groups.getPtr(idOf(run.value)) orelse continue;
@@ -1940,6 +2134,10 @@ const status_h = 40;
// --- Setup ----------------------------------------------------------------------------------
+fn markdownFont(ns_font: id, name: []const u8, size: f64, fallback: id) id {
+ return msg(id, msg(id, ns_font, "fontWithName:size:", .{ str(name), size }) orelse fallback, "retain", .{});
+}
+
fn setup(app: id) void {
const NSObject = "NSObject";
const action = "v@:@";
@@ -1961,6 +2159,7 @@ fn setup(app: id) void {
.{ .name = "aiAlternative:", .imp = @ptrCast(&aiAlternative), .types = action },
.{ .name = "inference:", .imp = @ptrCast(&inference), .types = action },
.{ .name = "needInference:", .imp = @ptrCast(&needInference), .types = action },
+ .{ .name = "validateMenuItem:", .imp = @ptrCast(&validateMenuItem), .types = "B@:@" },
.{ .name = "labMenu:", .imp = @ptrCast(&labMenu), .types = action },
.{ .name = "labPass:", .imp = @ptrCast(&labPass), .types = action },
.{ .name = "labOriginal:", .imp = @ptrCast(&labOriginal), .types = action },
@@ -1969,6 +2168,7 @@ fn setup(app: id) void {
.{ .name = "labApply:", .imp = @ptrCast(&labApply), .types = action },
.{ .name = "styleChanged:", .imp = @ptrCast(&styleChanged), .types = action },
.{ .name = "resized:", .imp = @ptrCast(&resized), .types = action },
+ .{ .name = "textStorage:didProcessEditing:range:changeInLength:", .imp = @ptrCast(&markdownEdited), .types = "v@:@Q{_NSRange=QQ}q" },
.{ .name = "textDidChange:", .imp = @ptrCast(&textDidChange), .types = action },
.{ .name = "textDidEndEditing:", .imp = @ptrCast(&editingEnded), .types = action },
.{ .name = "textView:doCommandBySelector:", .imp = @ptrCast(&doCommand), .types = "B@:@:" },
@@ -1977,6 +2177,7 @@ fn setup(app: id) void {
.{ .name = "windowShouldClose:", .imp = @ptrCast(&windowShouldClose), .types = "B@:@" },
.{ .name = "applicationShouldTerminate:", .imp = @ptrCast(&shouldTerminate), .types = "Q@:@" },
.{ .name = "applicationShouldTerminateAfterLastWindowClosed:", .imp = @ptrCast(&quitWithWindow), .types = "B@:@" },
+ .{ .name = "applicationDidFinishLaunching:", .imp = @ptrCast(&didLaunch), .types = action },
.{ .name = "application:openFile:", .imp = @ptrCast(&openFile), .types = "B@:@@" },
});
_ = objc.subclass("NSTextView", "ROPage", &.{
@@ -2013,6 +2214,7 @@ fn setup(app: id) void {
.ring = rgb(0x6c6879, 1),
.hover = rgb(0x98a8e2, 0.14),
.selection = rgb(0x817cd4, 0.28),
+ .code = rgb(0x121522, 1),
};
const regular: f64 = 0;
const heavy: f64 = 0.4;
@@ -2021,11 +2223,16 @@ fn setup(app: id) void {
bold = msg(id, msg(id, NSFont, "monospacedSystemFontOfSize:weight:", .{ @as(f64, 20), heavy }), "retain", .{});
small = msg(id, msg(id, NSFont, "monospacedSystemFontOfSize:weight:", .{ @as(f64, 11), regular }), "retain", .{});
hidden = msg(id, msg(id, NSFont, "monospacedSystemFontOfSize:weight:", .{ @as(f64, 0.1), regular }), "retain", .{});
+ italic = markdownFont(NSFont, "Menlo-Italic", 20, font);
+ bold_italic = markdownFont(NSFont, "Menlo-BoldItalic", 20, bold);
+ code_font = markdownFont(NSFont, "Monaco", 18, font);
+ markdown_strike = msg(id, number(1), "retain", .{});
script = msg(id, msg(id, NSFont, "fontWithName:size:", .{ str("BradleyHandITCTT-Bold"), @as(f64, 17) }) orelse small, "retain", .{});
tones = .{ makeTone(1900), makeTone(1500) };
key_group = msg(id, str("WriteAwayGroup"), "retain", .{});
key_ghost = msg(id, str("WriteAwayGhost"), "retain", .{});
key_lab_keep = msg(id, str("WriteAwayLabKeep"), "retain", .{});
+ key_fence = msg(id, str("WriteAwayFence"), "retain", .{});
yes = msg(id, msg(id, objc.class("NSNumber"), "numberWithBool:", .{true}), "retain", .{});
const spaced = objc.new("NSMutableParagraphStyle");
msg(void, spaced, "setLineSpacing:", .{@as(f64, line_gap)});
@@ -2068,6 +2275,7 @@ fn setup(app: id) void {
msg(void, page, "setDefaultParagraphStyle:", .{spaced});
msg(void, page, "setSelectedTextAttributes:", .{dict(&.{.{ NSBackgroundColorAttributeName, color.selection }})});
storage = msg(id, page, "textStorage", .{});
+ msg(void, storage, "setDelegate:", .{ctl});
layout = msg(id, page, "layoutManager", .{});
const strip: NSRect = .{ .size = .{ .width = 280, .height = bounds.size.height } };
over_scroll = textArea("NSTextView", strip, color.panel, &over);
@@ -2141,7 +2349,7 @@ fn setup(app: id) void {
msg(void, clip, "setPostsFrameChangedNotifications:", .{true});
msg(void, msg(id, objc.class("NSNotificationCenter"), "defaultCenter", .{}), "addObserver:selector:name:object:", .{ ctl, objc.sel("resized:"), NSViewFrameDidChangeNotification, clip });
- lab_ui.setup(content, ctl, small, color.dim, color.word, color.text);
+ lab_ui.setup(content, ctl, page, small, color.dim, color.word, color.text);
menus(app);
panels();
resized(null, null, null);
@@ -2225,6 +2433,11 @@ fn menus(app: id) void {
item(write, "Ghost or Revive", "ghost:", "/", Mod.ctrl, ctl);
item(write, "Stash in Overflow", "stash:", "x", cs, ctl);
item(write, "Use from Overflow", "useOverflow:", "\r", Mod.ctrl, ctl);
+ item(write, "Lab…", "labMenu:", "l", cs, ctl);
+ item(write, "Lab: Next", "labNext:", "n", cs, ctl);
+ item(write, "Lab: Keep", "labKeep:", "k", cs, ctl);
+ item(write, "Lab: Apply rest", "labApply:", "p", cs, ctl);
+ item(write, "Lab: Discard / Original", "labOriginal:", "o", cs, ctl);
const view = submenu(bar, "View");
item(view, "Tools", "toggleTools:", "r", cs, ctl);
@@ -2261,15 +2474,17 @@ pub fn main() void {
const process = msg(id, objc.class("NSProcessInfo"), "processInfo", .{});
if (msg(id, msg(id, process, "environment", .{}), "objectForKey:", .{str("WRITE_AWAY_SELFTEST")}) != null) return selftest();
- load(@embedFile("welcome.md")); // until `openFile` is handed something else
- setPath(null);
-
+ document_defaults = msg(id, objc.class("NSUserDefaults"), "standardUserDefaults", .{});
const regular: isize = 0;
_ = msg(bool, app, "setActivationPolicy:", .{regular});
+ msg(void, app, "run", .{});
+}
+
+fn didLaunch(_: id, _: SEL, note: id) callconv(.c) void {
+ startDraft();
msg(void, window, "makeKeyAndOrderFront:", .{@as(id, null)});
_ = msg(bool, window, "makeFirstResponder:", .{page});
- msg(void, app, "activateIgnoringOtherApps:", .{true});
- msg(void, app, "run", .{});
+ msg(void, msg(id, note, "object", .{}), "activateIgnoringOtherApps:", .{true});
}
// --- The check ------------------------------------------------------------------------------
@@ -2286,6 +2501,27 @@ fn selftest() void {
};
const um = msg(id, page, "undoManager", .{});
+ // Use an isolated defaults suite and temporary draft, never the writer's last file.
+ const unique = msg(id, msg(id, objc.class("NSUUID"), "UUID", .{}), "UUIDString", .{});
+ document_defaults = msg(id, msg(id, objc.class("NSUserDefaults"), "alloc", .{}), "initWithSuiteName:", .{unique});
+ startDraft();
+ t.expect(len() == 0 and file_path == null and std.mem.eql(u8, objc.utf8(msg(id, window, "title", .{})), "Untitled"), "a first launch is empty and Untitled");
+ const fm = msg(id, objc.class("NSFileManager"), "defaultManager", .{});
+ const path = msg(id, msg(id, msg(id, fm, "temporaryDirectory", .{}), "URLByAppendingPathComponent:", .{unique}), "path", .{});
+ t.expect(openFile(null, null, null, path), "an explicit new path starts a draft");
+ startDraft();
+ t.expect(file_path != null and std.mem.eql(u8, file_path.?, objc.utf8(path)) and len() == 0, "a launch file takes precedence even when it does not exist yet");
+ insert(page, "Remember this.", .{});
+ t.expect(save(false), "save the named piece");
+ received_open = false;
+ load("");
+ startDraft();
+ t.expect(file_path != null and std.mem.eql(u8, file_path.?, objc.utf8(path)) and std.mem.eql(u8, objc.utf8(string(page)), "Remember this."), "the next launch restores the last file from disk");
+ t.expect(msg(bool, fm, "removeItemAtPath:error:", .{ path, @as(?*id, null) }), "remove the temporary piece");
+ startDraft();
+ t.expect(len() == 0 and file_path == null and msg(id, document_defaults, "objectForKey:", .{str(last_document)}) == null and !msg(bool, window, "isDocumentEdited", .{}), "a missing piece leaves a clean unnamed draft and no stale path");
+ msg(void, document_defaults, "removePersistentDomainForName:", .{unique});
+
load(@embedFile("welcome.md"));
t.expect(groups.count() == 3, "the welcome piece has three groups");
@@ -2309,12 +2545,12 @@ fn selftest() void {
t.expect(@abs(msg(NSRect, over_scroll, "frame", .{}).size.width - chosen) < 1, "reopening remembers the divider");
toggleOverflow(null, null, null);
- // The heading's marker is in the text and out of sight, and the caret keeps out of it.
- t.expect(msg(id, storage, "attribute:atIndex:effectiveRange:", .{ NSFontAttributeName, @as(usize, 0), @as(?*NSRange, null) }) == hidden, "a heading's marker is hidden");
- t.expect(msg(id, storage, "attribute:atIndex:effectiveRange:", .{ NSFontAttributeName, @as(usize, 2), @as(?*NSRange, null) }) == bold, "and the heading is bold");
- t.expect(selection().location == 2, "the caret starts after the marker");
+ // Moving into the heading reveals its source without changing the styled title.
+ select(.{ .location = len() });
+ t.expect(msg(id, storage, "attribute:atIndex:effectiveRange:", .{ NSFontAttributeName, @as(usize, 0), @as(?*NSRange, null) }) == hidden, "an inactive heading's marker is hidden");
select(.{ .location = 1 });
- t.expect(selection().location == 2, "and cannot be put inside it");
+ t.expect(selection().location == 1 and msg(id, storage, "attribute:atIndex:effectiveRange:", .{ NSFontAttributeName, @as(usize, 0), @as(?*NSRange, null) }) == font, "the caret can enter and reveal the heading marker");
+ t.expect(msg(id, storage, "attribute:atIndex:effectiveRange:", .{ NSFontAttributeName, @as(usize, 2), @as(?*NSRange, null) }) == bold, "the heading title remains bold");
// Flip a group in place, and undo it.
const gid = groups.keys()[0];
@@ -2367,12 +2603,42 @@ fn selftest() void {
// A right-click on the word: what can be done with it.
select(.{}); // undo left the word selected again, and then the menu would be about the selection
const right_down: usize = 3;
- const menu = contextMenu(page, null, msg(id, NSEvent, "mouseEventWithType:location:modifierFlags:timestamp:windowNumber:context:eventNumber:clickCount:pressure:", .{
+ _ = msg(bool, window, "makeFirstResponder:", .{page});
+ const click = msg(id, NSEvent, "mouseEventWithType:location:modifierFlags:timestamp:windowNumber:context:eventNumber:clickCount:pressure:", .{
right_down, msg(NSPoint, page, "convertPoint:toView:", .{ on_word, @as(id, null) }), zero, no_time, no_window, @as(id, null), no_window, no_window, @as(f32, 0),
- }));
- t.expect(msg(isize, menu, "numberOfItems", .{}) == 4, "the right-click menu has four commands");
- const title = objc.utf8(msg(id, msg(id, menu, "itemAtIndex:", .{@as(isize, 0)}), "title", .{}));
- t.expect(std.mem.find(u8, title, first) != null, "and the first names the word under the pointer");
+ });
+ msg(void, page, "rightMouseDown:", .{click});
+ const first_row = msg(id, window, "firstResponder", .{});
+ const writing_card = msg(id, first_row, "superview", .{});
+ t.expect(msg(usize, msg(id, writing_card, "subviews", .{}), "count", .{}) == 5, "the writing menu has four rows and the hidden Lab scroll view");
+ t.expect(std.mem.find(u8, objc.utf8(msg(id, first_row, "title", .{})), first) != null, "the first row names the word under the pointer");
+ const menu_key = struct {
+ fn send(code: u16, mods: usize, chars: []const u8) void {
+ const event = msg(id, objc.class("NSEvent"), "keyEventWithType:location:modifierFlags:timestamp:windowNumber:context:characters:charactersIgnoringModifiers:isARepeat:keyCode:", .{
+ @as(usize, 10), NSPoint{}, mods, @as(f64, 0), msg(isize, window, "windowNumber", .{}), @as(id, null), str(chars), str(chars), false, code,
+ });
+ if (!msg(bool, window, "performKeyEquivalent:", .{event}))
+ msg(void, msg(id, window, "firstResponder", .{}), "keyDown:", .{event});
+ }
+ };
+ menu_key.send(53, 0, "");
+ t.expect(msg(id, window, "firstResponder", .{}) == page, "Escape restores editor focus");
+ const selected = groupRange(gid).?;
+ select(selected);
+ t.expect(contextMenu(page, null, click) == null, "writing mode does not create a system menu");
+ t.expect(std.mem.eql(u8, objc.utf8(msg(id, first_row, "title", .{})), "Alternatives for selection"), "a click inside a selection keeps it");
+ menu_key.send(125, 0, "");
+ t.expect(std.mem.eql(u8, objc.utf8(msg(id, msg(id, window, "firstResponder", .{}), "title", .{})), "AI alternatives for selection"), "the down arrow moves focus to the next action");
+ menu_key.send(44, Mod.ctrl, "/");
+ t.expect(msg(id, window, "firstResponder", .{}) == page and std.meta.eql(selection(), selected) and ghostIn(selected), "the popup shortcut ghosts the selected text and returns focus");
+ msg(void, um, "undo", .{});
+ _ = contextMenu(page, null, click);
+ menu_key.send(36, 0, "\r");
+ t.expect(target == gid and msg(id, window, "firstResponder", .{}) == alts, "Return opens alternatives for the clicked group");
+ _ = contextMenu(page, null, click);
+ menu_key.send(53, 0, "");
+ t.expect(target == gid and msg(id, window, "firstResponder", .{}) == alts, "dismissing the popup leaves the alternatives panel and its focus alone");
+ closePanel();
// Ghost and revive. (Each undo so far has had one command to undo: outside the run
// loop nothing closes an undo group but undo itself.)
@@ -2476,11 +2742,17 @@ fn selftest() void {
reading = j;
return j;
}
+ fn key(code: u16, mods: usize) void {
+ const event = msg(id, objc.class("NSEvent"), "keyEventWithType:location:modifierFlags:timestamp:windowNumber:context:characters:charactersIgnoringModifiers:isARepeat:keyCode:", .{
+ @as(usize, 10), NSPoint{}, mods, @as(f64, 0), msg(isize, window, "windowNumber", .{}), @as(id, null), str(""), str(""), false, code,
+ });
+ msg(void, msg(id, window, "firstResponder", .{}), "keyDown:", .{event});
+ }
fn strength(pass: lab.Pass) void {
- const item_ = objc.new("NSMenuItem");
- defer msg(void, item_, "release", .{});
- msg(void, item_, "setTag:", .{@as(isize, @intFromEnum(pass))});
- labPass(null, null, item_);
+ labMenu(null, null, null);
+ // Shift-Tab wraps from the guide around the trim buttons, strongest first.
+ for (0..10 - @intFromEnum(pass)) |_| key(48, Mod.shift);
+ key(36, 0);
}
fn ghostValue(at: usize) id {
return if (runAt(key_ghost, at)) |run| run.value else null;
@@ -2500,6 +2772,25 @@ fn selftest() void {
const cut = "[{\"sentence\":1,\"shortened\":\"We need this today.\",\"importance\":5}]";
const trim_draft = "We really need this today. Keep my note.";
load(trim_draft);
+ _ = msg(bool, window, "makeFirstResponder:", .{page});
+ const write_menu = msg(id, msg(id, msg(id, msg(id, objc.class("NSApplication"), "sharedApplication", .{}), "mainMenu", .{}), "itemAtIndex:", .{@as(isize, 3)}), "submenu", .{});
+ const next_item = msg(id, write_menu, "itemWithTitle:", .{str("Lab: Next")});
+ t.expect(next_item != null and !validateMenuItem(null, null, next_item), "Lab review menu is disabled without a review");
+ toggleTools(null, null, null);
+ labMenu(null, null, null);
+ t.expect(tools and msg(id, window, "firstResponder", .{}) != page, "Lab opens from read mode");
+ stub.key(53, 0);
+ labMenu(null, null, null);
+ const guide_control = msg(id, window, "firstResponder", .{});
+ t.expect(guide_control != page, "Lab focuses the guide first");
+ stub.key(36, 0);
+ t.expect(msg(id, window, "firstResponder", .{}) != guide_control and reading == null, "Return opens the in-window guide without running a pass");
+ stub.key(53, 0);
+ t.expect(msg(id, window, "firstResponder", .{}) == page, "Escape from the guide restores editor focus");
+ labMenu(null, null, null);
+ const shield = msg(id, msg(id, window, "contentView", .{}), "hitTest:", .{NSPoint{ .x = 1, .y = 1 }});
+ msg(void, shield, "mouseDown:", .{@as(id, null)});
+ t.expect(msg(id, window, "firstResponder", .{}) == page, "An outside click dismisses Lab and restores focus");
// The test has no event loop to close undo groups between commands.
msg(void, um, "setGroupsByEvent:", .{false});
select(.{ .location = 10, .length = 4 }); // manual ghost immediately after "really "
@@ -2507,6 +2798,7 @@ fn selftest() void {
const trim = stub.reply(.slight, cut);
landed(trim);
t.expect(trim.owner != null and stub.ghostValue(3) == trim.owner and stub.ghostValue(10) == yes, "Lab and adjacent manual ghosts have distinct ownership");
+ t.expect(validateMenuItem(null, null, next_item), "Lab review menu is enabled for a review");
const saved_review = doc.parse(arena, snapshot(arena) catch unreachable) catch unreachable;
t.expect(saved_review.ghosts.len == 2, "save captures Lab and manual ghosts");
@@ -2612,5 +2904,62 @@ 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");
+ // 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("💤 **");
+ const italic_at = doc.utf16Len("💤 **bold _");
+ const code_at = doc.utf16Len("💤 **bold _and italic_** `");
+ const cut_at = doc.utf16Len("💤 **bold _and italic_** `*code*` ~~");
+ const second_at = doc.utf16Len("💤 **bold _and italic_** `*code*` ~~cut~~\n__");
+ const md_style = struct {
+ fn at(key: id, i: usize) id {
+ return msg(id, storage, "attribute:atIndex:effectiveRange:", .{ key, i, @as(?*NSRange, null) });
+ }
+ };
+ const md_rec = doc.GroupRec{ .at = "💤 **".len, .variants = &.{ "bold", "strong" } };
+ load(doc.serialize(arena, .{ .body = raw_md, .groups = &.{md_rec}, .ghosts = &.{.{ .at = "💤 **".len, .text = "bold" }} }) catch unreachable);
+ t.expect(md_style.at(NSFontAttributeName, bold_at - 1) == hidden and md_style.at(NSFontAttributeName, bold_at) == bold, "strong markup stays in storage while its delimiters hide");
+ t.expect(md_style.at(NSFontAttributeName, italic_at) == bold_italic and md_style.at(NSFontAttributeName, code_at) == code_font and md_style.at(NSStrikethroughStyleAttributeName, cut_at) == markdown_strike, "nested emphasis, code and strike have distinct styling");
+ t.expect(md_style.at(NSFontAttributeName, second_at) == bold and md_style.at(NSFontAttributeName, len() - 1) == font, "Markdown handles other paragraphs and leaves escaped delimiters literal");
+ select(.{ .location = bold_at + 1 });
+ t.expect(md_style.at(NSFontAttributeName, bold_at - 1) == font and selection().location == bold_at + 1, "moving inside inline markup reveals its source without moving the caret");
+ const typed_attrs = msg(id, page, "typingAttributes", .{});
+ t.expect(msg(id, typed_attrs, "objectForKey:", .{NSFontAttributeName}) == font and msg(id, typed_attrs, "objectForKey:", .{key_group}) != null and msg(id, typed_attrs, "objectForKey:", .{key_ghost}) == yes, "Markdown does not replace typing or metadata attributes");
+ select(.{ .location = len() });
+ t.expect(md_style.at(NSFontAttributeName, bold_at - 1) == hidden and !msg(bool, um, "canUndo", .{}), "leaving a span hides its markers without an Undo step");
+ const saved_md = doc.parse(arena, snapshot(arena) catch unreachable) catch unreachable;
+ t.expect(std.mem.eql(u8, saved_md.body, raw_md) and saved_md.groups.len == 1 and saved_md.ghosts.len == 1, "save retains raw Markdown, group and ghost");
+ const close_strong = doc.utf16Len("💤 **bold _and italic_");
+ stub.beginEvent();
+ insert(page, "", .{ .location = close_strong, .length = 2 });
+ stub.endEvent();
+ t.expect(md_style.at(NSFontAttributeName, bold_at) == font and md_style.at(NSFontAttributeName, italic_at) == italic and md_style.at(NSFontAttributeName, second_at - 2) == bold, "breaking a pair clears old styling without touching another paragraph");
+ msg(void, um, "undo", .{});
+ t.expect(std.mem.eql(u8, objc.utf8(string(page)), raw_md) and md_style.at(NSFontAttributeName, bold_at) == bold, "Undo restores both source and rendered formatting");
+ msg(void, um, "redo", .{});
+ t.expect(md_style.at(NSFontAttributeName, bold_at) == font, "Redo recalculates formatting instead of restoring a style operation");
+ load("## Two\n###### Six");
+ select(.{ .location = len() });
+ t.expect(md_style.at(NSFontAttributeName, 0) == hidden and md_style.at(NSFontAttributeName, 7) == font, "the caret at the end of the last heading reveals just that heading's hashes");
+ select(.{ .location = 5 });
+ t.expect(md_style.at(NSFontAttributeName, 0) == font and md_style.at(NSFontAttributeName, 7) == hidden, "moving between heading titles switches the visible prefix");
+
+ // Fenced code: nothing in it is Markdown, and the fences show only with the caret in the block.
+ load("```zig\n# **raw**\n```\n**after**");
+ select(.{ .location = len() });
+ t.expect(md_style.at(NSFontAttributeName, 0) == hidden and md_style.at(NSFontAttributeName, 17) == hidden, "a code block's fences are out of sight while the caret is elsewhere");
+ t.expect(md_style.at(NSFontAttributeName, 7) == code_font and md_style.at(NSFontAttributeName, 9) == code_font and md_style.at(NSFontAttributeName, 23) == bold, "what is fenced is code, hashes and stars and all, and what follows is not");
+ select(.{ .location = 8 });
+ t.expect(md_style.at(NSFontAttributeName, 0) == code_font and md_style.at(NSFontAttributeName, 17) == code_font, "the caret in the block shows both fences");
+ msg(void, layout, "ensureLayoutForCharacterRange:", .{NSRange{ .length = len() }});
+ stub.beginEvent();
+ insert(page, "", .{ .length = 1 });
+ stub.endEvent();
+ t.expect(md_style.at(NSFontAttributeName, 10) == bold and md_style.at(NSFontAttributeName, 16) == hidden and md_style.at(NSFontAttributeName, 22) == code_font, "breaking a fence restyles all that follows: the old closing fence now opens");
+ msg(void, layout, "ensureLayoutForCharacterRange:", .{NSRange{ .length = len() }});
+ t.expect(msg(u16, layout, "CGGlyphAtIndex:", .{@as(usize, 22)}) == msg(u32, code_font, "glyphWithName:", .{str("a")}), "in the code font's own glyphs, not the ones laid out before");
+ msg(void, um, "undo", .{});
+ t.expect(md_style.at(NSFontAttributeName, 9) == code_font and md_style.at(NSFontAttributeName, 23) == bold, "and Undo puts the block back");
+ t.expect(std.mem.eql(u8, snapshot(arena) catch unreachable, "```zig\n# **raw**\n```\n**after**"), "none of which is in the file");
std.debug.print("selftest ok\n", .{});
}
diff --git a/src/markdown.zig b/src/markdown.zig
new file mode 100644
index 0000000..3009c20
--- /dev/null
+++ b/src/markdown.zig
@@ -0,0 +1,217 @@
+//! A paragraph-local Markdown subset. Offsets address the original UTF-16, never a rewritten string.
+const std = @import("std");
+
+const Kind = enum { star, under, strong_star, strong_under, both_star, both_under, strike, code };
+const kind_count = @typeInfo(Kind).@"enum".fields.len;
+pub const Style = struct {
+ strong: bool = false,
+ emphasis: bool = false,
+ strike: bool = false,
+ code: bool = false,
+};
+
+pub const Mark = struct {
+ at: usize,
+ width: usize,
+ kind: Kind,
+ partner: ?usize = null,
+};
+
+pub const Parser = struct {
+ // Reused across paragraphs and keystrokes.
+ marks: std.ArrayList(Mark) = .empty,
+
+ pub fn parse(p: *Parser, alloc: std.mem.Allocator, text: []const u16) ![]const Mark {
+ p.marks.clearRetainingCapacity();
+ var opener: [kind_count]?usize = @splat(null);
+ var stack: [kind_count]usize = undefined; // at most one pending opener per kind
+ var depth: usize = 0;
+ var ticks: [2]usize = .{ 0, 0 };
+ var i: usize = 0;
+ while (i < text.len) {
+ const c = text[i];
+ if (c == '\\' and i + 1 < text.len and punctuation(text[i + 1])) {
+ i += 2;
+ continue;
+ }
+ if (c != '*' and c != '_' and c != '~' and c != '`') {
+ i += 1;
+ continue;
+ }
+ const at = i;
+ i = runEnd(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);
+ ticks[width - 1] = close;
+ if (close == text.len or close == i) continue;
+ const first = p.marks.items.len;
+ try p.marks.appendSlice(alloc, &.{
+ .{ .at = at, .width = width, .kind = .code, .partner = first + 1 },
+ .{ .at = close, .width = width, .kind = .code, .partner = first },
+ });
+ i = close + width;
+ continue;
+ }
+ const kind: Kind = switch (c) {
+ '*' => switch (width) {
+ 1 => .star,
+ 2 => .strong_star,
+ 3 => .both_star,
+ else => continue,
+ },
+ '_' => switch (width) {
+ 1 => .under,
+ 2 => .strong_under,
+ 3 => .both_under,
+ else => continue,
+ },
+ '~' => if (width == 2) .strike else continue,
+ else => unreachable,
+ };
+ const before = if (at == 0) ' ' else text[at - 1];
+ const after = if (i == text.len) ' ' else text[i];
+ const left = !space(after) and (!punctuation(after) or space(before) or punctuation(before));
+ const right = !space(before) and (!punctuation(before) or space(after) or punctuation(after));
+ const can_open = left and (c != '_' or !right or punctuation(before));
+ const can_close = right and (c != '_' or !left or punctuation(after));
+ const slot = &opener[@intFromEnum(kind)];
+ if (can_close) if (slot.*) |idx| {
+ const open = stack[idx];
+ // Unmatched opens inside a matched pair stay literal. Spans never cross.
+ for (stack[idx..depth]) |pending| opener[@intFromEnum(p.marks.items[pending].kind)] = null;
+ depth = idx;
+ p.marks.items[open].partner = p.marks.items.len;
+ try p.marks.append(alloc, .{ .at = at, .width = width, .kind = kind, .partner = open });
+ continue;
+ };
+ if (can_open and slot.* == null) {
+ slot.* = depth;
+ stack[depth] = p.marks.items.len;
+ depth += 1;
+ try p.marks.append(alloc, .{ .at = at, .width = width, .kind = kind });
+ }
+ }
+ return p.marks.items;
+ }
+};
+
+pub const Active = struct {
+ bits: [kind_count]bool = @splat(false),
+
+ pub fn toggle(a: *Active, mark: Mark) void {
+ const bit = &a.bits[@intFromEnum(mark.kind)];
+ bit.* = !bit.*;
+ }
+
+ fn has(a: Active, kind: Kind) bool {
+ return a.bits[@intFromEnum(kind)];
+ }
+
+ pub fn style(a: Active) Style {
+ if (a.has(.code)) return .{ .code = true, .strike = a.has(.strike) };
+ const both = a.has(.both_star) or a.has(.both_under);
+ return .{
+ .strong = both or a.has(.strong_star) or a.has(.strong_under),
+ .emphasis = both or a.has(.star) or a.has(.under),
+ .strike = a.has(.strike),
+ };
+ }
+};
+
+pub const Line = enum { text, code, fence };
+
+/// Fenced code, a line at a time. `open` is 0 outside a block, else the open fence's width
+/// and character; it is left as the next line will find it. An unclosed block runs to the end.
+pub fn fenceLine(line: []const u16, open: *u32) Line {
+ var i: usize = 0;
+ while (i < 3 and i < line.len and line[i] == ' ') i += 1;
+ 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 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)) {
+ 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) {
+ open.* = 0;
+ return .fence;
+ }
+ }
+ return if (open.* == 0) .text else .code;
+}
+
+fn space(c: u16) bool {
+ return switch (c) {
+ ' ', 9...13, 0x85, 0xa0, 0x1680, 0x2000...0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000 => true,
+ else => false,
+ };
+}
+
+fn punctuation(c: u16) bool {
+ return switch (c) {
+ '!'...'/', ':'...'@', '['...'`', '{'...'~' => true,
+ else => false,
+ };
+}
+
+fn runEnd(text: []const u16, start: usize, c: u16) 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 {
+ var i = start;
+ while (i < text.len) {
+ if (text[i] != '`') {
+ i += 1;
+ continue;
+ }
+ const stop = runEnd(text, i, '`');
+ if (stop - i == width) return i;
+ i = stop;
+ }
+ return text.len;
+}
+
+test "fences open, hold what looks like Markdown, and close only on their own kind" {
+ const L = std.unicode.utf8ToUtf16LeStringLiteral;
+ var open: u32 = 0;
+ const lines = [_]struct { []const u16, Line }{
+ .{ L("``not a fence``\n"), .text },
+ .{ L("```a`b\n"), .text },
+ .{ L(" ```\n"), .text },
+ .{ L(" ````zig\n"), .fence },
+ .{ L("# **raw**\n"), .code },
+ .{ L("```\n"), .code }, // too short to close four
+ .{ L("~~~~\n"), .code },
+ .{ L("```` x\n"), .code },
+ .{ L("````` \r\n"), .fence },
+ .{ L("after\n"), .text },
+ .{ L("~~~ a`b\n"), .fence },
+ .{ L("unclosed"), .code },
+ };
+ for (lines) |l| try std.testing.expectEqual(l[1], fenceLine(l[0], &open));
+ try std.testing.expectEqual(@as(u32, 3 << 1 | 1), open);
+}
+
+test "exact source offsets, literal escapes, and opaque code" {
+ const alloc = std.testing.allocator;
+ var p: Parser = .{};
+ defer p.marks.deinit(alloc);
+ const text = std.unicode.utf8ToUtf16LeStringLiteral("😀***both*** snake_case \\*literal* ``*raw*` ``");
+ const marks = try p.parse(alloc, text);
+ try std.testing.expectEqual(@as(usize, 4), marks.len);
+ try std.testing.expectEqual(Mark{ .at = 2, .width = 3, .kind = .both_star, .partner = 1 }, marks[0]);
+ try std.testing.expectEqual(Mark{ .at = 9, .width = 3, .kind = .both_star, .partner = 0 }, marks[1]);
+ try std.testing.expectEqual(Mark{ .at = text.len - 11, .width = 2, .kind = .code, .partner = 3 }, marks[2]);
+ try std.testing.expectEqual(Mark{ .at = text.len - 2, .width = 2, .kind = .code, .partner = 2 }, marks[3]);
+}