summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--README.md42
-rwxr-xr-xbin/write_away2
-rw-r--r--build.zig.zon2
-rw-r--r--src/doc.zig84
-rw-r--r--src/main.zig302
-rw-r--r--src/markdown.zig148
-rw-r--r--src/objc.zig1
7 files changed, 538 insertions, 43 deletions
diff --git a/README.md b/README.md
index 4d40581..40d1171 100644
--- a/README.md
+++ b/README.md
@@ -26,6 +26,17 @@ zig build test # the document model, then the app driven with no
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.
+### Launch from the terminal
+
+With `Write_Away.app` in `/Applications`, install the launcher into a directory on your `PATH` (here, `~/.local/bin`):
+
+```sh
+mkdir -p "$HOME/.local/bin"
+install -m 755 bin/write_away "$HOME/.local/bin/write_away"
+write_away # launch or bring the editor forward
+write_away "my draft.md" # open an existing file
+```
+
## Using it
| Keys | What happens |
@@ -47,8 +58,16 @@ Right-click the page for alternatives, AI alternatives, ghost/revive, or Overflo
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.
+`[Links](with/targets)` show as their underlined text. Move the caret inside one to see its brackets and target. Reference links stay as written, and a link isn’t clickable yet.
+
+An image alone on its line (`![alt](picture.png)`) shows as the picture, fitted to the column and never enlarged past its own size. Click it, or move the caret onto its line, and the source comes back in its place. Pictures are read from this Mac only: an absolute path, or one relative to the folder the piece is saved in, so an unsaved piece shows none. Nothing is fetched. An image among other text, a remote URL, or a file that can’t be read stays as written.
+
+A line starting with `> ` is a quote: a bar stands in for the marker and the text keeps its indent. A line of three or more `-`, `*` or `_` (all the same, spaces between them allowed) is a rule across the column. Unbroken hyphens directly under a line of text are the exception: Markdown would make that line a heading, so they stay as written. Put the caret on a quote or rule to see its source. Nested quotes stay as written.
+
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.
+YAML frontmatter is shown the same way, with its `---` lines as the fences. It counts only when the first line is `---` and a later line of `---` or `...` closes it; its contents are not parsed.
+
## The Lab
Choose **Lab** in the bottom bar or press **Ctrl+Shift+L** (also in the Write menu); the shortcut leaves read mode if needed. During a review, use **Ctrl+Shift+N** for Next, **Ctrl+Shift+K** for Keep, **Ctrl+Shift+P** for Apply rest, and **Ctrl+Shift+O** for Discard/Original. The in-window chooser has six editing passes and a row of trim strengths. Use the arrow keys to move, Return to choose, or Escape to go back to the draft. A pass can mark weak, long, or convoluted sentences, changes of tone, or filler. Punctuation and typo fixes are proposals until you apply them. **Next** visits the next passage; **Keep** leaves it alone.
@@ -81,8 +100,25 @@ escapes. All hidden text is still readable in the file source.
Write_Away preserves the visible bytes exactly after the blank line that separates the
comments from the draft. A file with no Overflow, alternatives or ghosts is saved
-unchanged. With metadata present, comments precede even YAML frontmatter; its bytes
-are preserved, but tools that require frontmatter on the first line may not recognize it.
+unchanged.
+
+YAML frontmatter stays on the first line: the comments go directly after the line that
+closes it, and the rest of the draft follows their blank line.
+
+```markdown
+---
+title: A draft
+---
+<!-- write_away {"v":2,"groups":[…]} -->
+
+
+# A draft
+```
+
+Files saved earlier with the comments above the frontmatter still open, and move to this
+layout on the next save. If the closing line is the last thing in the file with no line
+break after it, or ghosting leaves the published text without frontmatter, the comments
+go first as before.
Files record UTF-8 byte offsets into the restored editor body. While editing, ghosts are attributes on the text itself; Save computes fresh offsets. A fully ghosted alternative stays ghosted when swapped. If a replacement crosses a ghost boundary, revive the ghosted part first: Write_Away won’t guess which words in another version should be hidden.
@@ -99,7 +135,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/markdown.zig`: matches inline formatting and link delimiters in the editor’s UTF-16 text, and tells fences, frontmatter and rules from text a line at a time.
- `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/bin/write_away b/bin/write_away
new file mode 100755
index 0000000..467c87a
--- /dev/null
+++ b/bin/write_away
@@ -0,0 +1,2 @@
+#!/bin/sh
+exec /usr/bin/open -a /Applications/Write_Away.app -- "$@"
diff --git a/build.zig.zon b/build.zig.zon
index 0e7a29d..1c50060 100644
--- a/build.zig.zon
+++ b/build.zig.zon
@@ -7,5 +7,5 @@
// The AI features ask their model through libpantograph, checked out beside this repo.
.libpantograph = .{ .path = "../libpantograph" },
},
- .paths = .{ "build.zig", "build.zig.zon", "Info.plist", "README.md", "assets", "src" },
+ .paths = .{ "build.zig", "build.zig.zon", "Info.plist", "README.md", "assets", "bin", "src" },
}
diff --git a/src/doc.zig b/src/doc.zig
index 3860809..2320a6a 100644
--- a/src/doc.zig
+++ b/src/doc.zig
@@ -1,6 +1,7 @@
//! The document model and the file format. Pure Zig, no AppKit: `zig build test` covers it.
const std = @import("std");
const ghost_io = @import("ghost_io.zig");
+const markdown = @import("markdown.zig");
const mem = std.mem;
const Allocator = mem.Allocator;
@@ -161,8 +162,10 @@ pub fn suggestion(line: []const u8) ?[]const u8 {
//
// v2 puts optional Overflow and write_away comments before the visible Markdown. One LF
// separates the comments when both are present; two LFs separate the last comment from
-// the exact visible bytes. Legacy comments were trailers. Offsets always address the full
-// editor body, so v2 ghosts must be restored before the alternatives are reanchored.
+// the exact visible bytes. YAML frontmatter is those bytes' one exception: it stays on the
+// file's first line and the comments follow it. Legacy comments were trailers. Offsets
+// always address the full editor body, so v2 ghosts must be restored before the
+// alternatives are reanchored.
const overflow_mark = "<!-- overflow -->"; // legacy
const overflow_open = "<!-- overflow\n(";
@@ -195,8 +198,13 @@ pub fn serialize(gpa: Allocator, f: File) ![]u8 {
const visible = if (f.ghosts.len != 0) try ghost_io.visible(gpa, f.body, f.ghosts) else f.body;
defer if (f.ghosts.len != 0) gpa.free(visible);
+ // Frontmatter cut off by the end of the file has no line break to put a comment after.
+ var front = frontmatter(visible);
+ if (front != 0 and visible[front - 1] != '\n') front = 0;
+
var out: std.ArrayList(u8) = .empty;
errdefer out.deinit(gpa);
+ try out.appendSlice(gpa, visible[0..front]);
if (f.overflow.len > 0) {
try out.appendSlice(gpa, overflow_open);
// Escape ampersands first conceptually: each input byte is emitted only once.
@@ -225,10 +233,24 @@ pub fn serialize(gpa: Allocator, f: File) ![]u8 {
try out.appendSlice(gpa, meta_close);
}
try out.appendSlice(gpa, framing);
- try out.appendSlice(gpa, visible);
+ try out.appendSlice(gpa, visible[front..]);
return out.toOwnedSlice(gpa);
}
+/// The length of the YAML frontmatter `bytes` opens with, through the line that closes it,
+/// or 0. Without that line there is none: a first line of "---" is then only a rule.
+pub fn frontmatter(bytes: []const u8) usize {
+ var at: usize = 0;
+ while (at < bytes.len) {
+ const stop = if (mem.findScalarPos(u8, bytes, at, '\n')) |nl| nl + 1 else bytes.len;
+ const delimiter = markdown.frontDelimiter(u8, bytes[at..stop], at == 0);
+ if (at != 0 and delimiter) return stop;
+ if (at == 0 and !delimiter) return 0;
+ at = stop;
+ }
+ return 0;
+}
+
fn digest(bytes: []const u8) [Sha256.digest_length * 2]u8 {
var hash: [Sha256.digest_length]u8 = undefined;
Sha256.hash(bytes, &hash, .{});
@@ -239,12 +261,15 @@ fn digest(bytes: []const u8) [Sha256.digest_length * 2]u8 {
/// interpret, keep the entire source in the editor, including the recovery metadata.
pub fn parse(arena: Allocator, bytes: []const u8) !File {
const unchanged: File = .{ .body = bytes };
- var rest = bytes;
+ // The comments lead the file, or follow the frontmatter that does.
+ var rest = bytes[frontmatter(bytes)..];
+ if (!mem.startsWith(u8, rest, overflow_open) and !mem.startsWith(u8, rest, meta_open)) rest = bytes;
+ const head = bytes[0 .. bytes.len - rest.len];
var overflow: ?[]const u8 = null;
if (mem.startsWith(u8, rest, overflow_open)) {
const block = splitComment(rest, overflow_open, overflow_close) orelse return unchanged;
if (mem.startsWith(u8, block.rest, framing)) return .{
- .body = block.rest[framing.len..],
+ .body = try mem.concat(arena, u8, &.{ head, block.rest[framing.len..] }),
.overflow = try decodeOverflow(arena, block.payload),
};
if (!mem.startsWith(u8, block.rest, "\n" ++ meta_open)) return parseLegacy(arena, bytes);
@@ -258,7 +283,7 @@ pub fn parse(arena: Allocator, bytes: []const u8) !File {
if (meta.v != 2 or !mem.startsWith(u8, block.rest, framing)) return unchanged;
if ((meta.ghosts.len != 0) != (meta.visible_sha256 != null)) return unchanged;
- const visible = block.rest[framing.len..];
+ const visible = try mem.concat(arena, u8, &.{ head, block.rest[framing.len..] });
const body = if (meta.ghosts.len == 0) visible else body: {
const expected = meta.visible_sha256 orelse return unchanged;
if (!mem.eql(u8, &expected, &digest(visible))) return unchanged;
@@ -430,7 +455,7 @@ pub fn classify(para: []const u8, start: usize, end: usize) Scope {
const after = mem.trim(u8, para[end..], space);
if (sel.len == 0) return .word;
- const at_head = mem.trimStart(u8, before, "# ").len == 0; // heading marks do not count
+ const at_head = mem.trimStart(u8, before, "#> ").len == 0; // heading and quote marks do not count
const starts = at_head or isStop(before[before.len - 1]);
const ends = after.len == 0 or isStop(sel[sel.len - 1]);
if (!starts or !ends) return .word;
@@ -701,6 +726,51 @@ test "v2 restores adjacent UTF-8 ghosts and overlapping groups after an editor e
try t.expectError(error.InvalidGhost, serialize(a, .{ .body = body, .ghosts = &.{.{ .at = 0, .text = last }} }));
}
+test "comments follow YAML frontmatter, which keeps the first line" {
+ const t = std.testing;
+ var state: std.heap.ArenaAllocator = .init(t.allocator);
+ defer state.deinit();
+ const a = state.allocator();
+ try t.expectEqual(7, frontmatter("---\n---"));
+ try t.expectEqual(17, frontmatter("--- \r\nk: v\n... \r\n---\n"));
+ for ([_][]const u8{ "", "---", "---\nk: v\n", "---\nk: v\n ---\n", "\n---\n---\n", "...\n---\n", "----\n---\n" }) |none| try t.expectEqual(0, frontmatter(none));
+
+ const front = "---\ntitle: café\n---\n";
+ const rest = "\n# Title\n\n---\n";
+ const file: File = .{
+ .body = front ++ rest,
+ .overflow = "Kept.",
+ .groups = &.{.{ .at = front.len + 3, .variants = &.{ "Title", "Name" } }},
+ .ghosts = &.{.{ .at = 4, .text = "title" }},
+ };
+ const bytes = try serialize(a, file);
+ try t.expect(mem.startsWith(u8, bytes, "---\n: café\n---\n" ++ overflow_open));
+ try t.expect(mem.endsWith(u8, bytes, meta_close ++ framing ++ rest));
+ const back = try parse(a, bytes);
+ try t.expectEqualStrings(file.body, back.body);
+ try t.expectEqualStrings("Kept.", back.overflow);
+ try t.expectEqual(front.len + 3, back.groups[0].at);
+ try t.expectEqual(4, back.ghosts[0].at);
+ const stashed = try serialize(a, .{ .body = front ++ rest, .overflow = "Kept." });
+ try t.expectEqualStrings(front ++ overflow_open ++ "Kept." ++ overflow_close ++ framing ++ rest, stashed);
+ try t.expectEqualStrings(front ++ rest, (try parse(a, stashed)).body);
+
+ // A file saved with its comments first still opens, and saves the new way.
+ const old = try parse(a, overflow_open ++ "Kept." ++ overflow_close ++ framing ++ front ++ rest);
+ try t.expectEqualStrings(front ++ rest, old.body);
+ try t.expectEqualStrings(stashed, try serialize(a, old));
+ // With no line of its own to close on, or a ghost for a delimiter, the comments lead.
+ const cut_off = try serialize(a, .{ .body = "---\nk: v\n---", .overflow = "Kept." });
+ try t.expect(mem.startsWith(u8, cut_off, overflow_open));
+ try t.expectEqualStrings("---\nk: v\n---", (try parse(a, cut_off)).body);
+ const hidden: File = .{ .body = front ++ rest, .ghosts = &.{.{ .at = 0, .text = "---" }} };
+ const leading = try serialize(a, hidden);
+ try t.expect(mem.startsWith(u8, leading, meta_open));
+ try t.expectEqualStrings(hidden.body, (try parse(a, leading)).body);
+ // Frontmatter before a comment that cannot be read is left exactly as it is.
+ try expectRaw(a, front ++ meta_open ++ "{nope" ++ meta_close ++ framing ++ rest);
+}
+
test "plain Markdown is byte-exact; v1 ghosts and ghost-free v2 groups still follow their text" {
const t = std.testing;
var state: std.heap.ArenaAllocator = .init(t.allocator);
diff --git a/src/main.zig b/src/main.zig
index e8e4c21..91d611e 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -35,6 +35,8 @@ extern const NSBackgroundColorAttributeName: id;
extern const NSParagraphStyleAttributeName: id;
extern const NSViewFrameDidChangeNotification: id;
extern const NSAppearanceNameDarkAqua: id;
+extern const NSFileTypeRegular: id;
+extern const NSDeviceRGBColorSpace: id;
extern fn NSRectFill(rect: NSRect) void;
extern fn NSBeep() void;
@@ -80,6 +82,10 @@ 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_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
+var pictures: id = null; // every picture this piece has shown, by its file's path
var yes: id = null;
var font: id = null;
var bold: id = null;
@@ -91,12 +97,16 @@ var code_font: id = null;
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_units: std.ArrayList(u16) = .empty;
var markdown_parser: markdown.Parser = .{};
-var markdown_strike: id = null;
+var markdown_line: id = null; // a single line, struck through the text or under a link
+var spaced: id = null; // the page's paragraph style,
+var quote_shown: id = null; // a quoted paragraph's with the caret in it, its lines hung from the "> ",
+var quote_hidden: id = null; // and without: indented by as much as the "> " that is out of sight
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, code: 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, link: id } = undefined;
var groups: std.AutoArrayHashMapUnmanaged(u32, doc.Group) = .empty;
var next_id: u32 = 1;
@@ -510,10 +520,15 @@ fn markdownRefresh() void {
markdown_dirty = null;
if (n == 0) return;
- const dirty = if (changed) |r| markdownRange(
+ var dirty = if (changed) |r| markdownRange(
paragraphOf(page, .{ .location = @min(r.location, n) }).location,
end(paragraphOf(page, .{ .location = @min(end(r), n) })),
) else NSRange{};
+ if (changed != null) {
+ // The line that closes frontmatter makes its first line an opening one, from afar.
+ markdown_front = charAt(0) == '-' and doc.frontmatter(objc.utf8(string(page))) != 0;
+ if (markdown_front != (fenceAt(0) == markdown.front)) dirty = markdownRange(0, @max(end(dirty), end(paragraphOf(page, .{}))));
+ }
markdown_rendering = true;
defer markdown_rendering = false;
msg(void, storage, "beginEditing", .{});
@@ -570,6 +585,7 @@ fn markdownFences(caret: ?usize) void {
setMarkdownAttribute(line, NSFontAttributeName, if (show) code_font else hidden);
setMarkdownAttribute(line, NSForegroundColorAttributeName, if (show) color.dim else color.clear);
setMarkdownAttribute(line, NSStrikethroughStyleAttributeName, null);
+ setMarkdownAttribute(line, NSUnderlineStyleAttributeName, null);
}
}
}
@@ -579,35 +595,105 @@ 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);
+ const units = markdown_units.items;
+ const kind = markdown.fenceLine(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 quote = prefix != 0 and units[0] == '>';
+ const rule = kind == .text 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;
+ 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);
+ setMarkdownAttribute(para, NSParagraphStyleAttributeName, if (picture != null) pictureStyle(picture) else if (!quote) spaced else if (here) quote_shown else quote_hidden);
switch (kind) {
.fence => return, // `markdownFences` shows or hides it
.code => return markdownPaint(para, .{ .code = true }, false, false),
.text => {},
}
- const prefix = marker(para);
+ if (rule or picture != null) return markdownPaint(para, .{}, false, !here);
+ const heading = prefix != 0 and !quote;
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);
+ markdownPaint(markdownRange(para.location, body.location), .{}, false, !here);
+ const marks = markdown_parser.parse(gpa, units[prefix..]) catch return markdownPaint(body, .{}, heading, 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);
+ markdownPaint(markdownRange(at, tag.location), active.style(), heading, 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);
+ markdownPaint(tag, .{}, heading, !reveal);
active.toggle(mark_);
at = end(tag);
}
- markdownPaint(markdownRange(at, end(body)), active.style(), prefix != 0, false);
+ markdownPaint(markdownRange(at, end(body)), active.style(), heading, false);
+}
+
+/// The picture an image's target names, if that is a file on this Mac that is one. A
+/// relative path starts from the folder the piece is saved in. Nothing is fetched.
+fn pictureAt(named: []const u16) id {
+ if (named.len == 0) return null;
+ var path = msg(id, objc.class("NSString"), "stringWithCharacters:length:", .{ named.ptr, named.len });
+ path = msg(id, path, "stringByRemovingPercentEncoding", .{}) orelse path;
+ if (!msg(bool, path, "isAbsolutePath", .{})) {
+ const piece = file_path orelse return null;
+ path = msg(id, msg(id, str(piece), "stringByDeletingLastPathComponent", .{}), "stringByAppendingPathComponent:", .{path});
+ }
+ path = msg(id, path, "stringByResolvingSymlinksInPath", .{});
+ if (msg(id, pictures, "objectForKey:", .{path})) |known| return known;
+ // Only a file is read: a pipe or a device could keep the page waiting for ever.
+ const attrs = msg(id, msg(id, objc.class("NSFileManager"), "defaultManager", .{}), "attributesOfItemAtPath:error:", .{ path, @as(?*id, null) });
+ if (!msg(bool, msg(id, attrs, "fileType", .{}), "isEqualToString:", .{NSFileTypeRegular})) return null;
+ const picture = msg(id, msg(id, msg(id, objc.class("NSImage"), "alloc", .{}), "initWithContentsOfFile:", .{path}), "autorelease", .{}) orelse return null;
+ const size = msg(NSSize, picture, "size", .{});
+ if (!(size.width > 0 and size.height > 0)) return null;
+ msg(void, pictures, "setObject:forKey:", .{ picture, path });
+ return picture;
+}
+
+/// How big a picture is on the page: as wide as the column's text at most, and never
+/// larger than life.
+fn pictureSize(picture: id) NSSize {
+ const natural = msg(NSSize, picture, "size", .{});
+ const container = msg(id, page, "textContainer", .{});
+ const room = msg(NSSize, container, "containerSize", .{}).width - 2 * msg(f64, container, "lineFragmentPadding", .{});
+ const width = @min(natural.width, room);
+ return .{ .width = width, .height = @ceil(width * natural.height / natural.width) };
+}
+
+/// A line as tall as its picture: the source, out of sight, holds the place.
+fn pictureStyle(picture: id) id {
+ const style = msg(id, msg(id, spaced, "mutableCopy", .{}), "autorelease", .{});
+ msg(void, style, "setMinimumLineHeight:", .{pictureSize(picture).height});
+ return style;
+}
+
+/// A column of another width has room for pictures of another height.
+fn refitPictures() void {
+ const was = markdown_rendering;
+ markdown_rendering = true;
+ defer markdown_rendering = was;
+ msg(void, storage, "beginEditing", .{});
+ defer msg(void, storage, "endEditing", .{});
+ var it: Runs = .{ .key = key_picture };
+ while (it.next()) |run| setMarkdownAttribute(run.range, NSParagraphStyleAttributeName, pictureStyle(run.value));
+}
+
+/// Under a line of text, hyphens are not a rule: Markdown reads them as making that line a heading.
+fn underlines(at: usize) bool {
+ if (at == 0) return false;
+ const above = paragraphOf(page, .{ .location = at - 1 });
+ return trimmed(above).length != 0 and marker(above) == 0;
}
fn markdownPaint(r: NSRange, style: markdown.Style, heading: bool, hide: bool) void {
@@ -616,15 +702,18 @@ fn markdownPaint(r: NSRange, style: markdown.Style, heading: bool, hide: bool) v
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;
+ const link = style.link and !hide;
setMarkdownAttribute(r, NSFontAttributeName, face);
- setMarkdownAttribute(r, NSForegroundColorAttributeName, if (hide) color.clear else color.text);
- setMarkdownAttribute(r, NSStrikethroughStyleAttributeName, if (style.strike) markdown_strike else null);
+ setMarkdownAttribute(r, NSForegroundColorAttributeName, if (hide) color.clear else if (link) color.link else color.text);
+ setMarkdownAttribute(r, NSStrikethroughStyleAttributeName, if (style.strike) markdown_line else null);
+ setMarkdownAttribute(r, NSUnderlineStyleAttributeName, if (link) markdown_line else null);
}
fn setMarkdownAttribute(r: NSRange, key: id, want: id) void {
var run: NSRange = .{};
const have = msg(id, storage, "attribute:atIndex:longestEffectiveRange:inRange:", .{ key, r.location, &run, r });
- if (have == want and run.length == r.length) return;
+ // 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;
if (want != null) {
msg(void, storage, "addAttribute:value:range:", .{ key, want, r });
} else {
@@ -632,9 +721,14 @@ fn setMarkdownAttribute(r: NSRange, key: id, want: id) void {
}
}
-/// How much of a paragraph is a heading's marker: three characters of "## Title".
+/// How much of a paragraph is its marker: three characters of "## Title", two of "> quoted".
fn marker(para: NSRange) usize {
- if (fenceBefore(para.location) != 0) return 0; // code, not a heading
+ if (para.length == 0 or fenceBefore(para.location) != 0) return 0; // code, not a heading
+ if (charAt(para.location) == '>') {
+ if (para.length == 1) return 1;
+ const next = charAt(para.location + 1);
+ return if (next == ' ') 2 else @intFromBool(next == '\n' or next == '\r'); // ">" alone is a quote's blank line
+ }
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;
@@ -1648,6 +1742,7 @@ fn load(bytes: []const u8) void {
for (groups.values()) |*g| g.deinit(gpa);
groups.clearRetainingCapacity();
+ msg(void, pictures, "removeAllObjects", .{}); // opening again reads them again
hover = 0;
target = 0;
home.clearRetainingCapacity();
@@ -1707,6 +1802,11 @@ fn snapshot(arena: std.mem.Allocator) ![]u8 {
}
fn setPath(path: ?[]const u8) void {
+ const moved = if (path) |p| (if (file_path) |old| !std.mem.eql(u8, old, p) else true) else file_path != null;
+ defer if (moved) { // pictures are found from where the piece is
+ markdown_dirty = .{ .length = len() };
+ markdownRefresh();
+ };
const new = if (path) |p| gpa.dupe(u8, p) catch null else null;
if (file_path) |old| gpa.free(old);
file_path = new;
@@ -1867,7 +1967,10 @@ fn resized(_: id, _: SEL, _: id) callconv(.c) void {
const inset: NSSize = .{ .width = @max(least, (w - column) / 2), .height = top_inset };
const reflow = msg(NSSize, container, "containerSize", .{}).width != column;
if (!reflow and std.meta.eql(inset, msg(NSSize, page, "textContainerInset", .{}))) return;
- if (reflow) msg(void, container, "setContainerSize:", .{NSSize{ .width = column, .height = 1e7 }});
+ if (reflow) {
+ msg(void, container, "setContainerSize:", .{NSSize{ .width = column, .height = 1e7 }});
+ refitPictures();
+ }
msg(void, page, "setTextContainerInset:", .{inset});
// Moving the column does not move AppKit's blinking insertion indicator with it.
msg(void, page, "updateInsertionPointStateAndRestartTimer:", .{false});
@@ -2009,18 +2112,51 @@ fn drawBackground(self: id, _: SEL, dirty: NSRect) callconv(.c) void {
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 lines = linesOf(markdownRange(run.range.location, stop)) orelse continue;
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 },
+ .origin = .{ .x = lines.origin.x - pad, .y = lines.origin.y - line_gap / 2 },
+ .size = .{ .width = lines.size.width + 2 * pad, .height = lines.size.height },
};
msg(void, color.code, "setFill", .{});
msg(void, msg(id, objc.class("NSBezierPath"), "bezierPathWithRoundedRect:xRadius:yRadius:", .{ box, @as(f64, 8), @as(f64, 8) }), "fill", .{});
}
+ // Where a rule's source is out of sight, a line across the column at the height of its text. And
+ // down the side of quoted lines a bar, where each ">" would be.
+ msg(void, color.ring, "setFill", .{});
+ const padding = msg(f64, container, "lineFragmentPadding", .{});
+ var rules: Runs = .{ .key = key_rule };
+ while (rules.next()) |run| {
+ var at = run.range.location;
+ while (at < end(run.range)) {
+ const para = paragraphOf(page, .{ .location = at });
+ at = end(para);
+ const line = linesOf(para) orelse continue;
+ NSRectFill(.{
+ .origin = .{ .x = line.origin.x + padding, .y = line.origin.y + @floor((line.size.height - line_gap) / 2) },
+ .size = .{ .width = line.size.width - 2 * padding, .height = 1 },
+ });
+ }
+ }
+ var quotes: Runs = .{ .key = key_quote };
+ while (quotes.next()) |run| {
+ const lines = linesOf(run.range) orelse continue;
+ NSRectFill(.{ .origin = .{ .x = lines.origin.x + padding + 2, .y = lines.origin.y }, .size = .{ .width = 3, .height = lines.size.height - line_gap } });
+ }
+ // Each picture, in the room its line was given: see `pictureStyle`.
+ var shown: Runs = .{ .key = key_picture };
+ while (shown.next()) |run| {
+ var at = run.range.location; // the same picture twice running is one run
+ while (at < end(run.range)) {
+ const para = paragraphOf(page, .{ .location = at });
+ at = end(para);
+ const line = linesOf(para) orelse continue;
+ const box: NSRect = .{ .origin = .{ .x = line.origin.x + padding, .y = line.origin.y }, .size = pictureSize(run.value) };
+ if (box.origin.y > dirty.origin.y + dirty.size.height or box.origin.y + box.size.height < dirty.origin.y) continue;
+ const source_over: usize = 2;
+ msg(void, run.value, "drawInRect:fromRect:operation:fraction:respectFlipped:hints:", .{ box, NSRect{}, source_over, @as(f64, 1), true, @as(id, null) });
+ }
+ }
if (!tools) return;
var it: Runs = .{ .key = key_group };
while (it.next()) |run| {
@@ -2070,6 +2206,19 @@ fn drawBackground(self: id, _: SEL, dirty: NSRect) callconv(.c) void {
}
}
+/// The lines of the page that `r` runs over, as one box in the page's coordinates.
+fn linesOf(r: NSRange) ?NSRect {
+ const glyphs = msg(NSRange, layout, "glyphRangeForCharacterRange:actualCharacterRange:", .{ r, @as(?*NSRange, null) });
+ if (glyphs.length == 0) return null;
+ const origin = msg(NSPoint, page, "textContainerOrigin", .{});
+ 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) });
+ return .{
+ .origin = .{ .x = origin.x + top.origin.x, .y = origin.y + top.origin.y },
+ .size = .{ .width = top.size.width, .height = bottom.origin.y + bottom.size.height - top.origin.y },
+ };
+}
+
/// Beside each row of the alternatives panel, its marker: a disc for the variant showing,
/// a speck for the others, a box for one the AI wrote.
fn drawRows(self: id, _: SEL, dirty: NSRect) callconv(.c) void {
@@ -2215,6 +2364,7 @@ fn setup(app: id) void {
.hover = rgb(0x98a8e2, 0.14),
.selection = rgb(0x817cd4, 0.28),
.code = rgb(0x121522, 1),
+ .link = rgb(0x98a8e2, 1),
};
const regular: f64 = 0;
const heavy: f64 = 0.4;
@@ -2226,18 +2376,28 @@ fn setup(app: id) void {
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", .{});
+ markdown_line = 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", .{});
+ key_rule = msg(id, str("WriteAwayRule"), "retain", .{});
+ key_quote = msg(id, str("WriteAwayQuote"), "retain", .{});
+ key_picture = msg(id, str("WriteAwayPicture"), "retain", .{});
+ pictures = objc.new("NSMutableDictionary");
yes = msg(id, msg(id, objc.class("NSNumber"), "numberWithBool:", .{true}), "retain", .{});
- const spaced = objc.new("NSMutableParagraphStyle");
+ spaced = objc.new("NSMutableParagraphStyle");
msg(void, spaced, "setLineSpacing:", .{@as(f64, line_gap)});
// A heading with nothing after its marker yet is still a line of full height.
msg(void, spaced, "setMinimumLineHeight:", .{msg(f64, msg(id, objc.new("NSLayoutManager"), "autorelease", .{}), "defaultLineHeightForFont:", .{font})});
+ // A quote's text stands where its source has it, so nothing moves when the "> " shows.
+ const quote_indent = msg(NSSize, str("> "), "sizeWithAttributes:", .{dict(&.{.{ NSFontAttributeName, font }})}).width;
+ quote_shown = msg(id, spaced, "mutableCopy", .{});
+ msg(void, quote_shown, "setHeadIndent:", .{quote_indent});
+ quote_hidden = msg(id, quote_shown, "mutableCopy", .{});
+ msg(void, quote_hidden, "setFirstLineHeadIndent:", .{quote_indent});
base_attrs = msg(id, dict(&.{
.{ NSFontAttributeName, font },
.{ NSForegroundColorAttributeName, color.text },
@@ -2919,7 +3079,7 @@ fn selftest() void {
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, italic_at) == bold_italic and md_style.at(NSFontAttributeName, code_at) == code_font and md_style.at(NSStrikethroughStyleAttributeName, cut_at) == markdown_line, "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");
@@ -2961,5 +3121,91 @@ fn selftest() void {
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");
+
+ // Frontmatter, rules, quotes and links show as what they mean until the caret is on them.
+ const blocks = "---\ntitle: a_b_c\n---\n\n---\n\n> quoted **loud**\n\ntext\n---\nsee [the _docs_](https://a.b/c_d_e) and ![img](x)";
+ const find = struct {
+ fn at(comptime text: []const u8, comptime what: []const u8) usize {
+ return comptime std.mem.indexOf(u8, text, what).?;
+ }
+ }.at;
+ const rule_at = find(blocks, "\n\n---\n\n") + 2;
+ const quote_at = find(blocks, "> quoted");
+ const link_at = find(blocks, "[the");
+ const target_at = find(blocks, "c_d_e") + 2;
+ const img_at = find(blocks, "[img");
+ load(blocks);
+ select(.{ .location = len() });
+ t.expect(md_style.at(NSFontAttributeName, 0) == hidden and md_style.at(NSFontAttributeName, 17) == hidden and md_style.at(key_rule, 0) == null and md_style.at(NSFontAttributeName, find(blocks, "b_c")) == code_font, "frontmatter is a block of code between delimiters that are not rules");
+ t.expect(md_style.at(key_rule, rule_at) == yes and md_style.at(NSFontAttributeName, rule_at) == hidden, "a line of hyphens is a rule, its hyphens out of sight");
+ t.expect(md_style.at(key_rule, find(blocks, "text\n---") + 5) == null and md_style.at(NSFontAttributeName, find(blocks, "text\n---") + 5) == font, "but not right under a line of text, where it would make a heading");
+ t.expect(md_style.at(key_quote, quote_at) == yes and md_style.at(NSFontAttributeName, quote_at) == hidden and md_style.at(NSFontAttributeName, find(blocks, "loud")) == bold, "a quoted line has a bar for its marker, and its own formatting");
+ t.expect(msg(bool, md_style.at(NSParagraphStyleAttributeName, quote_at), "isEqual:", .{quote_hidden}) and msg(bool, md_style.at(NSParagraphStyleAttributeName, rule_at), "isEqual:", .{spaced}), "and it alone is indented");
+ t.expect(md_style.at(NSFontAttributeName, link_at) == hidden and md_style.at(NSFontAttributeName, target_at) == hidden and md_style.at(NSFontAttributeName, find(blocks, "docs")) == italic, "a link shows as its text, formatted, and its target's underscores are not emphasis");
+ t.expect(md_style.at(NSUnderlineStyleAttributeName, link_at + 1) == markdown_line and msg(bool, md_style.at(NSForegroundColorAttributeName, link_at + 1), "isEqual:", .{color.link}) and md_style.at(NSUnderlineStyleAttributeName, link_at - 1) == null, "underlined, in a color of its own");
+ t.expect(md_style.at(NSFontAttributeName, img_at) == font and md_style.at(NSUnderlineStyleAttributeName, img_at + 1) == null, "an image is left as written");
+ select(.{ .location = rule_at + 1 });
+ t.expect(md_style.at(key_rule, rule_at) == null and md_style.at(NSFontAttributeName, rule_at) == font, "the caret on a rule shows its hyphens");
+ select(.{ .location = quote_at + 3 });
+ t.expect(md_style.at(key_rule, rule_at) == yes and md_style.at(key_quote, quote_at) == null and md_style.at(NSFontAttributeName, quote_at) == font, "and on a quoted line its marker");
+ t.expect(msg(bool, md_style.at(NSParagraphStyleAttributeName, quote_at), "isEqual:", .{quote_shown}), "with the text left standing where it was");
+ select(.{ .location = link_at + 2 });
+ t.expect(md_style.at(key_quote, quote_at) == yes and md_style.at(NSFontAttributeName, link_at) == font and md_style.at(NSFontAttributeName, target_at) == font and md_style.at(NSUnderlineStyleAttributeName, link_at + 1) == markdown_line, "and in a link its brackets and its target");
+ t.expect(!msg(bool, um, "canUndo", .{}) and std.mem.eql(u8, snapshot(arena) catch unreachable, blocks), "none of which is an edit, or in the file");
+ msg(void, over, "setString:", .{str("Kept.")});
+ const fronted = snapshot(arena) catch unreachable;
+ t.expect(std.mem.startsWith(u8, fronted, "---\ntitle: a_b_c\n---\n<!-- overflow\n(Kept.)-->\n\n\n---\n"), "the file's comments go after its frontmatter");
+ load(fronted);
+ t.expect(std.mem.eql(u8, objc.utf8(string(page)), blocks) and std.mem.eql(u8, objc.utf8(string(over)), "Kept."), "and it opens as it was");
+
+ load("text\n***\n_ _ _\ntext\n---");
+ t.expect(md_style.at(key_rule, 5) == yes and md_style.at(key_rule, 9) == yes and md_style.at(NSFontAttributeName, 5) == hidden and md_style.at(key_rule, 20) == null, "asterisks and underscores rule the page off too, under text as only hyphens cannot");
+
+ // Frontmatter needs the line that closes it. Without one its first line is only a rule.
+ load("---\ntitle: x\n---\nbody");
+ select(.{ .location = len() });
+ t.expect(md_style.at(NSFontAttributeName, 4) == code_font and md_style.at(key_rule, 0) == null, "closed frontmatter is code");
+ stub.beginEvent();
+ insert(page, "", .{ .location = 13, .length = 4 });
+ stub.endEvent();
+ t.expect(md_style.at(NSFontAttributeName, 4) == font and md_style.at(key_fence, 4) == null and md_style.at(key_rule, 0) == yes, "taking its closing line away restyles it from the top");
+ 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 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:", .{
+ @as(?*anyopaque, null), @as(isize, 1560), @as(isize, 780), @as(isize, 8), @as(isize, 4), true, false, NSDeviceRGBColorSpace, @as(isize, 0), @as(isize, 0),
+ });
+ const png = msg(id, bitmap, "representationUsingType:properties:", .{ @as(usize, 4), dict(&.{}) });
+ t.expect(msg(bool, png, "writeToFile:atomically:", .{ msg(id, path, "stringByAppendingPathComponent:", .{str("a wide one.png")}), true }), "with a picture twice as wide as the column");
+ const piece = "![wide](a%20wide%20one.png)\n\nsee ![it](a%20wide%20one.png)\n\n![gone](missing.png)\n";
+ const tall = struct {
+ fn height() f64 {
+ return msg(f64, msg(id, storage, "attribute:atIndex:effectiveRange:", .{ NSParagraphStyleAttributeName, @as(usize, 0), @as(?*NSRange, null) }), "minimumLineHeight", .{});
+ }
+ }.height;
+ setPath(null);
+ load(piece);
+ select(.{ .location = len() });
+ t.expect(md_style.at(key_picture, 0) == null and md_style.at(NSFontAttributeName, 0) == font, "an unsaved piece has nowhere to look for a picture from");
+ setPath(objc.utf8(msg(id, path, "stringByAppendingPathComponent:", .{str("piece.md")})));
+ const room = msg(NSSize, container, "containerSize", .{}).width - 2 * msg(f64, container, "lineFragmentPadding", .{});
+ t.expect(md_style.at(key_picture, 0) != null and md_style.at(NSFontAttributeName, 0) == hidden and tall() == @ceil(room / 2), "saved beside it, the line is its picture, fitted to the column");
+ t.expect(md_style.at(key_picture, find(piece, "see")) == null and md_style.at(key_picture, find(piece, "![gone")) == null and md_style.at(NSFontAttributeName, find(piece, "![gone")) == font, "an image among text, or with no file, stays as written");
+ const frame = linesOf(.{ .length = 1 }).?;
+ const clicked = msg(usize, page, "characterIndexForInsertionAtPoint:", .{NSPoint{ .x = frame.origin.x + room / 2, .y = frame.origin.y + frame.size.height / 2 }});
+ t.expect(frame.size.height >= tall() and clicked <= find(piece, "\n"), "a click anywhere on the picture lands in its line");
+ select(.{ .location = clicked });
+ t.expect(md_style.at(key_picture, 0) == null and md_style.at(NSFontAttributeName, 0) == font and msg(bool, md_style.at(NSParagraphStyleAttributeName, 0), "isEqual:", .{spaced}), "and the caret there puts its source back");
+ select(.{ .location = len() });
+ msg(void, container, "setContainerSize:", .{NSSize{ .width = room / 2 + 2 * msg(f64, container, "lineFragmentPadding", .{}), .height = 1e7 }});
+ refitPictures();
+ t.expect(tall() == @ceil(room / 4), "a narrower column has a shorter picture");
+ resized(null, null, null);
+ t.expect(tall() == @ceil(room / 2) and !msg(bool, um, "canUndo", .{}) and std.mem.eql(u8, snapshot(arena) catch unreachable, piece), "and none of it is an edit, or in the file");
+ setPath(null);
+ t.expect(md_style.at(key_picture, 0) == null and msg(bool, fm, "removeItemAtPath:error:", .{ path, @as(?*id, null) }), "remove the folder");
+ msg(void, document_defaults, "removePersistentDomainForName:", .{unique});
std.debug.print("selftest ok\n", .{});
}
diff --git a/src/markdown.zig b/src/markdown.zig
index 3009c20..253cd94 100644
--- a/src/markdown.zig
+++ b/src/markdown.zig
@@ -1,15 +1,17 @@
//! 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 = enum { star, under, strong_star, strong_under, both_star, both_under, strike, code, link };
const kind_count = @typeInfo(Kind).@"enum".fields.len;
pub const Style = struct {
strong: bool = false,
emphasis: bool = false,
strike: bool = false,
code: bool = false,
+ link: bool = false,
};
+/// A link's two marks are its "[" and everything from its "]" to the end of its target.
pub const Mark = struct {
at: usize,
width: usize,
@@ -27,6 +29,8 @@ pub const Parser = struct {
var stack: [kind_count]usize = undefined; // at most one pending opener per kind
var depth: usize = 0;
var ticks: [2]usize = .{ 0, 0 };
+ // The one link that is open: its first mark, its "]", and where its target ends.
+ var link: ?struct { mark: usize, close: usize, stop: usize } = null;
var i: usize = 0;
while (i < text.len) {
const c = text[i];
@@ -34,6 +38,21 @@ pub const Parser = struct {
i += 2;
continue;
}
+ if (c == '[') {
+ // A code span can swallow the "]" that was looked for. An image stays as written.
+ const free = if (link) |l| i > l.close else true;
+ if (free and (i == 0 or text[i - 1] != '!')) if (linkEnd(text, i)) |found| if (found[0] != i + 1) {
+ link = .{ .mark = p.marks.items.len, .close = found[0], .stop = found[1] };
+ try p.marks.append(alloc, .{ .at = i, .width = 1, .kind = .link });
+ };
+ } else if (c == ']') if (link) |l| if (l.close == i) {
+ // The target is skipped: its underscores are not emphasis.
+ p.marks.items[l.mark].partner = p.marks.items.len;
+ try p.marks.append(alloc, .{ .at = i, .width = l.stop - i, .kind = .link, .partner = l.mark });
+ link = null;
+ i = l.stop;
+ continue;
+ };
if (c != '*' and c != '_' and c != '~' and c != '`') {
i += 1;
continue;
@@ -111,21 +130,36 @@ pub const Active = struct {
}
pub fn style(a: Active) Style {
- if (a.has(.code)) return .{ .code = true, .strike = a.has(.strike) };
+ if (a.has(.code)) return .{ .code = true, .strike = a.has(.strike), .link = a.has(.link) };
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),
+ .link = a.has(.link),
};
}
};
pub const Line = enum { text, code, fence };
+/// `open` inside YAML frontmatter. No fence is so narrow.
+pub const front: u32 = 1;
+
/// 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 {
+/// Frontmatter is a block too, fenced by its delimiters. Only the caller can know that the
+/// piece's first line `opens_front`: that takes a line further on to close it.
+pub fn fenceLine(line: []const u16, open: *u32, opens_front: bool) Line {
+ if (opens_front) {
+ open.* = front;
+ return .fence;
+ }
+ if (open.* == front) {
+ if (!frontDelimiter(u16, line, false)) return .code;
+ open.* = 0;
+ return .fence;
+ }
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] == '~')) {
@@ -148,6 +182,71 @@ pub fn fenceLine(line: []const u16, open: *u32) Line {
return if (open.* == 0) .text else .code;
}
+fn blanks(comptime T: type) []const T {
+ return &.{ ' ', '\t', '\r', '\n' };
+}
+
+/// A line that delimits YAML frontmatter: "---", or to close it "..." as well.
+pub fn frontDelimiter(comptime T: type, line: []const T, opening: bool) bool {
+ const s = std.mem.trimEnd(T, line, blanks(T));
+ return s.len == 3 and (std.mem.allEqual(T, s, '-') or (!opening and std.mem.allEqual(T, s, '.')));
+}
+
+pub const Rule = enum { no, yes, hyphens };
+
+/// A rule across the page: three or more of one of "-", "*" and "_", with any blanks among
+/// them, indented by less than code is. Unbroken `.hyphens` are a rule too, except under a
+/// line of text, which they underline into a heading: the caller can see that line.
+pub fn rule(line: []const u16) Rule {
+ var i: usize = 0;
+ while (i < 3 and i < line.len and line[i] == ' ') i += 1;
+ const s = std.mem.trimEnd(u16, line[i..], blanks(u16));
+ if (s.len == 0 or (s[0] != '-' and s[0] != '*' and s[0] != '_')) return .no;
+ var n: usize = 0;
+ for (s) |c| {
+ if (c == s[0]) n += 1 else if (c != ' ' and c != '\t') return .no;
+ }
+ if (n < 3) return .no;
+ return if (s[0] == '-' and n == s.len) .hyphens else .yes;
+}
+
+/// The target of the image that is all there is on `line`: of "![alt](target)", or of
+/// "![alt](target "title")". Only such a line can be shown as its picture.
+pub fn image(line: []const u16) ?[]const u16 {
+ const s = std.mem.trim(u16, line, blanks(u16));
+ if (s.len < 2 or s[0] != '!' or s[1] != '[') return null;
+ const found = linkEnd(s, 1) orelse return null;
+ if (found[1] != s.len) return null;
+ const inner = std.mem.trim(u16, s[found[0] + 2 .. s.len - 1], &.{ ' ', '\t' });
+ const target = inner[0 .. std.mem.indexOfAny(u16, inner, &.{ ' ', '\t' }) orelse inner.len];
+ return if (target.len == 0) null else target;
+}
+
+/// For the link or image whose text opens at `open`: its "]", and where its "(target)" ends.
+fn linkEnd(text: []const u16, open: usize) ?[2]usize {
+ const close = matching(text, open, '[', ']') orelse return null;
+ if (close + 1 == text.len or text[close + 1] != '(') return null;
+ const stop = matching(text, close + 1, '(', ')') orelse return null;
+ return .{ close, stop + 1 };
+}
+
+/// The bracket that closes the one at `start`, past any nested in it or escaped.
+fn matching(text: []const u16, start: usize, left: u16, right: u16) ?usize {
+ var depth: usize = 0;
+ var i = start;
+ while (i < text.len) : (i += 1) {
+ if (text[i] == '\\') {
+ i += 1;
+ } else if (text[i] == left) {
+ depth += 1;
+ } else if (text[i] == right) {
+ depth -= 1;
+ if (depth == 0) return i;
+ }
+ }
+ return null;
+}
+
fn space(c: u16) bool {
return switch (c) {
' ', 9...13, 0x85, 0xa0, 0x1680, 0x2000...0x200a, 0x2028, 0x2029, 0x202f, 0x205f, 0x3000 => true,
@@ -199,10 +298,51 @@ test "fences open, hold what looks like Markdown, and close only on their own ki
.{ L("~~~ a`b\n"), .fence },
.{ L("unclosed"), .code },
};
- for (lines) |l| try std.testing.expectEqual(l[1], fenceLine(l[0], &open));
+ for (lines) |l| try std.testing.expectEqual(l[1], fenceLine(l[0], &open, false));
try std.testing.expectEqual(@as(u32, 3 << 1 | 1), open);
}
+test "frontmatter is a block between its delimiters, and a rule is not one of them" {
+ const L = std.unicode.utf8ToUtf16LeStringLiteral;
+ var open: u32 = 0;
+ const lines = [_]struct { []const u16, Line }{
+ .{ L("--- \n"), .fence },
+ .{ L("title: **raw**\n"), .code },
+ .{ L("```\n"), .code },
+ .{ L("----\n"), .code },
+ .{ L("...\r\n"), .fence },
+ .{ L("---\n"), .text },
+ };
+ for (lines, 0..) |l, i| try std.testing.expectEqual(l[1], fenceLine(l[0], &open, i == 0));
+ try std.testing.expectEqual(@as(u32, 0), open);
+ try std.testing.expect(frontDelimiter(u8, "---\n", true) and !frontDelimiter(u8, "...\n", true) and !frontDelimiter(u8, " ---", false));
+ for ([_][]const u16{ L("---\n"), L(" ----- \r\n") }) |line| try std.testing.expectEqual(Rule.hyphens, rule(line));
+ for ([_][]const u16{ L("***"), L("___\n"), L(" * * *\n"), L("- - -"), L("-\t--\n"), L("_____ \n") }) |line| try std.testing.expectEqual(Rule.yes, rule(line));
+ for ([_][]const u16{ L(""), L("\n"), L("--"), L("--- a\n"), L(" ---\n"), L("\t---"), L("**_"), L("-*-\n"), L("* * item"), L("===") }) |line| try std.testing.expectEqual(Rule.no, rule(line));
+}
+
+test "links: the text is marked, the target is not read, and an image is left alone" {
+ const alloc = std.testing.allocator;
+ var p: Parser = .{};
+ defer p.marks.deinit(alloc);
+ const L = std.unicode.utf8ToUtf16LeStringLiteral;
+ const marks = try p.parse(alloc, L("[a] ![i](x) [*b* [c]](d_(e)_f \\) g) _h_"));
+ try std.testing.expectEqual(@as(usize, 6), marks.len);
+ try std.testing.expectEqual(Mark{ .at = 12, .width = 1, .kind = .link, .partner = 3 }, marks[0]);
+ try std.testing.expectEqual(Kind.star, marks[1].kind);
+ try std.testing.expectEqual(Mark{ .at = 20, .width = 15, .kind = .link, .partner = 0 }, marks[3]);
+ try std.testing.expectEqual(Mark{ .at = 36, .width = 1, .kind = .under, .partner = 5 }, marks[4]);
+ // No target, no text, no end: all as written. A "]" inside code does not strand the next link.
+ for ([_][]const u16{ L("[a] (b)"), L("[](b)"), L("[a](b"), L("\\[a](b)") }) |plain| try std.testing.expectEqual(@as(usize, 0), (try p.parse(alloc, plain)).len);
+ try std.testing.expectEqualSlices(u16, L("a/b%20c.png"), image(L(" ![](a/b%20c.png)\r\n")).?);
+ try std.testing.expectEqualSlices(u16, L("a_(b).png"), image(L("![an [alt]]( a_(b).png \"A title\" )\n")).?);
+ for ([_][]const u16{ L("![a]()"), L("![a](b) and text"), L("see ![a](b)"), L("[a](b)"), L("![a] (b)"), L("!") }) |not| try std.testing.expectEqual(@as(?[]const u16, null), image(not));
+ const after_code = try p.parse(alloc, L("[a `](x)` b](c) [d](e)"));
+ try std.testing.expectEqual(@as(usize, 5), after_code.len);
+ try std.testing.expectEqual(@as(?usize, null), after_code[0].partner);
+ try std.testing.expectEqual(@as(?usize, 4), after_code[3].partner);
+}
+
test "exact source offsets, literal escapes, and opaque code" {
const alloc = std.testing.allocator;
var p: Parser = .{};
diff --git a/src/objc.zig b/src/objc.zig
index 2cc7588..d9cad5f 100644
--- a/src/objc.zig
+++ b/src/objc.zig
@@ -36,6 +36,7 @@ fn Fn(comptime R: type, comptime Recv: type, comptime Args: type) type {
2 => fn (Recv, SEL, a[0].type, a[1].type) callconv(.c) R,
3 => fn (Recv, SEL, a[0].type, a[1].type, a[2].type) callconv(.c) R,
4 => fn (Recv, SEL, a[0].type, a[1].type, a[2].type, a[3].type) callconv(.c) R,
+ 6 => fn (Recv, SEL, a[0].type, a[1].type, a[2].type, a[3].type, a[4].type, a[5].type) callconv(.c) R,
9 => fn (Recv, SEL, a[0].type, a[1].type, a[2].type, a[3].type, a[4].type, a[5].type, a[6].type, a[7].type, a[8].type) callconv(.c) R,
10 => fn (Recv, SEL, a[0].type, a[1].type, a[2].type, a[3].type, a[4].type, a[5].type, a[6].type, a[7].type, a[8].type, a[9].type) callconv(.c) R,
else => @compileError("msg: add an arm for more arguments"),