diff options
Diffstat (limited to 'src/markdown.zig')
| -rw-r--r-- | src/markdown.zig | 217 |
1 files changed, 217 insertions, 0 deletions
diff --git a/src/markdown.zig b/src/markdown.zig new file mode 100644 index 0000000..3009c20 --- /dev/null +++ b/src/markdown.zig @@ -0,0 +1,217 @@ +//! 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_count = @typeInfo(Kind).@"enum".fields.len; +pub const Style = struct { + strong: bool = false, + emphasis: bool = false, + strike: bool = false, + code: bool = false, +}; + +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 }; + 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 != '*' and c != '_' and c != '~' and c != '`') { + i += 1; + continue; + } + const at = i; + i = runEnd(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(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) }; + 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), + }; + } +}; + +pub const Line = enum { text, code, fence }; + +/// 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 { + 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(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(u16, rest, '`') == null)) { + open.* = width << 1 | tilde; + return .fence; + } + } else if (open.* & 1 == tilde and width >= open.* >> 1 and std.mem.indexOfNone(u16, rest, &.{ ' ', '\t', '\r', '\n' }) == null) { + open.* = 0; + return .fence; + } + } + return if (open.* == 0) .text else .code; +} + +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(text: []const u16, start: usize, c: u16) usize { + var i = start + 1; + while (i < text.len and text[i] == c) i += 1; + return i; +} + +fn nextTicks(text: []const u16, start: usize, width: usize) usize { + var i = start; + while (i < text.len) { + if (text[i] != '`') { + i += 1; + continue; + } + const stop = runEnd(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(l[0], &open)); + try std.testing.expectEqual(@as(u32, 3 << 1 | 1), open); +} + +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]); +} |
