summaryrefslogtreecommitdiff
path: root/src/markdown.zig
blob: 3009c2015ccdc58078b17c90dd95db2dcb324f61 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
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]);
}