Repository navigation
Expand file tree
/
Copy pathrender.zig
More file actions
1856 lines (1636 loc) · 67.8 KB
/
Copy pathrender.zig
File metadata and controls
1856 lines (1636 loc) · 67.8 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
//! Renders markdown into a terminal.
//!
//! The renderer never allocates: its only error is `WriteFailed`. It also never
//! measures a styled string — it measures plain spans and computes prefix
//! widths arithmetically from the parts they are built from, so "how wide is
//! `\x1b[1mfoo\x1b[0m`" is not a question it has to answer.
//!
//! Blocks are recognised from a line's prefix rather than by building a
//! container stack. Every construct supported here is a line-prefix decision,
//! and the wrapping rule is per line, so a stack would buy only lazy
//! continuation lines joining a paragraph back onto a list item — which is
//! deliberately not done, because only indented elements are reflowed. Mixed
//! two- and four-space indentation from a model therefore renders unevenly, but
//! never incorrectly.
//!
//! Only lines that carry a prefix are reflowed. At column zero a plain
//! paragraph is emitted whole and left to the terminal's own soft-wrap; under a
//! margin (`Options.indent`) every line carries a prefix, so prose is wrapped
//! here — a terminal continues a soft-wrapped line at column zero, which would
//! leave the tail of a paragraph hanging outside the margin.
const std = @import("std");
const sgr = @import("style.zig");
const term = @import("term.zig");
const text = @import("../util/text.zig");
const vt = @import("../util/terminal/ansi.zig");
/// Beyond this, an unmatched marker is treated as literal text. Without a cap,
/// scanning for a closer is quadratic: `text.repeat("*", 100_000)` would compare ~10^10
/// bytes on a 100 KB reply.
const max_span_scan: usize = 2048;
/// Nesting caps. A prefix wider than the terminal would leave no room for
/// content and make the splitter spin, so depth is bounded everywhere.
const max_quote_depth: u8 = 4;
const max_list_depth: usize = 8;
const max_inline_depth: u8 = 4;
/// Columns of base indent applied to a fenced block, so the bar does not sit
/// flush against the left margin.
const code_indent: usize = 2;
/// Columns of base indent applied to a table, matching a fenced block's.
const table_indent: usize = 2;
/// Blank columns between two table cells.
const table_gap: usize = 2;
/// Rows buffered before a table is given up on. A "table" longer than this is
/// far more likely to be prose that happens to contain pipes.
const max_table_rows: usize = 128;
/// Columns past this are not laid out; such a line is treated as prose instead,
/// which loses nothing.
const max_table_columns: usize = 10;
/// A cell is laid out through this buffer. Only a cell longer than this is
/// truncated, and a cell that long would not fit a terminal column anyway.
const cell_buffer_size: usize = 1024;
// Preserve the renderer API while keeping SGR encoding in one module.
pub const Style = sgr.Style;
pub const Theme = struct {
h1: Style = .{ .bold = true, .color = .magenta },
h2: Style = .{ .bold = true, .color = .cyan },
h3: Style = .{ .bold = true },
h4: Style = .{ .bold = true, .dim = true },
code_lang: Style = .{ .dim = true },
code_bar: Style = .{ .dim = true },
quote_bar: Style = .{ .dim = true },
marker: Style = .{ .dim = true },
link_text: Style = .{ .underline = true, .color = .cyan },
link_url: Style = .{ .dim = true },
rule: Style = .{ .dim = true },
table_header: Style = .{ .bold = true },
bullet_glyph: []const u8 = "\xe2\x80\xa2", // •
rule_glyph: []const u8 = "\xe2\x94\x80", // ─
quote_bar_glyph: []const u8 = "\xe2\x94\x82 ", // │
code_bar_glyph: []const u8 = "\xe2\x96\x8f ", // ▏
pub const default: Theme = .{};
pub fn heading(self: Theme, level: u8) Style {
return switch (level) {
1 => self.h1,
2 => self.h2,
3 => self.h3,
else => self.h4,
};
}
};
pub const Options = struct {
/// Usable columns. The renderer never queries the terminal itself, which is
/// what lets the tests drive wrapping directly.
width: usize = 80,
/// False suppresses all SGR output but keeps the structure, so tests can
/// assert layout without escape codes in every expectation.
styled: bool = true,
/// Wrap long code lines. Turning this off keeps a long path or URL on one
/// line for copy-paste, at the cost of the bar vanishing past the margin.
wrap_code: bool = true,
/// Columns of left margin before every line, on top of whatever prefix a
/// block carries itself. The conversation renders at its margin; a caller
/// laying a document out from column zero leaves this at zero.
///
/// A margin is why a wrapped paragraph is reflowed here rather than left to
/// the terminal: a terminal's soft-wrap continues at column zero, which
/// would break the margin on every long line.
indent: usize = 0,
};
/// What is written before the content of a line, and before each continuation
/// line of a wrapped one.
const Prefix = struct {
quote_depth: u8 = 0,
code_bar: bool = false,
indent: usize = 0,
/// Written followed by one space, e.g. "•" or "12.".
marker: []const u8 = "",
marker_style: Style = .{},
fn width(self: Prefix, theme: Theme) usize {
var total: usize = @as(usize, self.quote_depth) * term.width(theme.quote_bar_glyph);
if (self.code_bar) total += term.width(theme.code_bar_glyph);
total += self.indent;
if (self.marker.len > 0) total += term.width(self.marker) + 1;
return total;
}
};
/// Accumulates one output line, wrapping as it goes.
const Wrap = struct {
w: *std.Io.Writer,
theme: Theme,
styled: bool,
width: usize,
first: Prefix = .{},
cont: Prefix = .{},
allow_wrap: bool = false,
/// Display columns used on the current line, prefix included.
col: usize = 0,
/// Whether the prefix of the current line has been written.
started: bool = false,
/// Which output line of this input line we are on; selects first vs cont.
line_index: usize = 0,
/// Spaces held back until a word follows them, so a wrapped line never ends
/// in trailing whitespace and a continuation never starts indented.
pending_spaces: usize = 0,
open_style: Style = .{},
fn setup(self: *Wrap, first: Prefix, cont: Prefix) void {
self.first = first;
self.cont = cont;
// The one rule that implements "reflow only what is indented": a
// paragraph has an empty prefix and is therefore left to the terminal.
self.allow_wrap = first.width(self.theme) > 0;
self.line_index = 0;
self.started = false;
self.col = 0;
self.pending_spaces = 0;
}
fn setStyle(self: *Wrap, s: Style) !void {
if (!self.styled) return;
if (std.meta.eql(s, self.open_style)) return;
// Resetting is only necessary when the new style drops something the
// current one set.
if (!s.covers(self.open_style)) try self.w.writeAll(sgr.RESET);
if (!s.isPlain()) {
var buf: [24]u8 = undefined;
try self.w.writeAll(s.open(&buf));
}
self.open_style = s;
}
fn writePrefix(self: *Wrap, p: Prefix) !void {
var i: u8 = 0;
while (i < p.quote_depth) : (i += 1) {
try self.setStyle(self.theme.quote_bar);
try self.w.writeAll(self.theme.quote_bar_glyph);
}
// Indent before the bar: a fenced block nested in a list should have
// its bar to the right of the list's indentation, not the other way
// round. Width is a sum, so the order here does not affect it.
var n: usize = 0;
while (n < p.indent) : (n += 1) try self.w.writeByte(' ');
if (p.code_bar) {
try self.setStyle(self.theme.code_bar);
try self.w.writeAll(self.theme.code_bar_glyph);
}
try self.setStyle(.{});
if (p.marker.len > 0) {
try self.setStyle(p.marker_style);
try self.w.writeAll(p.marker);
try self.w.writeByte(' ');
}
self.col = p.width(self.theme);
}
fn ensureLine(self: *Wrap) !void {
if (self.started) return;
try self.writePrefix(if (self.line_index == 0) self.first else self.cont);
self.started = true;
}
fn breakLine(self: *Wrap) !void {
try self.setStyle(.{});
try self.w.writeByte('\n');
self.line_index += 1;
self.started = false;
self.col = 0;
self.pending_spaces = 0;
}
fn flushSpaces(self: *Wrap) !void {
const n = self.pending_spaces;
self.pending_spaces = 0;
if (n == 0 or !self.started) return;
var i: usize = 0;
while (i < n) : (i += 1) try self.w.writeByte(' ');
self.col += n;
}
/// Hold back `n` spaces until the next word is written.
fn space(self: *Wrap, n: usize) void {
if (!self.started) return;
self.pending_spaces += n;
}
fn tabStop(self: *Wrap) !void {
if (!self.started) return;
const next = ((self.col / term.tab_width) + 1) * term.tab_width;
try self.flushSpaces();
var n = next - self.col;
if (n == 0) n = term.tab_width;
var i: usize = 0;
while (i < n) : (i += 1) try self.w.writeByte(' ');
self.col += n;
}
fn repeat(self: *Wrap, s: Style, glyph: []const u8, count: usize) !void {
try self.ensureLine();
try self.flushSpaces();
try self.setStyle(s);
var i: usize = 0;
while (i < count) : (i += 1) {
try self.w.writeAll(glyph);
self.col += term.width(glyph);
}
}
/// Emit `run`, breaking it at spaces so wrapping happens between words.
fn flow(self: *Wrap, s: Style, run: []const u8) !void {
var i: usize = 0;
while (i < run.len) {
var spaces: usize = 0;
while (i < run.len and run[i] == ' ') : (i += 1) spaces += 1;
if (spaces > 0) self.space(spaces);
if (i >= run.len) break;
const start = i;
while (i < run.len and run[i] != ' ') : (i += 1) {}
try self.word(s, run[start..i]);
}
}
/// Emit one unbreakable run, hard-splitting it if it cannot fit on a line
/// by itself. Tabs are expanded here so that every caller gets tab stops
/// without having to know about them.
fn word(self: *Wrap, s: Style, bytes: []const u8) !void {
var rest = bytes;
while (std.mem.indexOfScalar(u8, rest, '\t')) |idx| {
try self.plainWord(s, rest[0..idx]);
try self.tabStop();
rest = rest[idx + 1 ..];
}
try self.plainWord(s, rest);
}
fn plainWord(self: *Wrap, s: Style, bytes: []const u8) !void {
if (bytes.len == 0) return;
const wpx = term.width(bytes);
const gap: usize = if (self.started and self.pending_spaces > 0) 1 else 0;
if (self.allow_wrap and self.started and self.col + gap + wpx > self.width) {
try self.breakLine();
}
try self.ensureLine();
if (!self.allow_wrap or wpx <= self.width -| self.col) {
// Spaces are flushed before the style switch so that the leading
// space of a span stays unstyled. Dim, bold and italic are
// invisible on a space either way, but underline is not: a styled
// leading space draws a stray rule in front of a link label.
try self.flushSpaces();
try self.setStyle(s);
try self.w.writeAll(bytes);
self.col += wpx;
return;
}
// Wider than what is left of this line: emit it in chunks, each on its
// own line behind a fresh prefix. Overflowing instead would drop the
// bar for the rest of the visual row, which is the whole point of the
// hanging indent.
var rest = bytes;
while (rest.len > 0) {
// Each chunk after the first starts a fresh line, so it needs the
// continuation prefix written before anything else.
try self.ensureLine();
const taken = term.takeFit(rest, self.width -| self.col);
const chunk = rest[0..taken];
const chunk_width = term.width(chunk);
try self.flushSpaces();
try self.setStyle(s);
try self.w.writeAll(chunk);
self.col += chunk_width;
rest = rest[taken..];
if (rest.len > 0) try self.breakLine();
}
}
fn finish(self: *Wrap) !void {
self.pending_spaces = 0;
try self.setStyle(.{});
try self.w.writeByte('\n');
self.line_index += 1;
self.started = false;
self.col = 0;
}
/// Start a line whose layout the caller computes itself. Tables decide
/// where every column begins, so they write through this rather than
/// through `word`, which would wrap at spaces the caller already placed.
fn beginRaw(self: *Wrap, p: Prefix) !void {
try self.setStyle(.{});
try self.writePrefix(p);
self.started = true;
}
fn endRaw(self: *Wrap) !void {
try self.setStyle(.{});
try self.w.writeByte('\n');
self.started = false;
self.col = 0;
self.line_index = 0;
self.pending_spaces = 0;
}
fn writeSpaces(self: *Wrap, count: usize) !void {
var i: usize = 0;
while (i < count) : (i += 1) try self.w.writeByte(' ');
self.col += count;
}
};
/// A candidate emphasis or code span found by the inline scanner.
const Span = struct {
content_start: usize,
content_end: usize,
/// Index just past the closing marker.
end: usize,
style: Style = .{},
};
const Inline = struct {
wrap: *Wrap,
theme: Theme,
depth: u8 = 0,
cur: Style = .{},
/// The error set is spelled out because `run` and `nested` are mutually
/// recursive, and inferred sets would form a dependency loop.
fn run(self: *Inline, source: []const u8) std.Io.Writer.Error!void {
var i: usize = 0;
var start: usize = 0;
while (i < source.len) {
const byte = source[i];
if (byte == 0x1b) {
try self.wrap.flow(self.cur, source[start..i]);
i = vt.skipAnsiEscape(source, i);
start = i;
continue;
}
if (vt.isControl(byte) and byte != '\t') {
try self.wrap.flow(self.cur, source[start..i]);
var buf: [4]u8 = undefined;
try self.wrap.word(self.cur, vt.escapeByte(&buf, byte));
i += 1;
start = i;
continue;
}
if (byte >= 0x80) {
const cp = term.decodeAt(source, i);
if (cp.valid) {
// Advance by the whole sequence: no marker byte is ever
// >= 0x80, so this only keeps offsets honest.
i += cp.len;
} else {
try self.wrap.flow(self.cur, source[start..i]);
var buf: [4]u8 = undefined;
try self.wrap.word(self.cur, vt.escapeByte(&buf, byte));
i += 1;
start = i;
}
continue;
}
if (byte == '\\' and i + 1 < source.len and std.ascii.isPunctuation(source[i + 1])) {
try self.wrap.flow(self.cur, source[start..i]);
try self.wrap.word(self.cur, source[i + 1 .. i + 2]);
i += 2;
start = i;
continue;
}
// Code spans come before emphasis: that ordering is what keeps a
// `*` inside backticks from being read as a marker.
if (byte == '`') {
if (matchCodeSpan(source, i)) |span| {
try self.wrap.flow(self.cur, source[start..i]);
try self.wrap.flow(self.theme.code_lang, source[span.content_start..span.content_end]);
i = span.end;
start = i;
continue;
}
}
if (byte == '*' or byte == '_' or byte == '~') {
if (matchEmphasis(source, i, self.cur)) |span| {
try self.wrap.flow(self.cur, source[start..i]);
try self.nested(source[span.content_start..span.content_end], span.style);
i = span.end;
start = i;
continue;
}
}
if (byte == '[' or (byte == '!' and i + 1 < source.len and source[i + 1] == '[')) {
const bracket = if (byte == '!') i + 1 else i;
if (matchLink(source, bracket)) |link| {
try self.wrap.flow(self.cur, source[start..i]);
try self.emitLink(source, link);
i = link.end;
start = i;
continue;
}
}
i += 1;
}
try self.wrap.flow(self.cur, source[start..]);
}
fn nested(self: *Inline, content: []const u8, style: Style) std.Io.Writer.Error!void {
// At the depth cap the content still renders, just without the extra
// style, rather than recursing without bound.
const level = @min(self.depth + 1, max_inline_depth);
var inner = Inline{
.wrap = self.wrap,
.theme = self.theme,
.depth = level,
.cur = if (level == self.depth) self.cur else style,
};
try inner.run(content);
}
fn emitLink(self: *Inline, source: []const u8, link: Link) !void {
const label = source[link.text_start..link.text_end];
const url = source[link.url_start..link.url_end];
try self.wrap.flow(self.theme.link_text, label);
// A bare link prints once; anything else gets its target alongside.
if (std.mem.eql(u8, label, url)) return;
// Close the label's style before the separating space. Spaces are
// emitted with whatever style is open when they are flushed, and an
// underlined space draws a visible rule in front of the URL — the one
// attribute that is not invisible on a space.
try self.wrap.setStyle(.{});
try self.wrap.flow(self.theme.link_url, " (");
try self.wrap.flow(self.theme.link_url, url);
try self.wrap.flow(self.theme.link_url, ")");
}
};
const Link = struct {
text_start: usize,
text_end: usize,
url_start: usize,
url_end: usize,
end: usize,
};
fn countRun(source: []const u8, start: usize, ch: u8) usize {
var i = start;
while (i < source.len and source[i] == ch) : (i += 1) {}
return i - start;
}
fn isSpace(cp: ?u21) bool {
const value = cp orelse return true;
if (value >= 128) return false;
return switch (@as(u8, @intCast(value))) {
' ', '\t', '\n', '\r', 0x0b, 0x0c => true,
else => false,
};
}
fn isWordChar(cp: ?u21) bool {
const value = cp orelse return false;
// Anything non-ASCII counts as a word character, so an underscore next to
// CJK text does not open emphasis.
if (value >= 128) return true;
return std.ascii.isAlphanumeric(@intCast(value));
}
/// Codepoint ending at `index`, or the raw preceding byte when the sequence is
/// malformed.
fn cpBefore(source: []const u8, index: usize) ?u21 {
if (index == 0) return null;
var start = index - 1;
var back: usize = 0;
while (back < 3 and start > 0 and (source[start] & 0xc0) == 0x80) : (back += 1) start -= 1;
const cp = term.decodeAt(source, start);
if (start + cp.len != index) return source[index - 1];
return cp.value;
}
fn cpAfter(source: []const u8, index: usize) ?u21 {
if (index >= source.len) return null;
return term.decodeAt(source, index).value;
}
/// A run of backticks closed by a run of exactly the same length. Backticks
/// that never close are literal text, which is what keeps `a `b` c` sane.
fn matchCodeSpan(source: []const u8, start: usize) ?Span {
const open_len = countRun(source, start, '`');
const content_start = start + open_len;
const limit = @min(source.len, content_start + max_span_scan);
var j = content_start;
while (j < limit) {
if (source[j] != '`') {
j += 1;
continue;
}
const run = countRun(source, j, '`');
if (run == open_len and j > content_start) {
return .{ .content_start = content_start, .content_end = j, .end = j + run };
}
j += run;
}
return null;
}
/// Find the emphasis span opening at `start`, if any.
///
/// The closer is the *last* `n` characters of the first later run long enough
/// to close, which is what makes `**bold *and italic***` nest correctly instead
/// of collapsing to literal asterisks.
fn matchEmphasis(source: []const u8, start: usize, outer: Style) ?Span {
const ch = source[start];
const run_len = countRun(source, start, ch);
var n: usize = undefined;
var inner = Style{};
switch (ch) {
'~' => {
if (run_len < 2) return null;
n = 2;
inner = .{ .strike = true };
},
else => {
n = @min(run_len, 2);
inner = if (n == 2) .{ .bold = true } else .{ .italic = true };
},
}
const open_end = start + n;
if (open_end >= source.len) return null;
if (!emphasisOpens(source, start, ch, n)) return null;
const limit = @min(source.len, open_end + max_span_scan);
var j = open_end;
while (j < limit) {
if (source[j] != ch) {
j += 1;
continue;
}
const close_run = countRun(source, j, ch);
if (close_run >= n and emphasisCloses(source, j, ch, n)) {
const content_end = j + close_run - n;
if (content_end > open_end) {
return .{
.content_start = open_end,
.content_end = content_end,
.end = j + close_run,
.style = Style.overlay(outer, inner),
};
}
}
j += close_run;
}
return null;
}
fn emphasisOpens(source: []const u8, start: usize, ch: u8, n: usize) bool {
if (isSpace(cpAfter(source, start + n))) return false;
if (ch != '_') return true;
// An underscore only opens a span when it is not preceded by a word
// character, which is what leaves identifiers like snake_case_name alone.
return !isWordChar(cpBefore(source, start));
}
fn emphasisCloses(source: []const u8, start: usize, ch: u8, n: usize) bool {
if (isSpace(cpBefore(source, start))) return false;
if (ch != '_') return true;
// ...and only closes one when it is not followed by a word character, so
// the closing underscore of _foo_bar_ is the last one, not the middle one.
var end = start + n;
while (end < source.len and source[end] == ch) end += 1;
return !isWordChar(cpAfter(source, end));
}
/// Index of the bracket that closes the one at `start`, honouring nesting.
fn findClose(source: []const u8, start: usize, open: u8, close: u8) ?usize {
const limit = @min(source.len, start + max_span_scan);
var depth: usize = 0;
var i = start;
while (i < limit) : (i += 1) {
const byte = source[i];
if (byte == '\\') {
i += 1;
continue;
}
if (byte == open) {
depth += 1;
} else if (byte == close) {
if (depth == 0) return null;
depth -= 1;
if (depth == 0) return i;
}
}
return null;
}
fn matchLink(source: []const u8, start: usize) ?Link {
if (start >= source.len or source[start] != '[') return null;
const close = findClose(source, start, '[', ']') orelse return null;
if (close + 1 >= source.len or source[close + 1] != '(') return null;
const paren = findClose(source, close + 1, '(', ')') orelse return null;
const text_start = start + 1;
const url_start = close + 2;
if (close <= text_start or paren < url_start) return null;
return .{
.text_start = text_start,
.text_end = close,
.url_start = url_start,
.url_end = paren,
.end = paren + 1,
};
}
const Fence = struct {
marker: u8,
len: usize,
lang: []const u8,
quote_depth: u8,
};
fn matchFenceOpen(line: []const u8) ?struct { marker: u8, len: usize, lang: []const u8 } {
if (line.len < 3) return null;
const marker = line[0];
if (marker != '`' and marker != '~') return null;
const len = countRun(line, 0, marker);
if (len < 3) return null;
return .{ .marker = marker, .len = len, .lang = std.mem.trim(u8, line[len..], " \t") };
}
fn isFenceClose(line: []const u8, fence: Fence) bool {
if (line.len == 0 or line[0] != fence.marker) return false;
const len = countRun(line, 0, fence.marker);
if (len < fence.len) return false;
return std.mem.trim(u8, line[len..], " \t").len == 0;
}
/// `---`, `***`, `___`, and the spaced variants like `- - -`.
fn isThematicBreak(line: []const u8) bool {
var marker: u8 = 0;
var count: usize = 0;
for (line) |byte| {
if (byte == ' ') continue;
if (byte != '-' and byte != '*' and byte != '_') return false;
if (marker == 0) {
marker = byte;
} else if (byte != marker) return false;
count += 1;
}
return count >= 3;
}
const ListItem = struct {
level: usize,
/// Digits plus the delimiter, e.g. "12."; empty for a bullet.
number: []const u8,
content: []const u8,
};
fn matchListItem(line: []const u8) ?ListItem {
var i: usize = 0;
while (i < line.len and line[i] == ' ') : (i += 1) {}
if (i >= line.len) return null;
const level = @min(i / 2, max_list_depth);
const byte = line[i];
if (byte == '-' or byte == '*' or byte == '+') {
const rest = line[i + 1 ..];
if (rest.len > 0 and rest[0] != ' ') return null;
const content = std.mem.trimStart(u8, rest, " ");
// A bare marker is not an item. Rendering it as an empty bullet would
// silently drop the character the model actually wrote.
if (content.len == 0) return null;
return .{ .level = level, .number = "", .content = content };
}
if (std.ascii.isDigit(byte)) {
var j = i;
while (j < line.len and std.ascii.isDigit(line[j])) : (j += 1) {}
if (j >= line.len) return null;
if (line[j] != '.' and line[j] != ')') return null;
const rest = line[j + 1 ..];
if (rest.len > 0 and rest[0] != ' ') return null;
const content = std.mem.trimStart(u8, rest, " ");
if (content.len == 0) return null;
return .{ .level = level, .number = line[i .. j + 1], .content = content };
}
return null;
}
/// Strip one leading `>` marker, allowing the indentation markdown permits.
fn stripQuoteMarker(line: []const u8) ?[]const u8 {
var i: usize = 0;
while (i < line.len and line[i] == ' ') : (i += 1) {}
if (i >= line.len or line[i] != '>') return null;
const rest = line[i + 1 ..];
if (rest.len > 0 and rest[0] == ' ') return rest[1..];
return rest;
}
/// Render `doc` to `w`. Every input line produces exactly one output line,
/// plus one more for each wrap and one for a code fence's language label.
pub fn render(w: *std.Io.Writer, doc: []const u8, options: Options) std.Io.Writer.Error!void {
var r = Renderer.init(w, options);
try r.feed(doc);
}
pub const Renderer = struct {
wrap: Wrap,
theme: Theme,
options: Options,
fence: ?Fence = null,
table: Table = .{},
pub fn init(w: *std.Io.Writer, options: Options) Renderer {
const theme: Theme = .default;
return .{
.wrap = .{
.w = w,
.theme = theme,
.styled = options.styled,
.width = options.width,
},
.theme = theme,
.options = options,
};
}
/// A block's own prefix, moved out to the document's margin. Every prefix
/// the renderer writes goes through here, which is what keeps a list, a
/// fence and a table at the same left edge.
fn margin(self: *const Renderer, p: Prefix) Prefix {
var shifted = p;
shifted.indent += self.options.indent;
return shifted;
}
/// Feed a whole document. A streaming caller would call `feedLine` itself
/// with complete lines; the renderer keeps no state that requires more.
pub fn feed(self: *Renderer, doc: []const u8) !void {
if (doc.len == 0) return;
var body = doc;
if (std.mem.endsWith(u8, body, "\n")) body = body[0 .. body.len - 1];
var lines = std.mem.splitScalar(u8, body, '\n');
while (lines.next()) |line| try self.feedLine(line);
// A table is only recognisable once the line after it is known to be a
// delimiter row, so the last one is still held here.
if (self.table.count > 0) try self.flushTable();
}
/// Push everything fed so far out of the underlying writer, without
/// flushing the table buffer (which must wait for a non-table line or the
/// end of the document). A streaming caller calls this after each line so
/// the terminal shows it before the next one arrives.
pub fn flushWriter(self: *Renderer) !void {
try self.wrap.w.flush();
}
/// Flush the table held back while it was being recognised, and then the
/// underlying writer. A streaming caller calls this once after its last
/// line; a caller using `feed` never has to.
pub fn finish(self: *Renderer) !void {
if (self.table.count > 0) try self.flushTable();
try self.wrap.w.flush();
}
/// Lines containing pipes may be borrowed for table detection. Keep their
/// storage valid until the buffered table is flushed, or until `finish`.
pub fn feedLine(self: *Renderer, raw: []const u8) !void {
// A stray carriage return would send the cursor back to column zero.
const line = std.mem.trimEnd(u8, raw, " \t\r");
if (self.fence) |fence| {
if (isFenceClose(line, fence)) {
// The closing fence is structure, not content.
self.fence = null;
return;
}
return self.codeLine(line, fence);
}
var rest = line;
var quote_depth: u8 = 0;
while (quote_depth < max_quote_depth) {
rest = stripQuoteMarker(rest) orelse break;
quote_depth += 1;
}
// A line that cannot continue the buffered table ends it, and is then
// processed normally below. Rows are only ever buffered from lines that
// would otherwise be a paragraph, so a buffer that turns out not to be
// a table renders as exactly that.
if (self.table.count > 0) {
const continues = !self.table.full and
quote_depth == self.table.quote_depth and
hasRowSeparator(rest);
if (continues) return self.bufferRow(rest, quote_depth);
try self.flushTable();
}
if (rest.len == 0) {
// Blank lines stay blank; a lone quote marker draws nothing.
return self.wrap.finish();
}
if (matchFenceOpen(rest)) |open| {
self.fence = .{
.marker = open.marker,
.len = open.len,
.lang = open.lang,
.quote_depth = quote_depth,
};
return self.codeLabel(self.fence.?);
}
if (isThematicBreak(rest)) return self.rule(quote_depth);
if (headingLevel(rest)) |heading| {
return self.headingLine(heading.level, heading.content, quote_depth);
}
if (matchListItem(rest)) |item| {
return self.listLine(item, quote_depth);
}
// Only lines that reach this point — those that would be a paragraph —
// are candidates, which is what makes a wrong guess free to undo.
if (hasRowSeparator(rest)) return self.bufferRow(rest, quote_depth);
return self.paragraph(rest, quote_depth);
}
fn bufferRow(self: *Renderer, row: []const u8, quote_depth: u8) !void {
if (self.table.count == max_table_rows) {
self.table.full = true;
try self.flushTable();
}
if (self.table.count == 0) self.table.quote_depth = quote_depth;
self.table.rows[self.table.count] = row;
self.table.count += 1;
}
fn flushTable(self: *Renderer) !void {
const table = self.table;
self.table = .{};
// Fewer than two rows cannot hold a delimiter row, and a buffer that
// overflowed is prose that happened to contain pipes.
if (table.full or table.count < 2) return self.tableProse(table);
var cells: [max_table_columns][]const u8 = undefined;
var aligns: [max_table_columns]Alignment = @splat(.left);
const declared = splitRow(table.rows[1], &cells) orelse return self.tableProse(table);
for (cells[0..declared], 0..) |cell, i| {
// Every cell of the delimiter row has to be a delimiter, or this
// is not a table at all.
aligns[i] = parseAlignment(cell) orelse return self.tableProse(table);
}
return self.emitTable(table, aligns, declared);
}
/// The buffered rows were never a table after all.
fn tableProse(self: *Renderer, table: Table) !void {
for (table.rows[0..table.count]) |row| {
try self.paragraph(row, table.quote_depth);
}
}
fn emitTable(
self: *Renderer,
table: Table,
aligns: [max_table_columns]Alignment,
declared: usize,
) !void {
var cells: [max_table_columns][]const u8 = undefined;
var cols = declared;
var widths: [max_table_columns]usize = @splat(0);
// Every cell is measured before anything is written: the widest one in
// a column decides that column's width. Row 1 is the delimiter row —
// it is drawn as a rule rather than as content, so its dashes must not
// widen the column they stand under.
for (table.rows[0..table.count], 0..) |row, r| {
if (r == 1) continue;
const count = splitRow(row, &cells) orelse return self.tableProse(table);
cols = @max(cols, count);
for (cells[0..count], 0..) |cell, c| {
widths[c] = @max(widths[c], measureCell(self.theme, cell));
}
}
if (cols == 0) return self.tableProse(table);
const indent = self.margin(.{ .quote_depth = table.quote_depth, .indent = table_indent });
fitColumns(widths[0..cols], self.wrap.width -| indent.width(self.theme));
try self.tableRowLine(table.rows[0], cols, widths[0..cols], aligns[0..cols], table.quote_depth, self.theme.table_header);
try self.tableRule(cols, widths[0..cols], table.quote_depth);
for (table.rows[2..table.count]) |row| {
try self.tableRowLine(row, cols, widths[0..cols], aligns[0..cols], table.quote_depth, .{});
}
}
fn tableRowLine(
self: *Renderer,
row: []const u8,
cols: usize,
widths: []const usize,
aligns: []const Alignment,
quote_depth: u8,
base: Style,
) !void {
var cells: [max_table_columns][]const u8 = undefined;
const count = splitRow(row, &cells) orelse return;
var bufs: [max_table_columns][cell_buffer_size]u8 = undefined;
var used: [max_table_columns]usize = @splat(0);
var lines: usize = 1;
for (0..cols) |c| {
const cell = if (c < count) cells[c] else "";
const rendered = renderCell(self.theme, cell, widths[c], base, self.options.styled, &bufs[c]);
used[c] = rendered.len;
lines = @max(lines, renderedLines(rendered));
}
const indent = self.margin(.{ .quote_depth = quote_depth, .indent = table_indent });
for (0..lines) |line_index| {
// A row whose later cells are empty on this line stops there: the
// padding that would align them is whitespace at the end of a line.
var last: usize = 0;
for (0..cols) |c| {
if (term.width(nthRenderedLine(bufs[c][0..used[c]], line_index)) > 0) last = c;
}
try self.wrap.beginRaw(indent);
for (0..last + 1) |c| {
const line = nthRenderedLine(bufs[c][0..used[c]], line_index);
const slack = widths[c] -| term.width(line);