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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
|
//! 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 "<!--" is,
pub const comment_close = 3; // and "-->"
/// 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..], "<!--")) continue;
// "<!-->" 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{ "<!-- write_away ", "<!-- overflow\n(", "<!-- overflow -->" }) |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 "", 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,
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<!--\n# b\n\n```\n-->\nc <!-- d --> e<!--f--><!-->\n", &.{ "<!--\n# b\n\n```\n-->", "<!-- d -->", "<!--f-->", "<!-->" } },
.{ "<!-- a <!-- b --> c -->", &.{"<!-- a <!-- b -->"} },
// Only its own line can close one in a paragraph, a list or a quote.
.{ "a <!-- b\n\nc -->\n- <!-- d\ne -->\n> <!-- f -->\n <!-- g\n-->", &.{"<!-- f -->"} },
.{ "```\n<!-- a -->\n```\n`<!-- b -->` ``c ` <!-- d -->`` ` <!-- e -->", &.{"<!-- e -->"} },
.{ "\\<!-- a --> \\\\<!-- b -->\n<!-- c\n", &.{"<!-- b -->"} },
.{ "---\nx: 1\n<!-- a -->\n---\n<!-- b -->", &.{"<!-- b -->"} },
.{ "<!-- overflow\n(a)-->\n<!-- write_away {} -->\n\n<!-- overflow -->\n<!-- overflowing -->", &.{"<!-- overflowing -->"} },
};
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]  [*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 = .{};
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]);
}
|