diff options
Diffstat (limited to 'src/markdown.zig')
| -rw-r--r-- | src/markdown.zig | 148 |
1 files changed, 144 insertions, 4 deletions
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 "", or of +/// "". 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]  [*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(" \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(" and text"), L("see "), 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 = .{}; |
