summaryrefslogtreecommitdiff
path: root/src/main.zig
diff options
context:
space:
mode:
Diffstat (limited to 'src/main.zig')
-rw-r--r--src/main.zig302
1 files changed, 274 insertions, 28 deletions
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", .{});
}