-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathrender.mjs
More file actions
2237 lines (2071 loc) · 101 KB
/
Copy pathrender.mjs
File metadata and controls
2237 lines (2071 loc) · 101 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
// Phase 3 of tbdocs: render each page's markdown / HTML body to an HTML
// fragment stored on page.renderedContent. See builder/PLAN-3.md for the
// full spec.
//
// What this phase does NOT do (per PLAN-3 §3):
// - wrap in <html> / layout / sidebar / footer / scripts (Phase 4)
// - inject <a class="anchor-heading"> next to <hN id> (Phase 4 -- has
// to see auto-generated heading IDs)
// - compress whitespace (Phase 4)
// - generate the per-page nav-activation <style> block (Phase 4)
// - concatenate chapter bodies for the PDF book (Phase 8)
import MarkdownIt from "markdown-it";
import attrs from "markdown-it-attrs";
import deflist from "markdown-it-deflist";
import footnote from "markdown-it-footnote";
import { initHighlighter } from "./highlight.mjs";
// Circular with counts.mjs, which imports maskCodeRegions from here so that
// "what is code" has one definition across the pre-render rewrites and the
// count validator. Safe because both sides export function DECLARATIONS, which
// are hoisted and bound before either module body runs, and neither calls into
// the other at module-evaluation time. Verified in both import orders.
import { countPlugin, findSurvivingPlaceholder } from "./counts.mjs";
export async function renderPhase(pages, site, staticFiles = []) {
// Allow the orchestrator to pre-build the markdown-it instance (so
// Phase 2's seo.mjs can share the same renderer). Idempotent: if
// site.markdown is already set, use it; otherwise build it here.
let md = site.markdown;
if (!md) {
const highlighter = await initHighlighter();
const linkTables = buildLinkTables(pages);
const baseurl = String(site.config.baseurl || "");
const staticFileSet = new Set(staticFiles.map((s) => s.srcRel));
md = createMarkdownIt({ highlighter, linkTables, baseurl, staticFiles: staticFileSet });
site.markdown = md;
}
await Promise.all(pages.map(async (page) => {
page.renderedContent = renderPage(page, md);
// A count placeholder that reached the output is the failure the feature
// exists to prevent, arriving by a new route. Source validation cannot see
// this case -- a placeholder inside a raw HTML block has a perfectly good
// name, so it passes there, and markdown-it keeps an html_block as one
// opaque token the substitution rule never enters. One string scan per
// page, and it catches every cause rather than the ones anticipated.
const survivor = findSurvivingPlaceholder(page.renderedContent);
if (survivor) {
throw new Error(
`${page.srcRel}: ${survivor} survived rendering.\n` +
" The name is known, so this is a placement markdown-it cannot reach --\n" +
" a raw HTML block is the usual one. Put it in prose, or write the\n" +
" number by hand and say in the page why it is not derived.");
}
}));
}
function renderPage(page, md) {
if (page.ext === ".html") {
// 404.html passes through Phase 4's default-layout wrap; book.html is
// consumed by Phase 8. Either way, no markdown rendering happens here.
return page.rawContent;
}
const source = applyPreRenderRewrites(page.rawContent);
let html = md.render(source, { page });
html = normaliseVoidTags(html);
html = padEmptyCells(html);
return html;
}
// kramdown emits a single space inside otherwise-empty `<td>` / `<th>`
// cells (`<td> </td>`); markdown-it leaves them collapsed (`<td></td>`).
function padEmptyCells(html) {
// kramdown emits `<td>\xa0</td>` (nbsp) for empty cells; we mirror
// it so the rendered HTML byte-matches. Regular space here would
// visually look the same, but Phase 4's compress would later
// collapse it differently than kramdown's empty-cell content.
return html.replace(/<(t[dh])([^>]*)><\/\1>/g, "<$1$2> </$1>");
}
// kramdown accepts unescaped spaces inside `` and `[text](url)`
// URLs; CommonMark / markdown-it does NOT and leaves the source text
// unparsed. URL-encode spaces inside image and link URL components so
// markdown-it can parse them the way kramdown would.
//
// Only the simple case is handled: a URL that's a plain file path with
// spaces and NO embedded quotes or parens. Anything trickier (titles,
// nested parens) gets left alone -- the regex is too coarse to safely
// rewrite those.
// The whole pre-render rewrite chain, exactly as renderPage applies it.
// Exported so scripts/check_code_regions.mjs can gate the real thing rather
// than a reconstruction of it -- in particular so that removing the mask from
// one of these rewrites is caught, which a gate that only exercised
// maskCodeRegions would miss.
export function applyPreRenderRewrites(rawContent) {
// CommonMark normalises CRLF/CR to LF before block parsing. The rewrites
// below all rely on LF-only input -- do the normalisation up front so they
// see consistent line shapes.
const source = rawContent.replace(/\r\n?/g, "\n");
// These four are kramdown-parity fixes over raw source, so none of them
// knows what is code. On a site whose subject matter IS code that is a
// standing hazard, and it was demonstrated for each: `Items[1](a, b)` became
// `Items[1](a,%20b)`, `' *** banner ***` became `' **_ banner _**`, and a
// YAML sample ending in `---` had that line DELETED and the entry above it
// promoted to a heading. Mask the code regions, rewrite, then restore.
const code = maskCodeRegions(source);
let work = code.masked;
work = rewriteTripleAsteriskEmphasis(work);
work = encodeSpacesInMediaUrls(work);
work = rewriteListItemSetextHeadings(work);
work = absorbTrailingHtmlComments(work);
// rewriteAdmonitions runs OUTSIDE the mask, and must: a fence inside an
// admonition still carries its `> ` markers at this point, so the mask does
// not see it as a fence, and the admonition rewrite is what strips those
// markers. It does its own code handling.
return rewriteAdmonitions(code.restore(work));
}
// ---------- code-region mask for the pre-render rewrites --------------------
//
// Hides fenced code blocks (backtick or tilde, any fence length) and inline
// code spans (any backtick-run length) behind opaque placeholders, so a
// source-level rewrite cannot reach into a code sample.
//
// The placeholder is wrapped in backticks deliberately. A masked fence
// collapses several lines into one, and `absorbTrailingHtmlComments`
// classifies the PREVIOUS line to decide whether to join a comment to it --
// its PARAGRAPH_CONTINUATION_RE excludes a line starting with a backtick,
// which is what a real fence line started with. Keeping that leading
// backtick keeps the classification identical.
//
// Indented code blocks are NOT masked: telling one from a list-item
// continuation needs block context that a pre-render pass does not have, and
// guessing would change how real list content renders. That gap is a known,
// measured one -- scripts/check_code_regions.mjs covers it.
const CODE_MASK_RE = /`\u0000CM(\d+)\u0000`/g;
export function maskCodeRegions(src) {
const stash = [];
const lines = src.split("\n");
const out = [];
let i = 0;
while (i < lines.length) {
const open = lines[i].match(/^[ \t]{0,3}(`{3,}|~{3,})/);
if (open) {
const marker = open[1];
const fenceChar = marker[0];
const block = [lines[i]];
let j = i + 1;
for (; j < lines.length; j++) {
block.push(lines[j]);
const close = lines[j].match(/^[ \t]{0,3}(`+|~+)[ \t]*$/);
if (close && close[1][0] === fenceChar && close[1].length >= marker.length) {
j++;
break;
}
}
stash.push(block.join("\n"));
out.push(`\`\u0000CM${stash.length - 1}\u0000\``);
i = j;
continue;
}
out.push(maskInlineCode(lines[i], stash));
i++;
}
return {
masked: out.join("\n"),
restore: (s) => s.replace(CODE_MASK_RE, (_, n) => stash[Number(n)] ?? ""),
};
}
// A code span is a run of N backticks, the shortest possible content, then a
// run of exactly N backticks. An unmatched run is literal text in CommonMark
// and simply never matches here, which is the correct outcome.
function maskInlineCode(line, stash) {
let res = "";
let k = 0;
while (k < line.length) {
if (line[k] !== "`") { res += line[k++]; continue; }
let n = 0;
while (line[k + n] === "`") n++;
const open = k;
let p = k + n;
let found = -1;
while (p < line.length) {
if (line[p] === "`") {
let m = 0;
while (line[p + m] === "`") m++;
if (m === n) { found = p; break; }
p += m;
} else p++;
}
if (found < 0) { res += line.slice(open, open + n); k = open + n; continue; }
stash.push(line.slice(open, found + n));
res += `\`\u0000CM${stash.length - 1}\u0000\``;
k = found + n;
}
return res;
}
const MEDIA_URL_SPACES_RE = /(!?\[(?:[^\]\n]*)\])\(([^)"'\n]+)\)/g;
function encodeSpacesInMediaUrls(src) {
return src.replace(MEDIA_URL_SPACES_RE, (whole, prefix, url) => {
if (!/ /.test(url)) return whole;
return `${prefix}(${url.replace(/ /g, "%20")})`;
});
}
// kramdown emits `***text***` as `<strong><em>text</em></strong>`;
// markdown-it emits the same source as `<em><strong>text</strong></em>`.
// Pre-rewriting the source to `**_text_**` makes both renderers emit
// the strong-outside form. Leave existing `**_..._**` and `_**...**_`
// patterns alone so their em/strong order matches the source intent.
const TRIPLE_STAR_RE = /\*\*\*([^*\n][^*\n]*?)\*\*\*/g;
function rewriteTripleAsteriskEmphasis(src) {
return src.replace(TRIPLE_STAR_RE, "**_$1_**");
}
// kramdown attaches a standalone HTML-comment line to the preceding
// paragraph (the comment line ends up inside the paragraph's AST). In
// CommonMark / markdown-it, a comment that occupies a whole line is
// detected as a block-level HTML element and the preceding paragraph is
// closed before it. Pre-rewrite the source so a comment line that
// immediately follows a non-blank "regular text" line and is itself
// followed by a blank line is JOINED to the preceding line. markdown-it
// then treats the `<!-- ... -->` as inline raw HTML inside the same
// paragraph, matching kramdown.
//
// Conservative: skip if the previous line is a fence, heading, list
// marker, blockquote marker, or HTML-block opener -- those don't form
// the kind of paragraph kramdown would absorb the comment into.
const HTML_COMMENT_LINE_RE = /^[ \t]*<!--[^\n]*-->[ \t]*$/;
const PARAGRAPH_CONTINUATION_RE = /^[ \t]*[^\s#>*+\-`~|<\[].*$/;
function absorbTrailingHtmlComments(src) {
const lines = src.split("\n");
const out = [];
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (
i > 0
&& HTML_COMMENT_LINE_RE.test(line)
&& PARAGRAPH_CONTINUATION_RE.test(lines[i - 1])
&& (i + 1 >= lines.length || lines[i + 1].trim() === "")
) {
// Append to the previous emitted line with a single space.
out[out.length - 1] = `${out[out.length - 1]} ${line.trim()}`;
} else {
out.push(line);
}
}
return out.join("\n");
}
// kramdown quirk: when `---` appears on a line directly after a list item,
// it treats the previous list item's content as a setext H2 INSIDE the
// <li>, and the `---` does NOT terminate the list. markdown-it instead
// reads `---` as <hr> after the list. Rewrite the source to make the
// promoted item explicit: `- text\n---\n` becomes `- ## text\n` so
// markdown-it emits an <li><h2>text</h2></li> at that position.
const LIST_ITEM_SETEXT_RE = /^([ \t]*[*+\-][ \t]+)([^\n]*?)\n[ \t]*---[ \t]*$/gm;
function rewriteListItemSetextHeadings(src) {
return src.replace(LIST_ITEM_SETEXT_RE, (_, marker, text) => `${marker}## ${text}`);
}
// markdown-it inline newline rule, modified to keep all-but-the-final-
// two trailing spaces in the pending text. Matches kramdown's behaviour
// (the line-break regex `( )(?=\n)` consumes exactly the final two
// spaces). Otherwise identical to the upstream rule.
function kramdownHardBreakNewline(state, silent) {
let pos = state.pos;
if (state.src.charCodeAt(pos) !== 0x0A) return false;
const pmax = state.pending.length - 1;
const max = state.posMax;
if (!silent) {
if (pmax >= 0 && state.pending.charCodeAt(pmax) === 0x20) {
if (pmax >= 1 && state.pending.charCodeAt(pmax - 1) === 0x20) {
// Two-or-more trailing spaces -> hardbreak. Strip only the final
// two; preserve any additional trailing spaces in the text.
state.pending = state.pending.slice(0, pmax - 1);
state.push("hardbreak", "br", 0);
} else {
state.pending = state.pending.slice(0, -1);
state.push("softbreak", "br", 0);
}
} else {
state.push("softbreak", "br", 0);
}
}
pos++;
while (pos < max && state.src.charCodeAt(pos) === 0x20) pos++;
while (pos < max && state.src.charCodeAt(pos) === 0x09) pos++;
state.pos = pos;
return true;
}
// kramdown normalises HTML void elements to the XHTML self-closing form
// (`<br />`, `<hr />`, `<img ... />`) regardless of the input shape.
// markdown-it with `xhtmlOut: true` emits the same form for tokens it
// generates, but raw block / inline HTML (like author-written `<br>`)
// passes through verbatim. Rewrite those to match.
//
// The attributes are one flat `[^>]*`, and the trailing `/` is removed
// afterwards rather than described in the pattern. That is deliberate,
// and the history is worth keeping because the obvious shape was tried
// twice and was wrong twice.
//
// This used to spell the attribute list out as
// `(?:\s+[^>/]+(?:="[^"]*"|='[^']*')?)*`. `[^>/]` matches a space and so
// does `\s`, which makes it the classic `(a+)+`: one run of attribute
// text can be partitioned in exponentially many ways, and every
// partition gets tried when the match fails -- which it does on any `/`
// the quoted-value alternative does not cover. `Line/Column` in the alt
// text of IDE/Menu/Edit.md and `/Packages/WinDevLib` in
// Features/Packages/Updating a package.md each hung a render worker
// outright: two of 152 chunks stayed CLAIMED, the renderJoin and
// flushJoin barriers behind them never reached a dep count of zero, and
// the build printed its last line and sat there forever.
//
// Narrowing the class to `[^\s>/]+` fixed those two strings and did not
// fix the regex: `[^\s>/]` still matches `=`, `"` and `'`, so an
// attribute could be consumed either by the name class or by the
// quoted-value alternative, and that binary choice per attribute is the
// same 2^n one level down. scripts/check_regex_safety.mjs caught it with
// the witness `<BR\tG=` + `""\t"=''\t=='/">'\tG=` -- 186 characters took
// 97 ms and it grew from there.
//
// So do not reintroduce a per-attribute sub-pattern. Matching to the
// first `>` cannot be ambiguous, because `[^>]*` and the `>` that
// follows it share no character. Verified against every void tag in the
// built site -- 4,137 distinct tags, byte-identical output -- and
// recheck's own worst witness now runs in under a millisecond at 288,006
// characters.
const VOID_TAGS_RE = /<(br|hr|img|input|link|meta|area|base|col|embed|source|track|wbr)\b([^>]*)>/gi;
// Drop an existing self-closing slash and the whitespace around it, so
// the emitted tag ends in exactly one ` />`. Three anchored one-liners
// rather than one combined pattern: each is separately trivial to read
// and none of them can backtrack.
function stripSelfClose(attrs) {
return attrs.replace(/\s+$/, "").replace(/\/$/, "").replace(/\s+$/, "");
}
function normaliseVoidTags(html) {
return html.replace(VOID_TAGS_RE, (_, tag, attrs) =>
`<${tag.toLowerCase()}${stripSelfClose(attrs)} />`);
}
// ---------- markdown-it configuration ---------------------------------------
export { initHighlighter };
export function createMarkdownIt(ctx) {
const md = new MarkdownIt({
// kramdown parse_block_html + parse_span_html; recursion handled by
// blockHtmlRecursionPlugin (PLAN-3 §5.12).
html: true,
// kramdown emits self-closing <br /> / <hr /> (XHTML form); CommonMark
// default is HTML5 <br>. Match kramdown.
xhtmlOut: true,
// kramdown hard_wrap is OFF on this site -- single newlines are not
// <br>. Two-space line breaks still produce <br> via CommonMark.
breaks: false,
// Site content uses explicit [text](url) form; no bare URLs in body
// prose. Off matches current rendered output.
linkify: false,
// -- -> en-dash, --- -> em-dash, ASCII quotes -> curly. Matches
// kramdown smart_quotes; see PLAN-3 §5.9 for divergences.
typographer: true,
quotes: "“”‘’",
highlight: ctx.highlighter ? (code, lang) => ctx.highlighter.render(code, lang) : undefined,
});
// `hidden` as a whitespace-separated token anywhere after the language.
// Matched against the raw info string rather than parsed with
// scripts/lib/tb-fences.mjs's parseInfo: builder/ must not depend on
// scripts/, and this is the one token of that markup the renderer cares
// about. The word has to stand alone, or a language called `hidden-x` or a
// key like `id=hidden` would suppress a fence the author meant to publish.
const HIDDEN_FENCE_RE = /^\S+(?:\s+\S+)*?\s+hidden(?:\s|$)/;
// Override the fence renderer so our highlight callback's wrapper HTML
// (which starts with <div, not <pre>) is used verbatim. Without this,
// markdown-it's default fence rule wraps it in another <pre><code>.
//
// When the fence is nested (inside a list item, admonition, or other
// block container), kramdown inserts a newline between the inner
// `</div>` and the outer `</div>` of the wrapper as part of its
// indented-block pretty-printing -- the html-compress pass then
// renders that as a single space. Mirror by splicing a `\n` between
// the close tags when level > 0.
md.renderer.rules.fence = (tokens, idx, options) => {
const tok = tokens[idx];
const lang = tok.info ? tok.info.trim().split(/\s+/)[0] : "";
// A fence marked `hidden` is context for the compile gate, not content:
// scripts/check_examples.mjs builds it with the page's other samples so
// that the declarations a sample assumes can live beside it rather than in
// a shared template, and the reader never sees it. Emitting nothing here
// keeps it out of the HTML, and therefore out of the search index, the
// offline mirror and the PDF book, all of which read the rendered string.
if (HIDDEN_FENCE_RE.test(tok.info ?? "")) return "";
const html = options.highlight(tok.content, lang);
if (tok.level > 0 || tok.meta?.nestedInBlock) {
return html.replace(/<\/div><\/div>$/, "</div>\n</div>") + "\n";
}
return html + "\n";
};
// Indented (4-space) code blocks have no language info. kramdown wraps
// them in the same Rouge wrapper shape used for fences with a
// `language-plaintext` class. markdown-it's default emits a bare
// `<pre><code>` -- override to match.
md.renderer.rules.code_block = (tokens, idx, _opts, _env, _slf) => {
const tok = tokens[idx];
const body = escapeHtmlMinimal(tok.content);
return `<div class="language-plaintext highlighter-rouge"><div class="highlight" tabindex="0"><pre class="highlight"><code>${body}</code></pre></div></div>\n`;
};
// kramdown/just-the-docs tag inline `code` spans with the Rouge wrapper
// class so the same CSS rules style both block-level highlights and
// inline ones. Match that, and escape only `& < >` (matching kramdown's
// code-span escape) -- leaving `"` and `'` literal so embedded HTML
// attribute syntax stays readable.
md.renderer.rules.code_inline = (tokens, idx, _opts, _env, slf) => {
const tok = tokens[idx];
return `<code class="language-plaintext highlighter-rouge"${slf.renderAttrs(tok)}>${escapeHtmlMinimal(tok.content)}</code>`;
};
// just-the-docs wraps every <table> in <div class="table-wrapper"> via
// its `_includes/table_wrappers.html` Liquid pass. Mirror that here so
// CSS rules keyed on `.table-wrapper > table` keep working. Use the
// default renderToken first so markdown-it's per-token block-prefix
// whitespace handling still produces the leading newline when the
// table sits at the start of a list-item / dd / blockquote child.
//
// tabindex="0" for the same reason highlight.mjs puts it on div.highlight
// (PLAN-a11y.md 1.9): the wrapper is `overflow-x: auto` (JTD
// tables.scss:11), and a scroll container a keyboard user cannot focus
// cannot be scrolled without a pointer. Unconditional, as on code blocks --
// whether a given table overflows depends on the viewport, so there is no
// render-time answer. custom.scss gives the focus a visible ring.
md.renderer.rules.table_open = (tokens, idx, opts, _env, slf) =>
slf
.renderToken(tokens, idx, opts)
.replace(/<table>/, `<div class="table-wrapper" tabindex="0"><table>`);
md.renderer.rules.table_close = (tokens, idx, opts, _env, slf) =>
`</table></div>` + slf.renderToken(tokens, idx, opts).replace(/<\/table>/, "");
// kramdown emits `style="text-align: left"` with a space after the
// colon; markdown-it emits the compact form. Override the th/td
// renderers to widen the gap.
const styleSpace = (defaultRule) => (tokens, idx, opts, env, slf) => {
const tok = tokens[idx];
const styleIdx = tok.attrIndex("style");
if (styleIdx >= 0) {
tok.attrs[styleIdx][1] = tok.attrs[styleIdx][1].replace(/:/g, ": ");
}
return slf.renderToken(tokens, idx, opts);
};
md.renderer.rules.th_open = ((defaultRule) => (tokens, idx, opts, env, slf) => {
const tok = tokens[idx];
const styleIdx = tok.attrIndex("style");
if (styleIdx >= 0) {
tok.attrs[styleIdx][1] = tok.attrs[styleIdx][1].replace(/:/g, ": ");
}
tok.attrSet("scope", "col");
return slf.renderToken(tokens, idx, opts);
})();
md.renderer.rules.td_open = styleSpace();
// kramdown renders ordered lists with no `start` attribute even when
// the source numbers don't begin at 1 (it ignores the source
// numbering entirely). markdown-it preserves it; strip to match.
md.renderer.rules.ordered_list_open = (tokens, idx, _opts, _env, slf) => {
const tok = tokens[idx];
const startIdx = tok.attrIndex("start");
if (startIdx >= 0) tok.attrs.splice(startIdx, 1);
return slf.renderToken(tokens, idx, slf.options);
};
// Override the inline newline rule to match kramdown's hard-break
// semantics. kramdown's regex `( )(?=\n)` consumes EXACTLY the two
// spaces immediately before the newline -- any additional trailing
// spaces are preserved in the text. markdown-it's default rule strips
// ALL trailing spaces before emitting the hardbreak. For 2-space hard
// breaks (the common case) both behaviours are identical; the
// divergence shows up with 3+ trailing spaces, where Jekyll renders
// `text <br />` (one trailing space) and we render `text<br />`.
md.inline.ruler.at("newline", kramdownHardBreakNewline);
// kramdown's `{: ... }` attribute syntax. Default plugin delimiters
// are `{` / `}`; we override both to require the colon.
md.use(attrs, {
leftDelimiter: "{:",
rightDelimiter: "}",
});
md.use(standaloneIalForwardPlugin);
md.use(tightLooseListPlugin);
md.use(deflist);
md.use(looseDeflistPlugin);
md.use(footnote);
configureFootnotes(md);
md.use(headerIdPlugin);
md.use(headingLevelNormalizePlugin);
md.use(tocPlugin);
md.use(relativeLinksPlugin, ctx);
md.use(blockHtmlRecursionPlugin);
md.use(kramdownDashesPlugin);
md.use(kramdownEllipsisPlugin);
md.use(flattenAdjacentStrongPlugin);
md.use(svgInlinePlugin, ctx);
md.use(videoLinkPlugin, ctx);
md.use(remoteImagePlugin, ctx);
// Substitutes {{tbdocs:<name>}} in prose. Registered last so it runs after
// `replacements` has done the dash and quote transforms -- see counts.mjs
// for why the layer matters and what it deliberately cannot reach.
md.use(countPlugin, ctx);
return md;
}
// kramdown pairs adjacent `**` markers left-to-right (1st with 2nd,
// 3rd with 4th, ...). markdown-it follows CommonMark's emphasis rule,
// which prefers nesting when intermediate `**` markers can both open
// and close (e.g. `**X"**Y**"Z**` -> outer strong wrapping an inner
// strong). Detect the depth-2 nested-strong-with-text shape and
// flatten it back to two sibling strongs with the inner content as
// plain text between them.
function flattenAdjacentStrongPlugin(md) {
md.core.ruler.after("inline", "flatten-adjacent-strong", (state) => {
walkInlineChildren(state.tokens, (children) => {
let i = 0;
while (i < children.length) {
// Pattern (level L):
// [i ] strong_open (level L)
// [i+1] text (level L+1) -- non-empty, "outer-left"
// [i+2] strong_open (level L+1)
// [i+3] text (level L+2) -- "inner"
// [i+4] strong_close (level L+1)
// [i+5] text (level L+1) -- non-empty, "outer-right"
// [i+6] strong_close (level L)
const t0 = children[i];
if (t0 && t0.type === "strong_open"
&& children[i + 1]?.type === "text"
&& children[i + 2]?.type === "strong_open"
&& children[i + 3]?.type === "text"
&& children[i + 4]?.type === "strong_close"
&& children[i + 5]?.type === "text"
&& children[i + 6]?.type === "strong_close"
&& children[i + 2].markup === t0.markup
&& children[i + 4].markup === t0.markup
&& children[i + 6].markup === t0.markup) {
// Repair the nesting:
// inner strong_open -> outer strong_close
// inner strong_close -> outer strong_open
// Level of each remaining content drops by one (was inside
// the outer-then-inner stack, now only one deep at most).
const innerOpen = children[i + 2];
const innerClose = children[i + 4];
const baseLevel = t0.level;
innerOpen.type = "strong_close";
innerOpen.tag = "strong";
innerOpen.nesting = -1;
innerOpen.level = baseLevel;
innerClose.type = "strong_open";
innerClose.tag = "strong";
innerClose.nesting = 1;
innerClose.level = baseLevel;
// Plain-text middle is now at level baseLevel.
children[i + 3].level = baseLevel;
// Outer-left / outer-right texts retain their levels (still
// inside a strong each).
// No re-numbering of subsequent tokens needed -- levels are
// only used by the renderer for indentation and our other
// post-passes; the outer strong_close at i+6 is already at
// baseLevel.
i += 7;
continue;
}
i++;
}
});
});
}
// markdown-it's `replacements` core rule collapses every run of 2+ dots
// (`.{2,}`) to a single ellipsis `…`. kramdown is stricter: it converts
// exactly THREE consecutive dots to `…` and leaves any extra dots as
// plain dots. The two behaviours diverge on `....`, `.....`, etc.:
// kramdown writes `….`, `…..`, ...; markdown-it writes `…`, `…`, ....
// Walk text tokens after typographer has run; for each contiguous run of
// `…` immediately following a word/punctuation char (i.e. not in
// `?…` / `!…` patterns the upstream regex already special-cases),
// recover the missing dots if the source had >3 dots in a row.
function kramdownEllipsisPlugin(md) {
md.core.ruler.after("replacements", "kramdown-ellipsis", (state) => {
// The replacements rule has already collapsed `.{2,}` -> `…` (with
// `?…` / `!…` -> `?..` / `!..` exceptions). We can't recover the
// pre-collapse count from the token alone -- examine the inline
// token's source content, count consecutive dots in the source, and
// pad the rendered `…` with N-3 trailing dots when N > 3.
for (const blk of state.tokens) {
if (blk.type !== "inline" || !blk.children) continue;
const src = blk.content;
if (!/\.{4,}/.test(src)) continue;
// Walk text children left-to-right tracking source position by
// counting characters consumed. For each `…` we encounter in the
// text content, peek the source string to count how many dots
// were originally there.
let srcPos = 0;
for (const t of blk.children) {
if (t.type !== "text" || !t.content) continue;
let out = "";
for (let i = 0; i < t.content.length; i++) {
const ch = t.content[i];
if (ch === "…") {
// Find the matching dot run starting at or near srcPos.
const m = src.slice(srcPos).match(/^[^.…]*\.{3,}/);
const dotCount = m ? m[0].match(/\.+$/)[0].length : 3;
out += "…";
for (let k = 3; k < dotCount; k++) out += ".";
srcPos += (m ? m[0].length : 3);
} else if (ch === "—" || ch === "–") {
out += ch;
// skip 2-3 source chars for en/em-dash conversions
const skip = src.startsWith("---", srcPos) ? 3 : (src.startsWith("--", srcPos) ? 2 : 1);
srcPos += skip;
} else {
out += ch;
srcPos++;
}
}
t.content = out;
}
}
});
}
// ---------- kramdown-style smart dashes -------------------------------------
//
// markdown-it's typographer converts `--` -> en-dash only when neither
// side is whitespace ("word--word"). kramdown converts unconditionally:
// `word-- word` -> `word– word`. Run a small pass over inline text
// tokens after markdown-it's typographer has finished, replacing the
// remaining `---` with em-dash and `--` with en-dash. text tokens
// inside code spans and code blocks are separate token types
// (code_inline / code_block / fence), so they're untouched.
function kramdownDashesPlugin(md) {
md.core.ruler.after("replacements", "kramdown-dashes", (state) => {
walkTokens(state.tokens, (t) => {
if (t.type !== "text") return;
if (t.content.includes("--")) {
t.content = t.content.replace(/---/g, "—").replace(/--/g, "–");
}
// kramdown's smart_quotes also converts `<<` and `>>` to
// left/right guillemets (« / »). markdown-it's typographer
// doesn't, so do it here. Same `text`-token-only restriction
// keeps code spans and code blocks untouched.
if (t.content.includes("<<")) t.content = t.content.replace(/<<(?!=)/g, "«").replace(/<<=/g, "«=");
if (t.content.includes(">>")) t.content = t.content.replace(/>>(?!=)/g, "»").replace(/>>=/g, "»=");
});
});
// kramdown converts a straight ASCII `'` to a right-curly `’` whenever
// it follows non-whitespace and precedes a word character -- so
// `C/C++'s typedef` becomes `C/C++’s typedef`. markdown-it's
// smartquotes rule is stricter (requires word-char on both sides), so
// possessive apostrophes after punctuation stay straight. Run a
// post-smartquotes sweep on text tokens to fix the gap.
md.core.ruler.after("smartquotes", "kramdown-possessive", (state) => {
walkTokens(state.tokens, (t) => {
if (t.type !== "text") return;
if (!t.content.includes("'")) return;
t.content = t.content.replace(/(\S)'(?=\w)/g, "$1’");
});
});
// Kramdown's smart_quotes parser operates on the raw source string,
// so quotes adjacent to emphasis markers (`**"foo"**`) end up curled
// via rules that markdown-it's typographer (which operates on parsed
// text tokens, blind to siblings) can't reach. The result: Jekyll
// renders `<strong>"foo"</strong>` while we emit `<strong>"foo"</strong>`.
//
// Translate kramdown's two relevant patterns into token-stream rules:
//
// * Text ending with `"` / `'` followed by strong_close or em_close
// (`**...X"**`). Source scanner is positioned at X (the char before
// the quote, in the same text); rule 6 `(SQ_CLOSE)(quote)` fires
// when X is in SQ_CLOSE = `[^ \\\t\r\n\[{(-]`, otherwise rule 9
// catchall renders it as the opening curly form. Mirror: rdquo /
// rsquo if X is a "closing-friendly" char, ldquo / lsquo otherwise.
//
// * Text starting with `"` / `'` preceded by strong_open or em_open
// (`**"X...**`). Source scanner is positioned at the quote (the
// `**` was already consumed). Rules in order:
// - rule 1 (rquote1, SQ_PUNCT lookahead) -> rdquo if next char
// in same text is one of [!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~].
// - rule 7 (rquote1, \s|s\b|$ lookahead) -> rdquo if next char
// is whitespace, `s` at word boundary, or end of content.
// - else falls through to rule 9 catchall -> ldquo.
md.core.ruler.after("smartquotes", "kramdown-quote-near-emphasis", (state) => {
walkInlineChildren(state.tokens, (children) => {
for (let i = 0; i < children.length; i++) {
const t = children[i];
if (t.type !== "text" || !t.content) continue;
const last = t.content[t.content.length - 1];
if ((last === '"' || last === "'") && isEmphasisClose(children[i + 1])) {
// Char before the quote, in the same text token.
const charBefore = t.content.length >= 2 ? t.content[t.content.length - 2] : "";
const closing = !SQ_CLOSE_EXCLUDED.has(charBefore) && charBefore !== "";
if (closing) {
t.content = t.content.slice(0, -1) + (last === '"' ? "”" : "’");
} else {
t.content = t.content.slice(0, -1) + (last === '"' ? "“" : "‘");
}
}
const first = t.content[0];
if ((first === '"' || first === "'") && isEmphasisOpen(children[i - 1])) {
const charAfter = t.content.length >= 2 ? t.content[1] : "";
let closing = false;
if (charAfter === "") closing = true; // rule 7 EOL branch
else if (SQ_PUNCT_RE.test(charAfter)) closing = true; // rule 1
else if (/\s/.test(charAfter)) closing = true; // rule 7 \s branch
if (closing) {
t.content = (first === '"' ? "”" : "’") + t.content.slice(1);
} else {
t.content = (first === '"' ? "“" : "‘") + t.content.slice(1);
}
}
// Text starting with a quote whose previous sibling is an
// emphasis CLOSE (e.g. `*foo*'th` or `**foo**'s`). markdown-it
// already curls this as `’` / `”` (closing). kramdown's
// scanner at this position runs the same rule cascade as text
// after emphasis_open above:
// - rule 1 (next char SQ_PUNCT) -> closing
// - rule 7 EOL / `\s` / `s\b` lookahead -> closing
// - else (word char follows, not `s\b`) -> rule 9 -> opening
// The `s\b` branch of rule 7 fires for the apostrophe-s
// possessive (`*foo*'s`), keeping it closing. Other word
// characters fall through to rule 9 and flip to opening.
if ((first === "’" || first === "”") && isEmphasisClose(children[i - 1])) {
const charAfter = t.content.length >= 2 ? t.content[1] : "";
const charAfter2 = t.content.length >= 3 ? t.content[2] : "";
let closing = false;
if (charAfter === "") closing = true;
else if (SQ_PUNCT_RE.test(charAfter)) closing = true;
else if (/\s/.test(charAfter)) closing = true;
else if (first === "’" && charAfter === "s" && !/\w/.test(charAfter2)) closing = true;
if (!closing) {
t.content = (first === "’" ? "‘" : "“") + t.content.slice(1);
}
}
}
});
});
}
// kramdown's SQ_CLOSE = `[^ \\\t\r\n\[{(-]`: characters that, when they
// appear just before a quote, mark that quote as "closing" via rule 6.
// Encode the EXCLUDED set so a positive lookup gives us the inverse.
const SQ_CLOSE_EXCLUDED = new Set([" ", "\\", "\t", "\r", "\n", "[", "{", "(", "-"]);
// kramdown's SQ_PUNCT character class.
const SQ_PUNCT_RE = /[!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~]/;
// Any straight or curly quote character.
const QUOTE_ANY_RE = /["'“”‘’]/;
// Apply kramdown-style smart-quote conversion to a raw HTML body --
// used for content inside `<summary markdown=span>...</summary>` and
// similar inline elements where kramdown's HTML parser descends and
// applies inline conversions. Implements the same SQ_RULES cascade
// (rules 1, 6, 7, 9) on the raw text outside of nested tags:
// - `<context-char>"` -> rdquo (rule 6: SQ_CLOSE before quote)
// - `"<word-like>` -> rdquo via rule 7 (s\b) or fall to ldquo
// Conservative scan -- only converts straight `'` / `"` that look like
// English text quotes; leaves HTML attribute quotes alone by skipping
// content inside `<...>` brackets.
function applyKramdownSmartQuotes(body) {
if (!/['"]/.test(body)) return body;
// Walk char-by-char, skipping anything between `<` and `>` (inline
// tags) and any HTML entity. Track "previous visible char" so we can
// decide whether each `'` / `"` is opening or closing.
let out = "";
let i = 0;
let prev = ""; // last non-tag char emitted (or "" at start)
while (i < body.length) {
const ch = body[i];
if (ch === "<") {
const end = body.indexOf(">", i);
if (end < 0) { out += body.slice(i); break; }
out += body.slice(i, end + 1);
i = end + 1;
prev = ">";
continue;
}
if (ch === "'" || ch === '"') {
const next = body[i + 1] || "";
const isDouble = ch === '"';
// Rule 1 (kramdown SQ rule 126): quote followed by SQ_PUNCT -> rquote.
// Rule 7 (rule 139): quote followed by whitespace / `s\b` / EOL -> rquote.
// Rule 6 (rule 137): SQ_CLOSE before quote -> rquote.
// Default fall-through: ldquo.
const closingByPunct = SQ_PUNCT_RE.test(next);
const closingByWS = /\s/.test(next) || next === "";
const closingByS = !isDouble && next === "s" && !/\w/.test(body[i + 2] || "");
const closingByPrev = prev !== "" && !SQ_CLOSE_EXCLUDED.has(prev);
const closing = closingByPunct || closingByWS || closingByS || closingByPrev;
out += closing ? (isDouble ? "”" : "’") : (isDouble ? "“" : "‘");
prev = ch;
i++;
continue;
}
out += ch;
prev = ch;
i++;
}
return out;
}
function isEmphasisOpen(tok) {
return tok && (tok.type === "strong_open" || tok.type === "em_open");
}
function isEmphasisClose(tok) {
// Treat `code_inline` like an emphasis_close for smart-quote purposes:
// kramdown's source-position scanner sees `\`...\`'word` the same as
// `*...*'word` -- the backtick is consumed first, scanner lands AT
// the quote, and the same rule cascade fires.
return tok && (tok.type === "strong_close" || tok.type === "em_close" || tok.type === "code_inline");
}
// Walk inline-token children arrays so a visitor can examine adjacent
// siblings. The plain walkTokens helper recurses but only sees one token
// at a time -- this variant invokes the visitor once per inline token's
// children array (the level at which siblings live).
function walkInlineChildren(tokens, visit) {
for (const t of tokens) {
if (t.type === "inline" && Array.isArray(t.children)) {
visit(t.children);
}
}
}
// ---------- standalone IAL forward attachment -------------------------------
//
// kramdown rule: a standalone block IAL (an IAL that takes up an entire
// paragraph) attaches to the FOLLOWING block, not the preceding one.
// markdown-it-attrs attaches them to the paragraph itself, leaving the
// paragraph's inline children empty. Detect that, move the attrs to the
// next block-level token, and splice out the now-empty paragraph triplet.
function standaloneIalForwardPlugin(md) {
// kramdown's standalone-IAL attachment is direction-sensitive:
// - IAL adjacent to the previous block (no blank line between)
// attaches BACKWARD to that block.
// - IAL separated by a blank line attaches FORWARD to the next
// block.
// markdown-it-attrs always parses the IAL as its own paragraph and
// sets the attrs on it -- losing both behaviours. Detect the
// standalone shape (paragraph whose inline content was entirely
// consumed as attrs) and re-target the attrs onto the right
// neighbour using token.map to look up the source-line gap.
md.core.ruler.after("curly_attributes", "standalone-ial-attach", (state) => {
const srcLines = state.src.split("\n");
const toks = state.tokens;
// Lines previously occupied by a now-removed standalone IAL --
// counts as "non-blank" when checking adjacency for a following
// IAL (so multiple consecutive IALs all attach to the same
// preceding block, as kramdown does).
const consumedLines = new Set();
for (let i = 0; i < toks.length; i++) {
const open = toks[i];
if (open.type !== "paragraph_open") continue;
if (!open.attrs || open.attrs.length === 0) continue;
const inline = toks[i + 1];
if (inline?.type !== "inline") continue;
const hasVisibleContent = (inline.children || []).some(
(c) => c.type !== "text" || c.content !== "",
);
if (hasVisibleContent) continue;
const close = toks[i + 2];
if (close?.type !== "paragraph_close") continue;
const prev = toks[i - 1];
const next = toks[i + 3];
let target = null;
if (prev && isHeadingOrParagraphClose(prev)) {
const prevOpen = findBlockOpenFor(toks, i - 1);
if (prevOpen && ialAdjacentToPrev(prevOpen, open, consumedLines)) {
target = prevOpen;
}
}
if (!target && next) target = next;
if (!target) continue;
// markdown-it-attrs collapses consecutive standalone IALs into the
// attrs of the first paragraph but emits them in REVERSE source
// order. Detect the multi-line IAL paragraph (map spans 2+ lines)
// and reverse to match kramdown's source-order output.
const attrsList = open.map && open.map[1] - open.map[0] > 1
? [...open.attrs].reverse()
: open.attrs;
mergeAttrs(target, attrsList);
// Record the IAL's source line range so a following IAL one
// line away still counts as adjacent to the heading.
if (open.map) {
for (let ln = open.map[0]; ln < open.map[1]; ln++) consumedLines.add(ln);
}
toks.splice(i, 3);
i--;
}
});
}
// True when the IAL paragraph's first source line is the line right
// after the previous block's last source line (no blank line gap).
// Consumed lines (occupied by removed earlier IALs) count as belonging
// to the previous block so that consecutive `{: ... }` IALs all attach
// to the same heading.
function ialAdjacentToPrev(prevOpen, ialOpen, consumedLines) {
if (!prevOpen.map || !ialOpen.map) return false;
let line = prevOpen.map[1];
while (line < ialOpen.map[0]) {
if (!consumedLines.has(line)) return false;
line++;
}
return true;
}
function isHeadingOrParagraphClose(t) {
return t.type === "heading_close" || t.type === "paragraph_close";
}
// Walk back from a close token to its matching open token at the same
// nesting level. Tag matches (h1 close -> h1 open, p close -> p open).
function findBlockOpenFor(toks, closeIdx) {
const close = toks[closeIdx];
const openType = close.type.replace("_close", "_open");
let depth = 0;
for (let k = closeIdx; k >= 0; k--) {
const t = toks[k];
if (t.type === close.type && t.tag === close.tag) depth++;
else if (t.type === openType && t.tag === close.tag) {
depth--;
if (depth === 0) return t;
}
}
return null;
}
// ---------- loose-deflist <p> rewrap ----------------------------------------
//
// markdown-it-deflist emits paragraph_open / paragraph_close around every
// <dd> body but marks them `hidden=true` when the list parses as "tight".
// kramdown's rule is per-item: a definition that's separated from its
// term by a blank line wraps in <p>. Detect that gap by comparing the dt
// term's end line to the inner paragraph_open's start line and unhide
// the wrapper pair when the gap is >1.
// ---------- list-item paragraph unwrap (kramdown tightness) -----------------
//
// markdown-it determines tightness at the LIST level: any blank line
// between top-level items makes the entire list loose, which adds
// `<p>...</p>` around every item's inline content. kramdown's rule is
// per-item: an item gets `<p>` wrap only when it actually contains
// multiple paragraph blocks (e.g. inline + blank + more inline). An
// item that's just "inline + nested list" stays unwrapped.
//
// We post-process after block parsing: for each list_item_open, count
// the top-level paragraph_open tokens. If there's exactly one (the
// initial inline content), hide its paragraph_open / paragraph_close
// to match kramdown's tight emit.
function tightLooseListPlugin(md) {
md.core.ruler.after("block", "tight-loose-list", (state) => {
const srcLines = state.src.split("\n");
const toks = state.tokens;
// Records per-item tightness decisions so the post-pass can apply
// kramdown's "last item is loose unless an earlier sibling is
// tight" rule (see kramdown/parser/kramdown/list.rb#132-139).
// Keyed by list_item_open token index; value = { wouldBeTight,
// listListOpenIdx, paraOpenIdx, paraCloseIdx }.
const decisions = new Map();
// Map of list_open index -> array of contained item indices.
const listItems = new Map();
for (let i = 0; i < toks.length; i++) {
if (toks[i].type !== "list_item_open") continue;
const itemLevel = toks[i].level;
const itemMap = toks[i].map;
let firstParaOpenIdx = -1;