-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarkdown.zig
More file actions
executable file
·1509 lines (1312 loc) · 53.1 KB
/
markdown.zig
File metadata and controls
executable file
·1509 lines (1312 loc) · 53.1 KB
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
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// --- markdown.zig (Final Corrected Version) ---
const std = @import("std");
const mem = std.mem;
const lexer = @import("lexer.zig");
const ascii = std.ascii;
// Global color configuration (initialized at app startup)
pub var COLOR_INLINE_CODE_BG: []const u8 = "\x1b[48;5;237m"; // Grey background - default
// --- Table Alignment ---
pub const Alignment = enum {
left,
center,
right,
};
// --- AST Node Definition ---
pub const AstNode = struct {
tag: Tag,
children: ?std.ArrayListUnmanaged(*AstNode),
text: ?[]const u8,
start_number: usize = 1,
lang: ?[]const u8,
alignments: ?[]Alignment = null,
pub const Tag = enum {
document,
paragraph,
heading,
bold,
italic,
text,
blockquote,
inline_code,
unordered_list,
list_item,
ordered_list,
code_block,
strikethrough,
horizontal_rule,
link,
table,
table_row,
table_cell,
};
pub fn init(allocator: mem.Allocator, tag: Tag) !*AstNode {
const node = try allocator.create(AstNode);
node.* = .{
.tag = tag,
.children = std.ArrayListUnmanaged(*AstNode){},
.text = null,
.lang = null,
};
return node;
}
pub fn initText(allocator: mem.Allocator, text: []const u8) !*AstNode {
const node = try allocator.create(AstNode);
node.* = .{
.tag = .text,
.children = null,
.text = try allocator.dupe(u8, text), // DUPLICATE THE TEXT
.lang = null,
};
return node;
}
pub fn deinit(self: *AstNode, allocator: mem.Allocator) void {
if (self.children) |*children| {
for (children.items) |child| {
child.deinit(allocator);
}
children.deinit(allocator);
}
// --- THIS IS THE CORRECTED LOGIC ---
// We first check if the tag is .text, and *then* we check if the
// optional self.text has a value to be freed.
if (self.tag == .text) {
if (self.text) |text| {
allocator.free(text);
}
}
// Free alignments array if present
if (self.alignments) |alignments| {
allocator.free(alignments);
}
allocator.destroy(self);
}
};
pub const Delimiter = struct {
token_index: usize,
delim_char: u8,
num_delims: usize,
can_open: bool,
can_close: bool,
};
pub const RenderableItem = struct {
tag: Tag,
payload: Payload,
pub const Tag = enum {
styled_text,
blockquote,
code_block,
horizontal_rule,
list,
link,
blank_line,
table,
};
pub const Payload = union {
styled_text: []const u8,
blockquote: std.ArrayListUnmanaged(RenderableItem),
code_block: struct {
content: []const u8,
lang: ?[]const u8,
},
horizontal_rule: void,
list: struct {
is_ordered: bool,
start_number: usize,
items: std.ArrayListUnmanaged(std.ArrayListUnmanaged(RenderableItem)),
},
link: struct {
text: []const u8,
url: []const u8,
},
blank_line: void,
table: struct {
headers: [][]const u8,
alignments: []Alignment,
rows: [][]const u8,
column_count: usize,
},
};
pub fn deinit(self: *RenderableItem, allocator: mem.Allocator) void {
switch (self.tag) {
.styled_text => allocator.free(self.payload.styled_text),
.code_block => {
allocator.free(self.payload.code_block.content);
if (self.payload.code_block.lang) |lang| {
allocator.free(lang);
}
},
.blockquote => {
for (self.payload.blockquote.items) |*item| {
item.deinit(allocator);
}
self.payload.blockquote.deinit(allocator);
},
.list => {
for (self.payload.list.items.items) |*item_blocks| {
for (item_blocks.items) |*block| {
block.deinit(allocator);
}
item_blocks.deinit(allocator);
}
self.payload.list.items.deinit(allocator);
},
.link => {
allocator.free(self.payload.link.text);
allocator.free(self.payload.link.url);
},
.table => {
for (self.payload.table.headers) |header| {
allocator.free(header);
}
allocator.free(self.payload.table.headers);
allocator.free(self.payload.table.alignments);
for (self.payload.table.rows) |row_cell| {
allocator.free(row_cell);
}
allocator.free(self.payload.table.rows);
},
.horizontal_rule => {},
.blank_line => {},
}
}
};
const Classification = struct {
can_open: bool,
can_close: bool,
};
fn isPunctuation(char: u8) bool {
return std.mem.indexOfScalar(u8, "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~", char) != null;
}
fn classifyDelimiter(
tokens: []const lexer.Token,
start_index: usize,
length: usize,
) Classification {
const end_index = start_index + length - 1;
const delim_char = tokens[start_index].text[0];
const char_before: ?u8 = if (start_index > 0 and tokens[start_index - 1].text.len > 0)
tokens[start_index - 1].text[tokens[start_index - 1].text.len - 1]
else
null;
const char_after: ?u8 = if (end_index < tokens.len - 1 and tokens[end_index + 1].text.len > 0)
tokens[end_index + 1].text[0]
else
null;
const followed_by_whitespace = (char_after == null) or std.ascii.isWhitespace(char_after.?);
var can_open = !followed_by_whitespace and
(char_before == null or std.ascii.isWhitespace(char_before.?) or isPunctuation(char_before.?));
const preceded_by_whitespace = (char_before == null) or std.ascii.isWhitespace(char_before.?);
var can_close = !preceded_by_whitespace and
(char_after == null or std.ascii.isWhitespace(char_after.?) or isPunctuation(char_after.?));
if (delim_char == '_') {
const preceded_by_non_whitespace = (char_before != null) and !std.ascii.isWhitespace(char_before.?);
const followed_by_non_whitespace = (char_after != null) and !std.ascii.isWhitespace(char_after.?);
if (preceded_by_non_whitespace and followed_by_non_whitespace) {
if (char_before != null and !isPunctuation(char_before.?)) {
if (char_after != null and !isPunctuation(char_after.?)) {
can_open = false;
can_close = false;
}
}
}
}
return Classification{
.can_open = can_open,
.can_close = can_close,
};
}
const Parser = struct {
allocator: mem.Allocator,
tokens: []lexer.Token,
pos: usize = 0,
fn init(allocator: mem.Allocator, tokens: []lexer.Token) Parser {
return .{ .allocator = allocator, .tokens = tokens };
}
fn eof(self: *const Parser) bool {
return self.pos >= self.tokens.len;
}
fn peek(self: *const Parser) ?lexer.Token {
if (self.eof()) return null;
return self.tokens[self.pos];
}
fn advance(self: *Parser) void {
if (!self.eof()) self.pos += 1;
}
fn consume(self: *Parser, tag: lexer.Token.Tag) bool {
if (self.peek()) |tok| {
if (tok.tag == tag) {
self.advance();
return true;
}
}
return false;
}
fn consumeNewline(self: *Parser) void {
while (self.peek()) |tok| {
if (tok.tag == .newline) self.advance() else break;
}
}
fn isBlockStarter(self: *const Parser, token: lexer.Token) bool {
_ = self;
return switch (token.tag) {
.atx_heading, .blockquote, .code_fence, .unordered_list_marker, .ordered_list_marker => true,
else => false,
};
}
fn parseLink(self: *Parser, parent_list: *std.ArrayListUnmanaged(?*AstNode)) !void {
var scan_pos = self.pos + 1;
var found_close_bracket = false;
while (scan_pos < self.tokens.len) {
const tok = self.tokens[scan_pos];
if (tok.tag == .newline) break;
if (tok.tag == .left_bracket) break;
if (tok.tag == .right_bracket) {
found_close_bracket = true;
scan_pos += 1;
break;
}
scan_pos += 1;
}
if (!found_close_bracket or scan_pos >= self.tokens.len) {
try parent_list.append(self.allocator, try AstNode.initText(self.allocator, self.peek().?.text));
self.advance();
return;
}
const next_tok = self.tokens[scan_pos];
const is_link = (next_tok.tag == .text and next_tok.text.len > 1 and next_tok.text[0] == '(' and next_tok.text[next_tok.text.len - 1] == ')');
if (!is_link) {
try parent_list.append(self.allocator, try AstNode.initText(self.allocator, self.peek().?.text));
self.advance();
return;
}
self.advance();
const link_node = try AstNode.init(self.allocator, .link);
while (self.peek().?.tag != .right_bracket) {
try link_node.children.?.append(self.allocator, try AstNode.initText(self.allocator, self.peek().?.text));
self.advance();
}
self.advance();
const url_tok = self.peek().?;
const url = url_tok.text[1 .. url_tok.text.len - 1];
link_node.text = try self.allocator.dupe(u8, url);
self.advance();
try parent_list.append(self.allocator, link_node);
}
fn parseInline(self: *Parser, parent_list: *std.ArrayListUnmanaged(*AstNode)) !void {
var delimiters = std.ArrayListUnmanaged(Delimiter){};
defer delimiters.deinit(self.allocator);
var nodes = std.ArrayListUnmanaged(?*AstNode){};
defer {
for (nodes.items) |node| {
if (node) |non_null_node| {
non_null_node.deinit(self.allocator);
}
}
nodes.deinit(self.allocator);
}
while (self.peek()) |token| {
if (token.tag == .newline) break;
switch (token.tag) {
.text => {
try nodes.append(self.allocator, try AstNode.initText(self.allocator, token.text));
self.advance();
},
.backtick => {
// Count opening backticks (CommonMark: delimiter length must match)
var open_count: usize = 0;
while (self.pos < self.tokens.len and self.tokens[self.pos].tag == .backtick) {
open_count += 1;
self.advance();
}
var content_buffer = std.ArrayListUnmanaged(u8){};
defer content_buffer.deinit(self.allocator);
// Collect content until finding matching closing delimiter
while (self.peek()) |tok| {
if (tok.tag == .newline) break; // Don't cross line boundaries
if (tok.tag == .backtick) {
// Count consecutive closing backticks
var close_count: usize = 0;
while (self.pos < self.tokens.len and self.tokens[self.pos].tag == .backtick) {
close_count += 1;
self.advance();
}
if (close_count == open_count) {
// Found matching closer!
break;
} else {
// Not a match, add these backticks to content
for (0..close_count) |_| {
try content_buffer.append(self.allocator, '`');
}
}
} else {
// Normal content
try content_buffer.appendSlice(self.allocator, tok.text);
self.advance();
}
}
const code_node = try AstNode.init(self.allocator, .inline_code);
code_node.text = try content_buffer.toOwnedSlice(self.allocator);
try nodes.append(self.allocator, code_node);
},
.left_bracket => {
try self.parseLink(&nodes);
},
.asterisk, .underscore, .tilde => {
const start_pos = self.pos;
var current_pos = self.pos;
while (current_pos < self.tokens.len and self.tokens[current_pos].tag == token.tag) {
current_pos += 1;
}
const num_delims = current_pos - start_pos;
const classification = classifyDelimiter(self.tokens, start_pos, num_delims);
try delimiters.append(self.allocator, .{
.token_index = nodes.items.len,
.delim_char = token.text[0],
.num_delims = num_delims,
.can_open = classification.can_open,
.can_close = classification.can_close,
});
self.pos = current_pos;
},
else => {
try nodes.append(self.allocator, try AstNode.initText(self.allocator, token.text));
self.advance();
},
}
}
try processDelimiters(self.allocator, &nodes, &delimiters);
for (nodes.items) |node| {
if (node) |non_null_node| {
try parent_list.append(self.allocator, non_null_node);
}
}
for (nodes.items) |*node_ptr| {
node_ptr.* = null;
}
}
fn findMatchingOpener(delimiters: *const std.ArrayListUnmanaged(Delimiter), closer_idx: usize) ?usize {
const closer = delimiters.items[closer_idx];
var i: i64 = @as(i64, @intCast(closer_idx)) - 1;
while (i >= 0) : (i -= 1) {
const opener = delimiters.items[@intCast(i)];
if (opener.can_open and opener.delim_char == closer.delim_char) {
if (!((opener.can_close or closer.can_open) and (opener.num_delims + closer.num_delims) % 3 == 0 and (opener.num_delims % 3 != 0 or closer.num_delims % 3 != 0))) {
return @intCast(i);
}
}
}
return null;
}
fn processDelimiters(
allocator: mem.Allocator,
nodes: *std.ArrayListUnmanaged(?*AstNode),
delimiters: *std.ArrayListUnmanaged(Delimiter),
) !void {
var i: i64 = if (delimiters.items.len == 0) -1 else @as(i64, @intCast(delimiters.items.len - 1));
while (i >= 0) : (i -= 1) {
const closer_idx = @as(usize, @intCast(i));
var closer = &delimiters.items[closer_idx];
if (!closer.can_close) continue;
if (findMatchingOpener(delimiters, closer_idx)) |opener_idx| {
var opener = &delimiters.items[opener_idx];
const num_delims = if (opener.num_delims < closer.num_delims) opener.num_delims else closer.num_delims;
const tag: AstNode.Tag = if (opener.delim_char == '~')
.strikethrough
else if (num_delims >= 2)
.bold
else
.italic;
const styled_node = try AstNode.init(allocator, tag);
const start_node_idx = opener.token_index;
const end_node_idx = closer.token_index;
if (start_node_idx < end_node_idx) {
for (nodes.items[start_node_idx..end_node_idx]) |node| {
if (node) |non_null_node| {
try styled_node.children.?.append(allocator, non_null_node);
}
}
}
nodes.items[start_node_idx] = styled_node;
var j = start_node_idx + 1;
while (j < end_node_idx) : (j += 1) {
nodes.items[j] = null;
}
opener.num_delims -= num_delims;
closer.num_delims -= num_delims;
}
}
var final_nodes = std.ArrayListUnmanaged(*AstNode){};
defer final_nodes.deinit(allocator);
var node_cursor: usize = 0;
var delim_cursor: usize = 0;
while (node_cursor < nodes.items.len or delim_cursor < delimiters.items.len) {
const next_delim_idx = if (delim_cursor < delimiters.items.len)
delimiters.items[delim_cursor].token_index
else
std.math.maxInt(usize);
if (node_cursor < next_delim_idx) {
if (nodes.items[node_cursor]) |node| {
try final_nodes.append(allocator, node);
}
node_cursor += 1;
} else if (delim_cursor < delimiters.items.len) {
const delim = delimiters.items[delim_cursor];
if (delim.num_delims > 0) {
var text_buf = std.ArrayListUnmanaged(u8){};
defer text_buf.deinit(allocator);
for (0..delim.num_delims) |_| try text_buf.append(allocator, delim.delim_char);
try final_nodes.append(allocator, try AstNode.initText(allocator, try text_buf.toOwnedSlice(allocator)));
}
delim_cursor += 1;
} else {
break;
}
}
nodes.clearRetainingCapacity();
for (final_nodes.items) |node| {
try nodes.append(allocator, node);
}
}
fn isHorizontalRule(self: *const Parser) bool {
var scan_pos = self.pos;
if (scan_pos >= self.tokens.len) return false;
const first_tok = self.tokens[scan_pos];
const rule_char_opt: ?u8 = switch (first_tok.tag) {
.asterisk => '*',
.underscore => '_',
.text => blk: {
const trimmed = mem.trim(u8, first_tok.text, " ");
if (trimmed.len == 0) break :blk null;
const c = trimmed[0];
if (c != '*' and c != '_' and c != '-') {
break :blk null;
}
break :blk c;
},
else => null,
};
const rule_char = rule_char_opt orelse return false;
var count: usize = 0;
while (scan_pos < self.tokens.len) {
const tok = self.tokens[scan_pos];
if (tok.tag == .newline) break;
for (tok.text) |c| {
if (c == rule_char) {
count += 1;
} else if (c != ' ') {
return false;
}
}
scan_pos += 1;
}
return count >= 3;
}
fn parseAlignment(text: []const u8) Alignment {
const trimmed = mem.trim(u8, text, " \t");
if (trimmed.len == 0) return .left;
const starts_with_colon = trimmed[0] == ':';
const ends_with_colon = trimmed[trimmed.len - 1] == ':';
if (starts_with_colon and ends_with_colon) return .center;
if (ends_with_colon) return .right;
return .left;
}
fn isDelimiterCell(text: []const u8) bool {
const trimmed = mem.trim(u8, text, " \t");
if (trimmed.len < 3) return false;
var start: usize = 0;
var end: usize = trimmed.len;
// Skip leading colon
if (trimmed[0] == ':') start = 1;
// Skip trailing colon
if (trimmed[trimmed.len - 1] == ':') end = trimmed.len - 1;
var dash_count: usize = 0;
for (trimmed[start..end]) |c| {
if (c == '-') {
dash_count += 1;
} else if (c != ' ' and c != '\t') {
return false;
}
}
return dash_count >= 3;
}
fn isTableStart(self: *const Parser) bool {
var scan_pos = self.pos;
// Skip any leading indent
if (scan_pos < self.tokens.len and self.tokens[scan_pos].tag == .indent) {
scan_pos += 1;
}
// Check first line has pipes
var has_pipe = false;
while (scan_pos < self.tokens.len) {
const tok = self.tokens[scan_pos];
if (tok.tag == .newline) break;
if (tok.tag == .pipe) has_pipe = true;
scan_pos += 1;
}
if (!has_pipe) return false;
// Skip newline
if (scan_pos >= self.tokens.len or self.tokens[scan_pos].tag != .newline) return false;
scan_pos += 1;
// Skip indent on second line
if (scan_pos < self.tokens.len and self.tokens[scan_pos].tag == .indent) {
scan_pos += 1;
}
// Check second line is delimiter row (pipes with valid delimiters)
var has_valid_delimiter = false;
var second_line_has_pipe = false;
while (scan_pos < self.tokens.len) {
const tok = self.tokens[scan_pos];
if (tok.tag == .newline) break;
if (tok.tag == .pipe) second_line_has_pipe = true;
if (tok.tag == .text and isDelimiterCell(tok.text)) {
has_valid_delimiter = true;
}
scan_pos += 1;
}
return second_line_has_pipe and has_valid_delimiter;
}
fn parseBlock(self: *Parser, min_indent: usize) anyerror!?*AstNode {
if (self.eof()) return null;
const backup_pos = self.pos;
var indent_width: usize = 0;
if (self.peek()) |tok| {
if (tok.tag == .indent) {
indent_width = tok.indent_width;
self.advance();
}
}
if (indent_width < min_indent) {
self.pos = backup_pos;
return null;
}
if (self.isHorizontalRule()) {
while (!self.eof() and self.peek().?.tag != .newline) {
self.advance();
}
return try AstNode.init(self.allocator, .horizontal_rule);
}
// Check for table start
self.pos = backup_pos;
if (self.peek()) |tok| {
if (tok.tag == .indent) {
self.advance();
}
}
if (self.isTableStart()) {
return self.parseTable();
}
self.pos = backup_pos;
if (self.peek()) |tok| {
if (tok.tag == .indent) {
self.advance();
}
}
if (self.eof()) return null;
return switch (self.peek().?.tag) {
.atx_heading => self.parseHeading(),
.blockquote => self.parseBlockquote(indent_width),
.code_fence => self.parseCodeBlock(),
.unordered_list_marker, .ordered_list_marker => self.parseList(indent_width),
else => self.parseParagraph(),
};
}
fn parseHeading(self: *Parser) anyerror!*AstNode {
const heading = try AstNode.init(self.allocator, .heading);
self.advance();
if (!self.eof() and self.peek().?.tag == .text and self.peek().?.text.len > 0 and self.peek().?.text[0] == ' ') {
self.tokens[self.pos].text = self.tokens[self.pos].text[1..];
}
try self.parseInline(&heading.children.?);
return heading;
}
fn parseParagraph(self: *Parser) anyerror!*AstNode {
const para = try AstNode.init(self.allocator, .paragraph);
var buffer = std.ArrayListUnmanaged(u8){};
defer buffer.deinit(self.allocator);
while (self.peek()) |tok| {
if (self.isBlockStarter(tok)) break;
if (tok.tag == .newline) {
if (self.pos + 1 < self.tokens.len and self.tokens[self.pos + 1].tag == .newline) {
self.advance();
break;
}
try buffer.append(self.allocator, ' ');
self.advance();
continue;
}
try buffer.appendSlice(self.allocator, tok.text);
self.advance();
}
if (buffer.items.len > 0) {
var temp_arena = std.heap.ArenaAllocator.init(self.allocator);
defer temp_arena.deinit();
const temp_allocator = temp_arena.allocator();
var paragraph_tokens = try lexer.tokenize(temp_allocator, buffer.items);
defer paragraph_tokens.deinit(temp_allocator);
if (paragraph_tokens.items.len > 0) {
var inline_parser = Parser.init(self.allocator, paragraph_tokens.items);
try inline_parser.parseInline(¶.children.?);
}
}
return para;
}
fn parseCodeBlock(self: *Parser) anyerror!*AstNode {
const open_fence = self.peek().?.text;
self.advance();
const node = try AstNode.init(self.allocator, .code_block);
if (!self.eof() and self.peek().?.tag == .text) {
node.lang = self.peek().?.text;
self.advance();
}
_ = self.consume(.newline);
var content = std.ArrayListUnmanaged(u8){};
defer content.deinit(self.allocator);
while (!self.eof()) {
const tok = self.peek().?;
if (tok.tag == .code_fence and mem.eql(u8, tok.text, open_fence)) {
self.advance();
break;
}
try content.appendSlice(self.allocator, tok.text);
self.advance();
}
node.text = try content.toOwnedSlice(self.allocator);
return node;
}
fn parseBlockquote(self: *Parser, _: usize) anyerror!*AstNode {
const quote = try AstNode.init(self.allocator, .blockquote);
var buffer = std.ArrayListUnmanaged(u8){};
defer buffer.deinit(self.allocator);
while (!self.eof()) {
const backup_pos = self.pos;
if (self.peek().?.tag == .blockquote) {
self.advance();
if (!self.eof() and self.peek().?.tag == .text and self.peek().?.text.len > 0 and self.peek().?.text[0] == ' ') {
self.tokens[self.pos].text = self.tokens[self.pos].text[1..];
}
} else {
if (buffer.items.len > 0) {
self.pos = backup_pos;
break;
}
}
while (!self.eof()) {
const tok = self.peek().?;
if (tok.tag == .newline) {
try buffer.append(self.allocator, '\n');
self.advance();
break;
}
try buffer.appendSlice(self.allocator, tok.text);
self.advance();
}
if (self.peek()) |next_tok| {
if (self.isBlockStarter(next_tok)) break;
} else {
break;
}
}
var sub_tokens = try lexer.tokenize(self.allocator, buffer.items);
defer sub_tokens.deinit(self.allocator);
if (sub_tokens.items.len > 0) {
var sub_parser = Parser.init(self.allocator, sub_tokens.items);
const sub_ast = try sub_parser.parse();
defer sub_ast.deinit(self.allocator);
try quote.children.?.appendSlice(self.allocator, sub_ast.children.?.items);
sub_ast.children = null;
}
return quote;
}
fn parseList(self: *Parser, indent_width: usize) anyerror!*AstNode {
const first_marker_tok = self.peek().?;
const list_type = first_marker_tok.tag;
const list = try AstNode.init(self.allocator, if (list_type == .unordered_list_marker) .unordered_list else .ordered_list);
if (list_type == .ordered_list_marker) {
var j: usize = 0;
while (j < first_marker_tok.text.len and ascii.isDigit(first_marker_tok.text[j])) {
j += 1;
}
if (j > 0) {
list.start_number = std.fmt.parseInt(usize, first_marker_tok.text[0..j], 10) catch 1;
}
}
while (true) {
const item_backup_pos = self.pos;
var current_indent: usize = 0;
if (self.peek()) |tok| {
if (tok.tag == .indent) {
current_indent = tok.indent_width;
self.advance();
}
}
if (current_indent < indent_width) {
self.pos = item_backup_pos;
break;
}
if (self.peek() == null or self.peek().?.tag != list_type) {
if (list.children.?.items.len > 0) {
const last_item = list.children.?.items[list.children.?.items.len - 1];
self.pos = item_backup_pos;
try self.parseListItemContinuation(last_item, indent_width);
if (self.pos == item_backup_pos) {
break;
} else {
continue;
}
}
self.pos = item_backup_pos;
break;
}
try list.children.?.append(self.allocator, try self.parseListItem(indent_width));
if (self.eof()) break;
}
return list;
}
fn parseListItem(self: *Parser, list_indent: usize) anyerror!*AstNode {
const item = try AstNode.init(self.allocator, .list_item);
const para = try AstNode.init(self.allocator, .paragraph);
try item.children.?.append(self.allocator, para);
self.advance();
if (self.peek()) |tok| {
if (tok.tag == .text and tok.text.len > 0 and tok.text[0] == ' ') {
self.tokens[self.pos].text = tok.text[1..];
}
}
try self.parseInline(¶.children.?);
try self.parseListItemContinuation(item, list_indent);
return item;
}
fn parseListItemContinuation(self: *Parser, item: *AstNode, list_indent: usize) !void {
const required_indent = list_indent + 1;
while (true) {
const continuation_backup_pos = self.pos;
self.consumeNewline();
if (self.eof()) break;
var next_indent: usize = 0;
if (self.peek().?.tag == .indent) {
next_indent = self.peek().?.indent_width;
} else {
self.pos = continuation_backup_pos;
break;
}
if (next_indent < required_indent) {
self.pos = continuation_backup_pos;
break;
}
self.advance();
if (try self.parseBlock(next_indent)) |block| {
try item.children.?.append(self.allocator, block);
} else {
const para = try AstNode.init(self.allocator, .paragraph);
try self.parseInline(¶.children.?);
try item.children.?.append(self.allocator, para);
}
}
}
fn parseTable(self: *Parser) anyerror!*AstNode {
const table = try AstNode.init(self.allocator, .table);
// Skip indent if present
if (!self.eof() and self.peek().?.tag == .indent) {
self.advance();
}
// Parse header row
var header_cells = std.ArrayListUnmanaged([]const u8){};
defer header_cells.deinit(self.allocator);
var cell_buffer = std.ArrayListUnmanaged(u8){};
defer cell_buffer.deinit(self.allocator);
// Skip leading pipe if present
if (!self.eof() and self.peek().?.tag == .pipe) {
self.advance();
}
while (!self.eof()) {
const tok = self.peek().?;
if (tok.tag == .newline) break;
if (tok.tag == .pipe) {
// End of cell
const cell_text = try cell_buffer.toOwnedSlice(self.allocator);
try header_cells.append(self.allocator, cell_text);
cell_buffer = std.ArrayListUnmanaged(u8){};
self.advance();
} else {
// Add to current cell
try cell_buffer.appendSlice(self.allocator, tok.text);
self.advance();
}
}
// Add last cell if buffer not empty
if (cell_buffer.items.len > 0) {
try header_cells.append(self.allocator, try cell_buffer.toOwnedSlice(self.allocator));
}
const column_count = header_cells.items.len;
if (column_count == 0) {
table.deinit(self.allocator);
return error.InvalidTable;
}
// Skip newline
if (!self.eof() and self.peek().?.tag == .newline) {
self.advance();
}
// Skip indent on delimiter row
if (!self.eof() and self.peek().?.tag == .indent) {
self.advance();
}
// Parse delimiter row to extract alignments
var alignments = try self.allocator.alloc(Alignment, column_count);
var align_idx: usize = 0;