From 2f1d226f6baaafec34b5b3623ba6c9df9aaa003b Mon Sep 17 00:00:00 2001 From: t Date: Tue, 24 Nov 2026 22:50:09 -0700 Subject: Render Markdown in the editor and add a terminal launcher Show links, images, quotes, rules and YAML frontmatter as formatted text, revealing the source while the caret is on their line. Images load only from local files and are never fetched. Store frontmatter ahead of the hidden comment block so the file's first line stays a YAML opener. Files saved the old way still open. Add bin/write_away to launch or focus the app from a shell. --- src/doc.zig | 84 ++++++++++++++-- src/main.zig | 302 +++++++++++++++++++++++++++++++++++++++++++++++++------ src/markdown.zig | 148 ++++++++++++++++++++++++++- src/objc.zig | 1 + 4 files changed, 496 insertions(+), 39 deletions(-) (limited to '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 = ""; // legacy const overflow_open = "\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"), -- cgit v1.3