//! 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, 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, kind: Kind, partner: ?usize = null, }; pub const Parser = struct { // Reused across paragraphs and keystrokes. marks: std.ArrayList(Mark) = .empty, pub fn parse(p: *Parser, alloc: std.mem.Allocator, text: []const u16) ![]const Mark { p.marks.clearRetainingCapacity(); var opener: [kind_count]?usize = @splat(null); var stack: [kind_count]usize = undefined; // at most one pending opener per kind var depth: usize = 0; var ticks: [2]usize = .{ 0, 0 }; // 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]; if (c == '\\' and i + 1 < text.len and punctuation(text[i + 1])) { 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; } const at = i; i = runEnd(u16, text, at, c); const width = i - at; if (c == '`') { if (width > ticks.len) continue; // Each cursor moves only forward, even when a backtick run is unmatched. const close = nextTicks(u16, text, @max(i, ticks[width - 1]), width); ticks[width - 1] = close; if (close == text.len or close == i) continue; const first = p.marks.items.len; try p.marks.appendSlice(alloc, &.{ .{ .at = at, .width = width, .kind = .code, .partner = first + 1 }, .{ .at = close, .width = width, .kind = .code, .partner = first }, }); i = close + width; continue; } const kind: Kind = switch (c) { '*' => switch (width) { 1 => .star, 2 => .strong_star, 3 => .both_star, else => continue, }, '_' => switch (width) { 1 => .under, 2 => .strong_under, 3 => .both_under, else => continue, }, '~' => if (width == 2) .strike else continue, else => unreachable, }; const before = if (at == 0) ' ' else text[at - 1]; const after = if (i == text.len) ' ' else text[i]; const left = !space(after) and (!punctuation(after) or space(before) or punctuation(before)); const right = !space(before) and (!punctuation(before) or space(after) or punctuation(after)); const can_open = left and (c != '_' or !right or punctuation(before)); const can_close = right and (c != '_' or !left or punctuation(after)); const slot = &opener[@intFromEnum(kind)]; if (can_close) if (slot.*) |idx| { const open = stack[idx]; // Unmatched opens inside a matched pair stay literal. Spans never cross. for (stack[idx..depth]) |pending| opener[@intFromEnum(p.marks.items[pending].kind)] = null; depth = idx; p.marks.items[open].partner = p.marks.items.len; try p.marks.append(alloc, .{ .at = at, .width = width, .kind = kind, .partner = open }); continue; }; if (can_open and slot.* == null) { slot.* = depth; stack[depth] = p.marks.items.len; depth += 1; try p.marks.append(alloc, .{ .at = at, .width = width, .kind = kind }); } } return p.marks.items; } }; pub const Active = struct { bits: [kind_count]bool = @splat(false), pub fn toggle(a: *Active, mark: Mark) void { const bit = &a.bits[@intFromEnum(mark.kind)]; bit.* = !bit.*; } fn has(a: Active, kind: Kind) bool { return a.bits[@intFromEnum(kind)]; } pub fn style(a: Active) Style { if (a.has(.code)) return .{ .code = true, .strike = a.has(.strike), .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. /// 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(comptime T: type, line: []const T, open: *u32, opens_front: bool) Line { if (opens_front) { open.* = front; return .fence; } if (open.* == front) { if (!frontDelimiter(T, 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] == '~')) { const c = line[i]; const tilde = @intFromBool(c == '~'); const stop = runEnd(T, line, i, c); const width: u32 = @intCast(stop - i); const rest = line[stop..]; if (open.* == 0) { // A backtick fence's info string has no backticks: that would be inline code. if (width >= 3 and (c == '~' or std.mem.indexOfScalar(T, rest, '`') == null)) { open.* = width << 1 | tilde; return .fence; } } else if (open.* & 1 == tilde and width >= open.* >> 1 and std.mem.indexOfNone(T, rest, &.{ ' ', '\t', '\r', '\n' }) == null) { open.* = 0; return .fence; } } return if (open.* == 0) .text else .code; } pub const Span = struct { lo: usize, hi: usize }; pub const comment_open = 4; // how long "" /// The HTML comments of a whole piece, in order. What is not surely a comment is prose: to /// hide text that Markdown then publishes would be the worse mistake. So one that starts a /// line may run over any others, but elsewhere (and in a list or a quote) it has to close on /// its own line; and code, frontmatter and what is never closed have none. The file's own /// records, if they could not be read, stay in sight too. pub fn Comments(comptime T: type) type { return struct { text: []const T, front: bool, // it opens with frontmatter: see `fenceLine` at: usize = 0, open: u32 = 0, pub fn next(it: *@This()) ?Span { const text = it.text; lines: while (it.at < text.len) { const stop = if (std.mem.indexOfScalarPos(T, text, it.at, '\n')) |nl| nl + 1 else text.len; var i = it.at; if (starts(text, i) and fenceLine(T, text[i..stop], &it.open, it.front and i == 0) != .text) i = stop; while (i < stop) switch (text[i]) { '\\' => i += 2, '`' => { const body = runEnd(T, text[0..stop], i, '`'); const close = nextTicks(T, text[0..stop], body, body - i); i = if (close == stop) body else close + (body - i); }, '<' => { const lo = i; i += 1; if (!has(text[lo..], "" is a whole comment. const close = find(text[0..if (starts(text, lo)) text.len else stop], lo + 2, "-->") orelse continue; it.at = close + comment_close; for ([_][]const u8{ "" }) |record| if (has(text[lo..], record)) continue :lines; return .{ .lo = lo, .hi = it.at }; }, else => i += 1, }; it.at = stop; } return null; } fn starts(text: []const T, i: usize) bool { return i == 0 or text[i - 1] == '\n'; } fn has(text: []const T, what: []const u8) bool { if (text.len < what.len) return false; for (text[0..what.len], what) |a, b| if (a != b) return false; return true; } fn find(text: []const T, from: usize, what: []const u8) ?usize { var i = from; while (i + what.len <= text.len) : (i += 1) if (has(text[i..], what)) return i; return null; } }; } 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, else => false, }; } fn punctuation(c: u16) bool { return switch (c) { '!'...'/', ':'...'@', '['...'`', '{'...'~' => true, else => false, }; } fn runEnd(comptime T: type, text: []const T, start: usize, c: T) usize { var i = start + 1; while (i < text.len and text[i] == c) i += 1; return i; } fn nextTicks(comptime T: type, text: []const T, start: usize, width: usize) usize { var i = start; while (i < text.len) { if (text[i] != '`') { i += 1; continue; } const stop = runEnd(T, text, i, '`'); if (stop - i == width) return i; i = stop; } return text.len; } test "fences open, hold what looks like Markdown, and close only on their own kind" { const L = std.unicode.utf8ToUtf16LeStringLiteral; var open: u32 = 0; const lines = [_]struct { []const u16, Line }{ .{ L("``not a fence``\n"), .text }, .{ L("```a`b\n"), .text }, .{ L(" ```\n"), .text }, .{ L(" ````zig\n"), .fence }, .{ L("# **raw**\n"), .code }, .{ L("```\n"), .code }, // too short to close four .{ L("~~~~\n"), .code }, .{ L("```` x\n"), .code }, .{ L("````` \r\n"), .fence }, .{ L("after\n"), .text }, .{ L("~~~ a`b\n"), .fence }, .{ L("unclosed"), .code }, }; for (lines) |l| try std.testing.expectEqual(l[1], fenceLine(u16, 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(u16, 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 "comments: one that starts a line runs on, and nothing Markdown might publish is one" { const cases = [_]struct { []const u8, []const []const u8 }{ .{ "a\n\nc e\n", &.{ "", "", "", "" } }, .{ " c -->", &.{""} }, // Only its own line can close one in a paragraph, a list or a quote. .{ "a \n- \n> \n ", &.{""} }, .{ "```\n\n```\n`` ``c ` `` ` ", &.{""} }, .{ "\\ \\\\\n"} }, .{ "---\nx: 1\n\n---\n", &.{""} }, .{ "\n\n\n\n", &.{""} }, }; for (cases) |c| { const front_matter = std.mem.startsWith(u8, c[0], "---"); var it: Comments(u8) = .{ .text = c[0], .front = front_matter }; for (c[1]) |want| { const got = it.next().?; try std.testing.expectEqualStrings(want, c[0][got.lo..got.hi]); } try std.testing.expectEqual(@as(?Span, null), it.next()); // The page reads the same ones, in UTF-16. var units: [256]u16 = undefined; const n = try std.unicode.utf8ToUtf16Le(&units, c[0]); var wide: Comments(u16) = .{ .text = units[0..n], .front = front_matter }; it = .{ .text = c[0], .front = front_matter }; while (it.next()) |want| try std.testing.expectEqual(want, wide.next().?); try std.testing.expectEqual(@as(?Span, null), wide.next()); } } 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 = .{}; defer p.marks.deinit(alloc); const text = std.unicode.utf8ToUtf16LeStringLiteral("😀***both*** snake_case \\*literal* ``*raw*` ``"); const marks = try p.parse(alloc, text); try std.testing.expectEqual(@as(usize, 4), marks.len); try std.testing.expectEqual(Mark{ .at = 2, .width = 3, .kind = .both_star, .partner = 1 }, marks[0]); try std.testing.expectEqual(Mark{ .at = 9, .width = 3, .kind = .both_star, .partner = 0 }, marks[1]); try std.testing.expectEqual(Mark{ .at = text.len - 11, .width = 2, .kind = .code, .partner = 3 }, marks[2]); try std.testing.expectEqual(Mark{ .at = text.len - 2, .width = 2, .kind = .code, .partner = 2 }, marks[3]); }