lagrange-library 0.3.3

A WASI-rendered Markdown static site facility — multilingual out of the box
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
//! Markdown parser.
//!
//! Block structure is detected line-by-line in Rust (mirroring the
//! ratatui-markdown scheme); each block's inline content is tokenised by the
//! pest grammar in `grammar.pest`.
//!
//! The parse core produces [`SpannedBlock`]s — every block (top-level and
//! nested inside containers) carries its source coordinates relative to the
//! **full source file**, the heading path it sits under, and a stable
//! content-addressed id. Two entry points:
//!
//! - [`parse`] — plain markdown, returns bare [`Block`]s (spans stripped);
//!   the historical API, unchanged in shape.
//! - [`parse_doc`] — a full source file (frontmatter included); coordinates
//!   are compensated for the stripped frontmatter so spans slice the
//!   original file directly.

use std::collections::HashMap;

use pest::{iterators::Pair, Parser as _};
use pest_derive::Parser;
use sha2::{Digest, Sha256};

use super::ast::{Block, Inline, ListItem, SourceSpan, SpannedBlock};

#[derive(Parser)]
#[grammar = "markdown/grammar.pest"]
pub struct InlineParser;

/// Parse plain markdown into bare blocks (the historical entry point).
///
/// Coordinates are computed and then stripped; use [`parse_doc`] when the
/// source coordinates matter.
pub fn parse(input: &str) -> Vec<Block> {
    parse_with_depth(input, 0)
}

/// [`parse`] with the list-nesting depth the scan starts at. `finish_item`
/// re-scans an item's dedented lines, so every nesting level is a fresh
/// `parse` pass; carrying the depth across passes is what bounds recursion on
/// pathological input (`"- " * 1000`).
fn parse_with_depth(input: &str, list_depth: usize) -> Vec<Block> {
    strip_spans(parse_body_spanned_at(input, 0, list_depth))
}

/// Parse a full markdown source file (frontmatter included) into blocks with
/// source coordinates. Spans index the full file, so a consumer can slice the
/// original bytes by span without re-deriving the frontmatter offset.
pub fn parse_doc(input: &str) -> Vec<SpannedBlock> {
    let (_kind, _fm, body, body_offset) = crate::frontmatter::strip_with_offset(input);
    if body.is_empty() {
        return Vec::new();
    }
    // The byte tables below are built over the FULL file, so byte
    // coordinates need no compensation; only the scan start (line index) and
    // the 1-based line shift move past the frontmatter.
    let body_line = input[..body_offset].matches('\n').count();
    parse_body_spanned_at(input, body_line, 0)
}

/// Scan `input`'s line tables starting at line `body_line` (0-based). The
/// tables carry full-file byte coordinates; the shift adds `body_line` to
/// turn slice-relative indices back into 1-based file line numbers.
fn parse_body_spanned_at(input: &str, body_line: usize, list_depth: usize) -> Vec<SpannedBlock> {
    let (lines, starts, ends) = line_tables(input);
    if body_line >= lines.len() {
        return Vec::new();
    }
    let mut ctx = Ctx::default();
    let mut scan = Scan {
        full: input,
        shift: TableShift {
            line_shift: body_line,
        },
        stack: Vec::new(),
        ctx: &mut ctx,
        list_depth,
    };
    parse_spanned_lines(
        &lines[body_line..],
        &starts[body_line..],
        &ends[body_line..],
        &mut scan,
    )
}

// ── source coordinate tables ──────────────────────────────────────────────

fn line_tables(input: &str) -> (Vec<&str>, Vec<usize>, Vec<usize>) {
    let mut lines = Vec::new();
    let mut starts = Vec::new();
    let mut ends = Vec::new();
    let mut off = 0usize;
    for raw in input.split('\n') {
        starts.push(off);
        let stripped = raw.strip_suffix('\r').unwrap_or(raw);
        ends.push(off + stripped.len());
        lines.push(stripped);
        off += raw.len() + 1;
    }
    (lines, starts, ends)
}

/// How far the current line slice is shifted inside the enclosing file:
/// every block's line numbers get `line_shift` added (turning 0-based loop
/// indices into 1-based file lines).
///
/// Byte coordinates are NOT derived from this shift — the byte tables are
/// built once for the whole file and sub-slices keep absolute offsets (the
/// blockquote additionally points each inner line past its `>` prefix), so
/// `starts`/`ends` are already file-absolute everywhere. Only line numbers
/// need the running shift, and container recursion therefore adds its own
/// slice offset instead of forwarding this value unchanged.
#[derive(Clone, Copy)]
struct TableShift {
    line_shift: usize,
}

impl TableShift {
    fn span(
        &self,
        starts: &[usize],
        ends: &[usize],
        first: usize,
        end_exclusive: usize,
    ) -> SourceSpan {
        let last = end_exclusive - 1;
        SourceSpan {
            start_line: first + 1 + self.line_shift,
            end_line: last + 1 + self.line_shift,
            start_byte: starts[first],
            end_byte: ends[last],
        }
    }
}

// ── block ids & heading stack ─────────────────────────────────────────────

#[derive(Default)]
struct Ctx {
    /// Block source text → how many times it has been seen in this document.
    /// Identical blocks disambiguate as `b-<hash>-2`, `-3`, …; the first
    /// occurrence keeps the bare content hash.
    id_counts: HashMap<String, usize>,
}

/// Everything the block scan needs besides the line tables. Container
/// recursion clones `stack` so a heading nested inside a blockquote/div
/// annotates its own subtree without altering the document-level stack.
struct Scan<'a> {
    full: &'a str,
    shift: TableShift,
    stack: Vec<(usize, String)>,
    ctx: &'a mut Ctx,
    /// How many list nesting levels the enclosing item scans already opened.
    /// Bounds `finish_item -> parse -> parse_list -> finish_item` recursion.
    list_depth: usize,
}

/// Content-addressed block id: `b-` + first 8 hex of the SHA-256 of the
/// block's exact source text, with an occurrence suffix on repeats.
fn block_id(ctx: &mut Ctx, source_text: &str) -> String {
    let digest = Sha256::digest(source_text.as_bytes());
    let mut base = String::with_capacity(10);
    base.push_str("b-");
    for b in &digest[..4] {
        base.push_str(&format!("{b:02x}"));
    }
    let seen = ctx.id_counts.entry(source_text.to_string()).or_insert(0);
    *seen += 1;
    if *seen == 1 {
        base
    } else {
        format!("{base}-{}", *seen)
    }
}

/// Plain text of an inline run (used for heading-path entries).
fn inline_plain_text(inlines: &[Inline]) -> String {
    let mut out = String::new();
    for i in inlines {
        match i {
            Inline::Text(s) => out.push_str(s),
            Inline::Code(s) => out.push_str(s),
            Inline::Strong(inner) | Inline::Emphasis(inner) => {
                out.push_str(&inline_plain_text(inner))
            }
            Inline::Link { text, .. } => out.push_str(&inline_plain_text(text)),
            Inline::Image { alt, .. } => out.push_str(alt),
            Inline::InlineHtml(_) => {}
        }
    }
    out
}

fn heading_path_of(stack: &[(usize, String)]) -> Vec<String> {
    stack.iter().map(|(_, t)| t.clone()).collect()
}

/// Recursive block scan over a line slice.
///
/// `lines/starts/ends` are parallel tables for the slice; `starts/ends`
/// already point at full-file byte coordinates.
fn parse_spanned_lines(
    lines: &[&str],
    starts: &[usize],
    ends: &[usize],
    scan: &mut Scan<'_>,
) -> Vec<SpannedBlock> {
    let mut blocks = Vec::new();
    let mut i = 0usize;
    while i < lines.len() {
        let line = lines[i];
        if line.trim().is_empty() {
            i += 1;
            continue;
        }
        let (block, next): (Block, usize) = if let Some(pair) = parse_fenced_code(lines, i) {
            pair
        } else if let Some(pair) = parse_atx_heading(line, i, &mut scan.stack) {
            pair
        } else if is_thematic_break(line) {
            (Block::ThematicBreak, i + 1)
        } else if let Some(pair) = parse_center_container(lines, starts, ends, i, scan) {
            pair
        } else if let Some(pair) = parse_html_block(lines, i) {
            pair
        } else if let Some(pair) = parse_blockquote(lines, starts, ends, i, scan) {
            pair
        } else if let Some(pair) = parse_table(lines, i) {
            pair
        } else if let Some(pair) = parse_list(lines, i, scan.list_depth) {
            pair
        } else {
            parse_paragraph(lines, i)
        };
        let span = scan.shift.span(starts, ends, i, next);
        let source_text = &scan.full[span.start_byte..span.end_byte];
        let id = block_id(scan.ctx, source_text);
        blocks.push(SpannedBlock {
            block,
            span,
            id,
            heading_path: heading_path_of(&scan.stack),
        });
        // Never wedge the block loop: a line that starts_block() rejects as
        // paragraph content while no detector claims it (e.g. '#604' — a
        // hash glued to text is not an ATX heading) used to leave
        // `next == i`, spinning here forever and growing `blocks` unbounded
        // (the 2026-10 wowsp docs outage, where every site deploy died on a
        // runner shutdown signal).
        i = next.max(i + 1);
    }
    blocks
}

// ----------------------------------------------------------------------------
// Block detectors
// ----------------------------------------------------------------------------

fn parse_fenced_code(lines: &[&str], i: usize) -> Option<(Block, usize)> {
    let trimmed = lines[i].trim_start();
    let (fence_char, n) = leading_fence(trimmed)?;
    let info = trimmed[n..].trim();
    let mut code = String::new();
    let mut j = i + 1;
    while j < lines.len() {
        let t = lines[j].trim_start();
        if let Some((c, m)) = leading_fence(t) {
            if c == fence_char && m >= n {
                if let Some(block) = route_special_fence(info, &code) {
                    return Some((block, j + 1));
                }
                let lang = if info.is_empty() {
                    None
                } else {
                    Some(info.to_string())
                };
                return Some((Block::CodeBlock { lang, code }, j + 1));
            }
        }
        code.push_str(lines[j]);
        code.push('\n');
        j += 1;
    }
    // Unterminated fence — take everything to EOF.
    if let Some(block) = route_special_fence(info, &code) {
        return Some((block, j));
    }
    let lang = if info.is_empty() {
        None
    } else {
        Some(info.to_string())
    };
    Some((Block::CodeBlock { lang, code }, j))
}

/// Route fences whose info string marks them as something other than plain
/// code: ```` ```hikari ```` (live component compiled at build time) and
/// ```` ```mermaid ```` / ```` ```math ```` (client-side rendered diagrams).
fn route_special_fence(info: &str, code: &str) -> Option<Block> {
    let source = || code.trim_end().to_string();
    match info {
        "hikari" => Some(Block::LiveComponent {
            source: source(),
            lang: None,
        }),
        s if s.starts_with("hikari:") => {
            let lang = s.strip_prefix("hikari:").unwrap().to_string();
            Some(Block::LiveComponent {
                source: source(),
                lang: Some(lang),
            })
        }
        "mermaid" => Some(Block::Diagram {
            kind: crate::markdown::ast::DiagramKind::Mermaid,
            source: source(),
        }),
        "math" | "latex" | "katex" => Some(Block::Diagram {
            kind: crate::markdown::ast::DiagramKind::Math,
            source: source(),
        }),
        _ => None,
    }
}

fn leading_fence(s: &str) -> Option<(char, usize)> {
    let c = s.chars().next()?;
    if c != '`' && c != '~' {
        return None;
    }
    let n = s.chars().take_while(|&ch| ch == c).count();
    if n >= 3 {
        Some((c, n))
    } else {
        None
    }
}

/// Level of a valid ATX heading opener: 1-6 '#' immediately followed by a
/// space, a tab, or end-of-line. A hash run glued to other text ('#604')
/// is not a heading — CommonMark keeps such a line as paragraph content.
fn atx_level(t: &str) -> Option<usize> {
    let hashes = t.chars().take_while(|&c| c == '#').count();
    if hashes == 0 || hashes > 6 {
        return None;
    }
    match t[hashes..].chars().next() {
        None | Some(' ') | Some('\t') => Some(hashes),
        _ => None,
    }
}

/// Parse an ATX heading line and fold it into the heading stack: all stack
/// entries at the same or deeper level are popped, then this heading is
/// pushed, so the block's heading path always reads outermost → innermost.
fn parse_atx_heading(
    line: &str,
    i: usize,
    stack: &mut Vec<(usize, String)>,
) -> Option<(Block, usize)> {
    let trimmed = line.trim_start();
    let hashes = atx_level(trimmed)?;
    let rest = &trimmed[hashes..];
    let text = parse_inline(rest.trim());
    let plain = inline_plain_text(&text);
    while stack.last().is_some_and(|(lvl, _)| *lvl >= hashes) {
        stack.pop();
    }
    stack.push((hashes, plain));
    Some((
        Block::Heading {
            level: hashes as u8,
            text,
        },
        i + 1,
    ))
}

fn is_thematic_break(line: &str) -> bool {
    let t = line.trim();
    if t.is_empty() {
        return false;
    }
    let first = t.chars().next().unwrap();
    if first != '-' && first != '*' && first != '_' {
        return false;
    }
    t.chars().all(|c| c == first || c == ' ' || c == '\t')
        && t.chars().filter(|&c| c == first).count() >= 3
}

/// Detect a raw HTML block.
///
/// Two shapes are recognised (enough for the READMEs in this ecosystem, which
/// use block-level HTML for centering):
///
/// 1. **Single-line, self-closed HTML** — a line whose trimmed form opens and
///    closes the same element, e.g. `<p align="center"><img …/></p>`,
///    `<h1 align="center">Name</h1>`. The line is captured verbatim.
/// 2. **Multi-line HTML run** — consecutive non-blank lines starting with `<`
///    (e.g. a raw `<img …/>` on its own line), captured together until a blank
///    line.
///
/// Blank lines always terminate a run, so `<div>` … blank … markdown … blank …
/// `</div>` becomes three separate blocks (the inner markdown is parsed as
/// normal, which is the GitHub-compatible behaviour the READMEs rely on).
fn parse_html_block(lines: &[&str], i: usize) -> Option<(Block, usize)> {
    let trimmed = lines[i].trim_start();
    if !is_html_block_start(trimmed) {
        return None;
    }

    // Shape 1: the opener is fully closed on the same line (`<tag …>…</tag>` or
    // a self-closing `<…/>`). Capture just this line.
    if html_line_is_self_contained(trimmed) {
        return Some((Block::Html(lines[i].to_string()), i + 1));
    }

    // Shape 2: gather a maximal run of consecutive non-blank `<…>`-prefixed
    // lines. The first line is already known to qualify; keep eating while the
    // next line is non-blank and also begins with `<`.
    let mut buf = String::from(lines[i]);
    buf.push('\n');
    let mut j = i + 1;
    while j < lines.len() {
        let l = lines[j];
        let lt = l.trim_start();
        if lt.is_empty() {
            break;
        }
        // Allow continuation lines that are themselves tag lines. A line that
        // does not start with `<` ends the run (it will be parsed as markdown).
        if !lt.starts_with('<') {
            break;
        }
        buf.push_str(l);
        buf.push('\n');
        j += 1;
    }
    Some((Block::Html(buf), j))
}

/// A line begins an HTML block if, after leading whitespace, it starts with `<`
/// immediately followed by an ASCII letter, `</` + letter, or an HTML
/// comment / declaration opener (`<!--`, `<!`, `<?`).
fn is_html_block_start(s: &str) -> bool {
    let bytes = s.as_bytes();
    if bytes.first() != Some(&b'<') {
        return false;
    }
    if bytes.starts_with(b"<!--") || bytes.starts_with(b"<!") || bytes.starts_with(b"<?") {
        return true;
    }
    let mut k = 1;
    if bytes.get(k) == Some(&b'/') {
        k += 1;
    }
    bytes.get(k).is_some_and(|b| b.is_ascii_alphabetic())
}

/// True when a trimmed HTML line opens and closes its root element on the same
/// line (`<x …>…</x>`), or is a self-closing tag (`<x …/>`).
fn html_line_is_self_contained(s: &str) -> bool {
    // Self-closing singleton like `<img …/>`.
    if s.ends_with("/>") {
        return true;
    }
    // `<tag …>…</tag>`: capture the first tag name, then require its close tag.
    let after_open = match s.strip_prefix('<') {
        Some(rest) => rest,
        None => return false,
    };
    let name: String = after_open
        .chars()
        .take_while(|c| c.is_ascii_alphanumeric())
        .collect();
    if name.is_empty() {
        return false;
    }
    let Some(open_end) = after_open.find('>') else {
        return false;
    };
    let close = format!("</{name}>");
    s[open_end + 1..].contains(&close)
}

/// Detect a `<div align="center">` … (inner markdown blocks) … `</div>`
/// container. The inner markdown is parsed recursively and wrapped in
/// [`Block::Center`] so the renderer can centre its children. If no closing
/// `</div>` is found, returns `None` (the line falls through to regular HTML
/// block detection).
fn parse_center_container(
    lines: &[&str],
    starts: &[usize],
    ends: &[usize],
    i: usize,
    scan: &mut Scan<'_>,
) -> Option<(Block, usize)> {
    let trimmed = lines[i].trim_start();
    if !trimmed.starts_with("<div") {
        return None;
    }
    let gt = trimmed.find('>')?;

    let attrs = trimmed[4..gt].trim().to_string();

    // Count nesting depth to handle nested <div> containers.
    let mut depth: i32 = 1;
    let mut j = i + 1;
    while j < lines.len() {
        let lt = lines[j].trim();
        if lt.starts_with("<div") {
            depth += 1;
        } else if lt == "</div>" {
            depth -= 1;
            if depth == 0 {
                break;
            }
        }
        j += 1;
    }
    if j >= lines.len() {
        return None;
    }

    // Inner blocks keep their file coordinates. Byte tables already carry
    // full-file offsets, but the LINE slice starts at the container's first
    // inner line, so the shift must absorb that offset — otherwise every
    // nested block's start_line/end_line is reported relative to the
    // container instead of the file (review S1: a `<div align="center">` on
    // file line 3 reported its child at line 2 instead of 5). The heading
    // stack is cloned so container headings stay local to their subtree.
    let mut inner = Scan {
        full: scan.full,
        shift: TableShift {
            line_shift: scan.shift.line_shift + i + 1,
        },
        stack: scan.stack.clone(),
        ctx: scan.ctx,
        list_depth: scan.list_depth,
    };
    let children = parse_spanned_lines(
        &lines[i + 1..j],
        &starts[i + 1..j],
        &ends[i + 1..j],
        &mut inner,
    );

    if attrs.contains("align=\"center\"") || attrs.contains("align=center") {
        Some((Block::Center(children), j + 1))
    } else {
        Some((Block::Div { attrs, children }, j + 1))
    }
}

fn parse_blockquote(
    lines: &[&str],
    starts: &[usize],
    ends: &[usize],
    i: usize,
    scan: &mut Scan<'_>,
) -> Option<(Block, usize)> {
    if !lines[i].trim_start().starts_with('>') {
        return None;
    }
    // Peel the `>` prefix per line while keeping every inner line's true
    // position in the file: the inner byte tables point at the first byte
    // AFTER the prefix, so inner spans slice the original text correctly.
    let mut inner_lines: Vec<&str> = Vec::new();
    let mut inner_starts: Vec<usize> = Vec::new();
    let mut inner_ends: Vec<usize> = Vec::new();
    let mut j = i;
    while j < lines.len() {
        let t = lines[j].trim_start();
        if let Some(rest) = t.strip_prefix('>') {
            let rest = rest.strip_prefix(' ').unwrap_or(rest);
            let prefix_len = lines[j].len() - rest.len();
            inner_lines.push(rest);
            inner_starts.push(starts[j] + prefix_len);
            inner_ends.push(starts[j] + prefix_len + rest.len());
            j += 1;
        } else if !lines[j].trim().is_empty() {
            // lazy continuation
            inner_lines.push(lines[j]);
            inner_starts.push(starts[j]);
            inner_ends.push(ends[j]);
            j += 1;
        } else {
            break;
        }
    }
    // Same line-offset discipline as the div/center container: the peeled
    // inner line array starts at the blockquote's OWN first line (`i`), so
    // the shift absorbs that offset while the byte tables stay full-file.
    let mut inner = Scan {
        full: scan.full,
        shift: TableShift {
            line_shift: scan.shift.line_shift + i,
        },
        stack: scan.stack.clone(),
        ctx: scan.ctx,
        list_depth: scan.list_depth,
    };
    let children = parse_spanned_lines(&inner_lines, &inner_starts, &inner_ends, &mut inner);
    Some((Block::Blockquote(children), j))
}

fn parse_table(lines: &[&str], i: usize) -> Option<(Block, usize)> {
    if i + 1 >= lines.len() {
        return None;
    }
    let header_line = lines[i].trim();
    let sep_line = lines[i + 1].trim();
    if !header_line.contains('|') || !is_table_separator(sep_line) {
        return None;
    }
    let headers = split_row(header_line)
        .iter()
        .map(|c| parse_inline(c))
        .collect();
    let mut rows = Vec::new();
    let mut j = i + 2;
    while j < lines.len() {
        let l = lines[j].trim();
        if l.is_empty() || !l.contains('|') {
            break;
        }
        let row = split_row(l).iter().map(|c| parse_inline(c)).collect();
        rows.push(row);
        j += 1;
    }
    Some((Block::Table { headers, rows }, j))
}

fn is_table_separator(s: &str) -> bool {
    !s.is_empty()
        && s.chars()
            .all(|c| c == '|' || c == '-' || c == ':' || c == ' ' || c == '\t')
        && s.contains('-')
}

fn split_row(line: &str) -> Vec<String> {
    let line = line.trim_matches('|').trim();
    line.split('|').map(|c| c.trim().to_string()).collect()
}

/// A parsed list marker: kind, ordinal, the marker's column, and the item
/// text that follows it.
struct ListMarker {
    ordered: bool,
    /// The item's number (`1` for bullets).
    number: usize,
    /// Column of the marker's first character, in expanded spaces.
    indent: usize,
    /// Column where the item's own content starts (marker + its trailing
    /// space), the width continuation lines get stripped by.
    content_indent: usize,
    /// Item text after the marker.
    text: String,
}

/// One item's raw lines while the list scan is still collecting them.
struct RawItem {
    content_indent: usize,
    lines: Vec<String>,
}

/// How many list levels deep the item re-scan may recurse before deeper
/// markers degrade to text. Real docs nest two or three levels; the cap only
/// exists so pathological input (`"- " * 1000`) cannot overflow the stack.
const MAX_LIST_DEPTH: usize = 8;

/// Parse one list block starting at line `i` (at nesting level `depth`).
///
/// The scan keeps a list together across the shapes docs actually use, none
/// of which the flat "marker lines only" version handled:
///
/// - **loose lists** — a blank line between items does not close the list
///   (closing it restarted `<ol>` numbering at 1 for every item);
/// - **lazy continuation** — a wrapped line at or left of the marker column
///   still continues the open item's paragraph (CommonMark lazy continuation;
///   dropping it truncated every hard-wrapped item mid-sentence);
/// - **nested blocks** — any line indented past the marker column belongs to
///   the open item (its content column only decides how far continuation lines
///   are dedented): child lists keep their hierarchy, and a table / fence /
///   paragraph under an item stays a table / fence / paragraph instead of
///   being spliced into the item's text or pushed out as a sibling;
/// - **explicit start** — the first item's number travels on the block so a
///   list that begins at `3.` renders `<ol start="3">`.
///
/// Each item's collected lines are dedented by its content column and re-parsed
/// by the same block scan, so the item's first paragraph becomes its own
/// inline run and everything else becomes child blocks.
fn parse_list(lines: &[&str], i: usize, depth: usize) -> Option<(Block, usize)> {
    let first = list_item_marker(lines[i])?;
    let ordered = first.ordered;
    let base = first.indent;
    let mut raw: Vec<RawItem> = Vec::new();
    let mut j = i;
    while j < lines.len() {
        let line = lines[j];
        if line.trim().is_empty() {
            // Loose list: a blank line only ends the list when what follows
            // cannot belong to it any more.
            let mut k = j + 1;
            while k < lines.len() && lines[k].trim().is_empty() {
                k += 1;
            }
            if k >= lines.len() || !list_continues(lines[k], base, ordered) {
                break;
            }
            // Keep the break inside the open item so it splits its blocks.
            if let Some(last) = raw.last_mut() {
                last.lines.push(String::new());
            }
            j = k;
            continue;
        }
        if let Some(m) = list_item_marker(line) {
            if m.indent == base && m.ordered == ordered {
                raw.push(RawItem {
                    content_indent: m.content_indent,
                    lines: vec![m.text],
                });
                j += 1;
                continue;
            }
            if m.indent > base && !raw.is_empty() {
                let item = raw.last_mut().expect("raw is non-empty");
                if depth + 1 < MAX_LIST_DEPTH {
                    item.lines.push(strip_indent(line, item.content_indent));
                } else {
                    // Past the nesting cap: keep the marker literal rather
                    // than opening another item re-scan level.
                    item.lines.push(line.trim().to_string());
                }
                j += 1;
                continue;
            }
            // Same column, different kind — a new list block starts here.
            break;
        }
        if !raw.is_empty() && leading_indent(line) > base {
            let item = raw.last_mut().expect("raw is non-empty");
            item.lines.push(strip_indent(line, item.content_indent));
            j += 1;
            continue;
        }
        // Lazy continuation: a wrapped line at the marker column (or left of
        // it) continues the open item's paragraph. Only a block opener ends
        // the list here — the old flat parser had this branch and removing it
        // truncated hard-wrapped items into stray paragraphs.
        if !raw.is_empty() && !starts_block(line) {
            let item = raw.last_mut().expect("raw is non-empty");
            item.lines.push(line.trim().to_string());
            j += 1;
            continue;
        }
        break;
    }
    if raw.is_empty() {
        return None;
    }
    let items: Vec<ListItem> = raw
        .into_iter()
        .map(|item| finish_item(item, depth))
        .collect();
    Some((
        Block::List {
            ordered,
            start: if ordered { first.number } else { 1 },
            items,
        },
        j,
    ))
}

/// Turn one item's dedented lines into its inline run plus child blocks.
fn finish_item(item: RawItem, depth: usize) -> ListItem {
    let mut lines = item.lines;
    while lines.last().map(|l| l.trim().is_empty()).unwrap_or(false) {
        lines.pop();
    }
    if lines.is_empty() {
        return ListItem {
            inlines: Vec::new(),
            children: Vec::new(),
        };
    }
    let joined = lines.join("\n");
    // Past the nesting cap, stop re-scanning the item as blocks: the cap is
    // what bounds `finish_item -> parse -> parse_list -> finish_item` on
    // pathological input (`"- " * 2000` on one line nests once per re-scan).
    // Real docs nest two or three levels, so only absurd input reaches here.
    if depth >= MAX_LIST_DEPTH {
        return ListItem {
            inlines: parse_inline(&joined),
            children: Vec::new(),
        };
    }
    let mut blocks = parse_with_depth(&joined, depth + 1);
    // The item's own text is the leading paragraph; rendering it unwrapped
    // keeps a tight `<li>text</li>` instead of `<li><p>text</p></li>`.
    let inlines = match blocks.first() {
        Some(Block::Paragraph(_)) => match blocks.remove(0) {
            Block::Paragraph(inlines) => inlines,
            _ => unreachable!("checked above"),
        },
        _ => Vec::new(),
    };
    ListItem {
        inlines,
        children: blocks,
    }
}

/// Does `line` belong to the list open at column `base` after a blank line?
///
/// A sibling marker continues it only when the kind matches; a deeper marker
/// or an indented line belongs to the open item. Anything else ends the list.
fn list_continues(line: &str, base: usize, ordered: bool) -> bool {
    match list_item_marker(line) {
        Some(m) if m.indent == base => m.ordered == ordered,
        Some(m) => m.indent > base,
        None => leading_indent(line) > base,
    }
}

/// Leading whitespace width in expanded spaces (tab = 4, as CommonMark).
fn leading_indent(line: &str) -> usize {
    line.chars()
        .take_while(|c| *c == ' ' || *c == '\t')
        .map(|c| if c == '\t' { 4 } else { 1 })
        .sum()
}

/// Strip up to `width` columns of leading whitespace (a tab counts as 4).
fn strip_indent(line: &str, width: usize) -> String {
    let mut removed = 0usize;
    let mut cut = 0usize;
    for (idx, ch) in line.char_indices() {
        if removed >= width {
            break;
        }
        match ch {
            ' ' => removed += 1,
            // A tab wider than the remaining columns stays put: consuming it
            // whole would dedent past the item's content column.
            '\t' if removed + 4 <= width => removed += 4,
            _ => break,
        }
        cut = idx + ch.len_utf8();
    }
    line[cut..].to_string()
}

/// Returns the marker shape when the line begins a list item.
fn list_item_marker(line: &str) -> Option<ListMarker> {
    let indent = leading_indent(line);
    let t = line.trim_start();
    let bytes = t.as_bytes();
    if bytes.is_empty() {
        return None;
    }
    // Unordered: - * +
    if matches!(bytes[0], b'-' | b'*' | b'+') && bytes.get(1) == Some(&b' ') {
        return Some(ListMarker {
            ordered: false,
            number: 1,
            indent,
            content_indent: indent + 2,
            text: t[2..].to_string(),
        });
    }
    // Ordered: digits followed by '.'
    let digits_end = bytes.iter().take_while(|&&b| b.is_ascii_digit()).count();
    // CommonMark caps an ordered marker at nine digits; a longer run is a
    // paragraph that happens to start with digits, not a list item.
    if (1..=9).contains(&digits_end)
        && bytes.get(digits_end) == Some(&b'.')
        && bytes.get(digits_end + 1) == Some(&b' ')
    {
        let number = t[..digits_end].parse().unwrap_or(1);
        return Some(ListMarker {
            ordered: true,
            number,
            indent,
            content_indent: indent + digits_end + 2,
            text: t[digits_end + 2..].to_string(),
        });
    }
    None
}

fn starts_block(line: &str) -> bool {
    let t = line.trim_start();
    // Only a VALID heading breaks a paragraph/list run: '#604' (hash glued
    // to text) is paragraph content per CommonMark and used to wedge the
    // block loop via the parse_paragraph early-break — see the progress
    // guard in the block loop.
    atx_level(t).is_some() || t.starts_with('>') || t.starts_with("```") || t.starts_with("~~~")
}

fn parse_paragraph(lines: &[&str], i: usize) -> (Block, usize) {
    let mut buf = String::new();
    let mut j = i;
    while j < lines.len() {
        let line = lines[j];
        if line.trim().is_empty() || starts_block(line) || list_item_marker(line).is_some() {
            break;
        }
        if !buf.is_empty() {
            buf.push('\n');
        }
        buf.push_str(line);
        j += 1;
    }
    (Block::Paragraph(parse_inline(&buf)), j)
}

/// Drop the span wrapper at the top level, producing bare blocks. Container
/// children keep their [`SpannedBlock`] wrapper — the container variants
/// hold that type — so nested blocks inside a [`parse`] result still carry
/// their source coordinates; only the top level is unwrapped.
fn strip_spans(blocks: Vec<SpannedBlock>) -> Vec<Block> {
    blocks.into_iter().map(|sb| sb.block).collect()
}

// ----------------------------------------------------------------------------
// Inline parsing (pest)
// ----------------------------------------------------------------------------

fn parse_inline(input: &str) -> Vec<Inline> {
    let mut pairs = match InlineParser::parse(Rule::inline_seq, input) {
        Ok(p) => p,
        Err(_) => return vec![Inline::Text(input.to_string())],
    };
    let Some(seq) = pairs.next() else {
        return vec![Inline::Text(input.to_string())];
    };
    seq.into_inner().map(build_inline).collect()
}

fn build_inline(pair: Pair<Rule>) -> Inline {
    // `pair` is a `span`; its first inner child is the concrete rule.
    let span_text = pair.as_str().to_string();
    let Some(inner) = pair.into_inner().next() else {
        return Inline::Text(span_text);
    };
    match inner.as_rule() {
        Rule::badge_link => {
            // `[![alt](img-url)](link-url)` -> a link wrapping an image.
            // The `alt` group is anonymous, so peel it out of the full match;
            // the two `url` captures come through as the only inner pairs.
            let full = inner.as_str();
            let alt = full
                .strip_prefix("[![")
                .and_then(|rest| rest.split_once("]("))
                .map(|(alt, _)| alt.to_string())
                .unwrap_or_default();
            let urls: Vec<String> = inner.into_inner().map(|p| p.as_str().to_string()).collect();
            let img_url = urls.first().cloned().unwrap_or_default();
            let link_url = urls.get(1).cloned().unwrap_or_default();
            Inline::Link {
                text: vec![Inline::Image { alt, url: img_url }],
                url: link_url,
            }
        }
        Rule::image => {
            let kids: Vec<_> = inner.into_inner().collect();
            let alt = kids
                .first()
                .map(|p| strip_delim(p.as_str(), '[', ']'))
                .unwrap_or_default();
            let url = kids
                .get(1)
                .map(|p| p.as_str().to_string())
                .unwrap_or_default();
            Inline::Image { alt, url }
        }
        Rule::link => {
            let kids: Vec<_> = inner.into_inner().collect();
            let label = kids
                .first()
                .map(|p| strip_delim(p.as_str(), '[', ']'))
                .unwrap_or_default();
            let url = kids
                .get(1)
                .map(|p| p.as_str().to_string())
                .unwrap_or_default();
            Inline::Link {
                text: parse_inline(&label),
                url,
            }
        }
        Rule::code_span => Inline::Code(strip_delim(inner.as_str(), '`', '`')),
        Rule::strong => Inline::Strong(inner.into_inner().map(build_inline).collect()),
        Rule::emphasis => Inline::Emphasis(inner.into_inner().map(build_inline).collect()),
        Rule::inline_html => Inline::InlineHtml(inner.as_str().to_string()),
        Rule::entity => Inline::Text(decode_entity(inner.as_str())),
        Rule::raw_double_atom | Rule::raw_single_atom => Inline::Text(inner.as_str().to_string()),
        Rule::escape => {
            let ch = inner
                .as_str()
                .chars()
                .nth(1)
                .map(|c| c.to_string())
                .unwrap_or_default();
            Inline::Text(ch)
        }
        Rule::raw => Inline::Text(inner.as_str().to_string()),
        _ => Inline::Text(inner.as_str().to_string()),
    }
}

/// Strip a single leading `open` and trailing `close` delimiter, if present.
fn strip_delim(s: &str, open: char, close: char) -> String {
    let s = s.strip_prefix(open).unwrap_or(s);
    let s = s.strip_suffix(close).unwrap_or(s);
    s.to_string()
}

/// Decode an HTML character reference (`&nbsp;`, `&#160;`, `&#xA0;`) to its
/// Unicode character, mirroring CommonMark entity handling: the character
/// lands in the text run, so the HTML layer's normal escaping keeps `&amp;`
/// and friends correct. Numeric references are total; named references cover
/// the common Latin-1 / punctuation set — anything unknown is passed through
/// literally (which is also how browsers render unknown entities).
fn decode_entity(s: &str) -> String {
    let body = &s[1..s.len() - 1]; // strip leading `&` and trailing `;`
    if let Some(num) = body.strip_prefix('#') {
        let code = if let Some(hex) = num.strip_prefix(['x', 'X']) {
            u32::from_str_radix(hex, 16).ok()
        } else {
            num.parse::<u32>().ok()
        };
        return code
            .and_then(char::from_u32)
            .map(|c| c.to_string())
            .unwrap_or_else(|| s.to_string());
    }
    let ch = match body {
        // XML-predefined + quoting.
        "amp" => '&',
        "lt" => '<',
        "gt" => '>',
        "quot" => '"',
        "apos" => '\'',
        // Spaces.
        "nbsp" => '\u{00A0}',
        "ensp" => '\u{2002}',
        "emsp" => '\u{2003}',
        "thinsp" => '\u{2009}',
        // Punctuation & symbols common in prose.
        "middot" => '·',
        "bull" => '•',
        "hellip" => '…',
        "mdash" => '—',
        "ndash" => '–',
        "lsquo" => '‘',
        "rsquo" => '’',
        "ldquo" => '“',
        "rdquo" => '”',
        "sbquo" => '‚',
        "bdquo" => '„',
        "dagger" => '†',
        "Dagger" => '‡',
        "permil" => '‰',
        "prime" => '′',
        "Prime" => '″',
        "lsaquo" => '‹',
        "rsaquo" => '›',
        "laquo" => '«',
        "raquo" => '»',
        // Latin-1 symbols & currency.
        "copy" => '©',
        "reg" => '®',
        "trade" => '™',
        "deg" => '°',
        "plusmn" => '±',
        "times" => '×',
        "divide" => '÷',
        "micro" => 'µ',
        "para" => '',
        "sect" => '§',
        "pound" => '£',
        "yen" => '¥',
        "euro" => '€',
        "cent" => '¢',
        "curren" => '¤',
        "brvbar" => '¦',
        "ordf" => 'ª',
        "ordm" => 'º',
        "not" => '¬',
        "shy" => '\u{00AD}',
        "macr" => '¯',
        "acute" => '´',
        "cedil" => '¸',
        "uml" => '¨',
        "sup1" => '¹',
        "sup2" => '²',
        "sup3" => '³',
        "frac14" => '¼',
        "frac12" => '½',
        "frac34" => '¾',
        "iexcl" => '¡',
        "iquest" => '¿',
        _ => return s.to_string(),
    };
    ch.to_string()
}

#[cfg(test)]
mod span_tests {
    use super::*;

    #[test]
    fn spans_cover_full_file_coordinates() {
        let src = "# Title\n\nIntro paragraph.\n\n```rust\ncode\n```\n";
        let blocks = parse_doc(src);
        assert_eq!(blocks.len(), 3);
        // Heading: line 1, bytes 0..7 ("# Title").
        assert_eq!(blocks[0].span.start_line, 1);
        assert_eq!(blocks[0].span.end_line, 1);
        assert_eq!(
            &src[blocks[0].span.start_byte..blocks[0].span.end_byte],
            "# Title"
        );
        // Paragraph: line 3.
        assert_eq!(blocks[1].span.start_line, 3);
        assert_eq!(
            &src[blocks[1].span.start_byte..blocks[1].span.end_byte],
            "Intro paragraph."
        );
        // Fenced code: lines 5..=7, includes both fence lines.
        assert_eq!(blocks[2].span.start_line, 5);
        assert_eq!(blocks[2].span.end_line, 7);
        assert!(src[blocks[2].span.start_byte..blocks[2].span.end_byte].starts_with("```rust"));
    }

    #[test]
    fn frontmatter_offsets_are_compensated() {
        let src = "---\ntitle: T\n---\n# Body Heading\n\ntext\n";
        let blocks = parse_doc(src);
        assert_eq!(blocks.len(), 2);
        // "# Body Heading" is file line 4; byte offset right after the fence.
        assert_eq!(blocks[0].span.start_line, 4);
        assert_eq!(
            &src[blocks[0].span.start_byte..blocks[0].span.end_byte],
            "# Body Heading"
        );
        assert_eq!(blocks[1].span.start_line, 6);
    }

    #[test]
    fn heading_paths_follow_the_stack() {
        let src = "# A\n\ntext\n\n## B\n\ntext2\n\n### C\n\nback to ## level\n\n## D\n\ntail\n";
        let blocks = parse_doc(src);
        let paths: Vec<Vec<String>> = blocks.iter().map(|b| b.heading_path.clone()).collect();
        assert_eq!(paths[0], vec!["A"]); // the H1 itself
        assert_eq!(paths[1], vec!["A"]);
        assert_eq!(paths[2], vec!["A", "B"]); // the H2
        assert_eq!(paths[3], vec!["A", "B"]);
        assert_eq!(paths[4], vec!["A", "B", "C"]);
        assert_eq!(paths[5], vec!["A", "B", "C"]); // paragraph inside C's section
        assert_eq!(paths[6], vec!["A", "D"]); // sibling H2 pops the H3
        assert_eq!(paths[7], vec!["A", "D"]);
    }

    #[test]
    fn container_headings_do_not_extend_the_document_stack() {
        let src = "# Top\n\n> ## Quoted\n>\n> quoted text\n\nafter\n";
        let blocks = parse_doc(src);
        let quote = &blocks[1];
        assert!(matches!(quote.block, Block::Blockquote(_)));
        assert_eq!(quote.heading_path, vec!["Top"]);
        let Block::Blockquote(inner) = &quote.block else {
            panic!("expected blockquote");
        };
        // Inner heading sees "Top" + itself locally; the sibling paragraph
        // inside the quote sees Top+Quoted; the paragraph AFTER the quote is
        // back on the plain document stack.
        assert_eq!(inner[0].heading_path, vec!["Top", "Quoted"]);
        assert_eq!(inner[1].heading_path, vec!["Top", "Quoted"]);
        assert_eq!(blocks[2].heading_path, vec!["Top"]);
    }

    #[test]
    fn block_ids_are_content_addressed_and_stable() {
        let src = "# A\n\npara one\n\n## B\n\npara two\n";
        let blocks = parse_doc(src);
        let id_a = &blocks[1].id;
        // Same paragraph in a different document position keeps its id.
        let src2 = "# Z\n\npara one\n";
        let blocks2 = parse_doc(src2);
        assert_eq!(id_a, &blocks2[1].id);
        // Repeated identical blocks disambiguate with an occurrence suffix.
        let dup = parse_doc("dup block\n\ndup block\n");
        assert_ne!(dup[0].id, dup[1].id);
        assert!(dup[1].id.starts_with(&dup[0].id));
    }

    #[test]
    fn nested_container_blocks_carry_their_own_spans() {
        let src = "<div align=\"center\">\n\ninner para\n\n</div>\n\n> quoted\n";
        let blocks = parse_doc(src);
        let Block::Center(children) = &blocks[0].block else {
            panic!("expected center");
        };
        assert_eq!(children.len(), 1);
        assert_eq!(
            &src[children[0].span.start_byte..children[0].span.end_byte],
            "inner para"
        );
        let Block::Blockquote(inner) = &blocks[1].block else {
            panic!("expected blockquote");
        };
        // The quoted span slices the ORIGINAL text including the `>` prefix
        // position — starts after "> " but byte-accurate to the source.
        assert_eq!(
            &src[inner[0].span.start_byte..inner[0].span.end_byte],
            "quoted"
        );
        // LINE coordinates are pinned too: the byte assertions above passed
        // while nested line numbers were systematically offset (review S1),
        // so a span test that only slices bytes cannot catch that class.
        assert_eq!(children[0].span.start_line, 3);
        assert_eq!(children[0].span.end_line, 3);
        assert_eq!(inner[0].span.start_line, 7);
        assert_eq!(inner[0].span.end_line, 7);
    }

    /// Review S1 regression: a container that does NOT start on line 1 used
    /// to report every nested block relative to the container instead of the
    /// file (`<div>` on line 3 reported its child at line 2 instead of 5;
    /// a blockquote on line 5 reported its child at line 1).
    #[test]
    fn nested_blocks_report_file_lines_not_container_relative_lines() {
        let src = "# Title\n\n<div align=\"center\">\n\nchild para\n\n</div>\n\n> quoted here\n";
        let blocks = parse_doc(src);

        let Block::Center(children) = &blocks[1].block else {
            panic!("expected center as second block");
        };
        // Container header sits on line 3; its child paragraph on line 5.
        assert_eq!(blocks[1].span.start_line, 3);
        assert_eq!(children[0].span.start_line, 5);
        assert_eq!(children[0].span.end_line, 5);
        assert_eq!(
            &src[children[0].span.start_byte..children[0].span.end_byte],
            "child para"
        );

        let Block::Blockquote(inner) = &blocks[2].block else {
            panic!("expected blockquote as third block");
        };
        // Blockquote sits on line 9; its inner paragraph shares that line.
        assert_eq!(blocks[2].span.start_line, 9);
        assert_eq!(inner[0].span.start_line, 9);
        assert_eq!(inner[0].span.end_line, 9);
        assert_eq!(
            &src[inner[0].span.start_byte..inner[0].span.end_byte],
            "quoted here"
        );
    }

    #[test]
    fn parse_strips_spans_and_keeps_shape() {
        let src = "# H\n\n> quoted para\n\ntext\n";
        let bare = parse(src);
        assert_eq!(bare.len(), 3);
        assert!(
            matches!(&bare[1], Block::Blockquote(inner) if matches!(inner[0].block, Block::Paragraph(_)))
        );
    }
}

#[cfg(test)]
mod list_tests {
    use super::*;

    fn list_of(blocks: &[Block]) -> (&str, usize, &Vec<ListItem>) {
        match &blocks[0] {
            Block::List {
                ordered,
                start,
                items,
            } => (if *ordered { "ol" } else { "ul" }, *start, items),
            other => panic!("expected a list, got {other:?}"),
        }
    }

    fn item_text(item: &ListItem) -> String {
        item.inlines
            .iter()
            .map(|i| match i {
                Inline::Text(t) => t.clone(),
                _ => String::new(),
            })
            .collect()
    }

    #[test]
    fn blank_lines_between_items_keep_one_list() {
        // The loose-list shape every doc site writes. Closing the list on the
        // blank line emitted one <ol> per item, so the rendered numbering
        // restarted at 1 for each of them.
        let blocks = parse("1. one\n\n2. two\n\n3. three\n");
        assert_eq!(blocks.len(), 1, "list split into blocks: {blocks:?}");
        let (tag, start, items) = list_of(&blocks);
        assert_eq!(tag, "ol");
        assert_eq!(start, 1);
        assert_eq!(items.len(), 3);
        assert_eq!(item_text(&items[2]).trim(), "three");
    }

    #[test]
    fn nested_markers_become_child_lists() {
        let blocks = parse("1. parent\n   - child a\n   - child b\n2. second\n");
        assert_eq!(blocks.len(), 1, "nested list escaped the block: {blocks:?}");
        let (_, _, items) = list_of(&blocks);
        assert_eq!(items.len(), 2, "child items flattened into siblings");
        assert_eq!(item_text(&items[0]).trim(), "parent");
        match &items[0].children[0] {
            Block::List {
                ordered,
                items: kids,
                ..
            } => {
                assert!(!ordered);
                assert_eq!(kids.len(), 2);
                assert_eq!(item_text(&kids[1]).trim(), "child b");
            }
            other => panic!("expected a child list, got {other:?}"),
        }
    }

    #[test]
    fn ordered_list_carries_its_first_number() {
        let blocks = parse("3. three\n4. four\n");
        let (_, start, items) = list_of(&blocks);
        assert_eq!(start, 3, "the start number was dropped");
        assert_eq!(items.len(), 2);
    }

    #[test]
    fn a_different_marker_kind_starts_a_new_block() {
        let blocks = parse("- bullet\n1. ordered\n");
        assert_eq!(blocks.len(), 2, "kinds merged into one list: {blocks:?}");
        assert_eq!(list_of(&blocks[..1]).0, "ul");
        assert_eq!(list_of(&blocks[1..]).0, "ol");
    }

    #[test]
    fn indented_continuation_stays_in_its_item() {
        let blocks = parse("1. first line\n   continued here\n2. second\n");
        let (_, _, items) = list_of(&blocks);
        assert_eq!(items.len(), 2);
        assert!(
            item_text(&items[0]).contains("continued here"),
            "continuation lost: {:?}",
            items[0]
        );
    }

    #[test]
    fn a_plain_paragraph_after_a_blank_line_ends_the_list() {
        let blocks = parse("- bullet\n\nplain paragraph\n");
        assert_eq!(
            blocks.len(),
            2,
            "paragraph swallowed by the list: {blocks:?}"
        );
        assert!(matches!(blocks[1], Block::Paragraph(_)));
    }

    #[test]
    fn a_table_under_an_item_stays_a_table() {
        // shittim-chest's guides indent tables two columns under a bullet.
        // Treating those lines as item text rendered the pipes literally.
        let src = "- lead-in:\n\n  | Base | Where |\n  |---|---|\n  | A | one |\n";
        let blocks = parse(src);
        let (_, _, items) = list_of(&blocks);
        assert_eq!(items[0].children.len(), 1, "table lost: {items:?}");
        assert!(
            matches!(items[0].children[0], Block::Table { .. }),
            "child is not a table: {:?}",
            items[0].children[0]
        );
    }

    #[test]
    fn wrapped_item_text_at_the_margin_stays_in_the_item() {
        // Real docs hard-wrap long items at column 0 (entelecheia's de/es/…
        // parallel-branch-convergence). The old flat parser kept those lines
        // in the item; dropping that branch truncated items mid-sentence and
        // split one list into several.
        let src = "1. Branch deadline — a wall-clock bound per branch; a branch\n   that misses it is folded into the report\nunder reuse of the failing-branch\nsemantics.\n2. Second item.\n";
        let blocks = parse(src);
        assert_eq!(blocks.len(), 1, "list split into blocks: {blocks:?}");
        let (_, _, items) = list_of(&blocks);
        assert_eq!(items.len(), 2, "items lost: {items:?}");
        let text = item_text(&items[0]);
        assert!(
            text.contains("under reuse of the failing-branch"),
            "lazy continuation dropped: {text:?}"
        );
        assert!(
            text.contains("semantics."),
            "continuation tail dropped: {text:?}"
        );
    }

    #[test]
    fn a_nine_digit_ordinal_is_a_marker_and_ten_digits_is_text() {
        let blocks = parse("123456789. nine digits\n");
        assert!(matches!(blocks[0], Block::List { .. }), "{blocks:?}");
        let blocks = parse("1234567890. ten digits\n");
        assert!(
            matches!(blocks[0], Block::Paragraph(_)),
            "over-long ordinal became a list: {blocks:?}"
        );
    }

    #[test]
    fn tab_indented_nesting_keeps_its_depth() {
        // A tab is four columns: `- a` + "\t- b" nests one level; the dedent
        // must not eat the tab whole and shift the child's own indentation.
        let src = "- parent\n\t- child\n";
        let blocks = parse(src);
        let (_, _, items) = list_of(&blocks);
        assert_eq!(
            items.len(),
            1,
            "tab-indented child became a sibling: {items:?}"
        );
        assert!(
            matches!(items[0].children.first(), Some(Block::List { .. })),
            "tab-indented nesting lost: {:?}",
            items[0].children
        );
    }

    #[test]
    fn absurd_nesting_depth_degrades_instead_of_overflowing() {
        // 2000 nested markers used to recurse through finish_item -> parse ->
        // parse_list -> finish_item until the stack died (a build-killing
        // abort, reachable from MCP writes because builds run in-process).
        let src: String = std::iter::repeat_n("- ", 2000).collect::<String>() + "x\n";
        let blocks = parse(&src);
        assert!(!blocks.is_empty(), "deep nesting produced nothing");
    }

    #[test]
    fn a_fence_under_an_item_stays_code() {
        let src = "1. run this:\n\n   ```rust\n   let x = 1;\n   ```\n";
        let blocks = parse(src);
        let (_, _, items) = list_of(&blocks);
        assert!(
            matches!(
                items[0].children.first(),
                Some(Block::CodeBlock { lang, .. }) if lang.as_deref() == Some("rust")
            ),
            "fence lost: {items:?}"
        );
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn badge_link_is_a_link_wrapping_an_image() {
        let blocks = parse("text [![License](badge.svg)](./LICENSE) tail");
        let Block::Paragraph(inlines) = &blocks[0] else {
            panic!("expected a paragraph, got {:?}", blocks);
        };
        // Find the link span.
        let link = inlines
            .iter()
            .find_map(|i| match i {
                Inline::Link { text, url } => Some((text, url)),
                _ => None,
            })
            .expect("a badge link");
        assert_eq!(link.1, "./LICENSE");
        assert!(
            text_contains_image(link.0, "License", "badge.svg"),
            "expected an image span inside the link, got {:?}",
            link.0
        );
    }

    #[test]
    fn raw_html_block_passes_through_verbatim() {
        let blocks = parse("<h1 align=\"center\">Lagrange</h1>\n\nparagraph");
        assert_eq!(blocks.len(), 2);
        let Block::Html(raw) = &blocks[0] else {
            panic!("expected an Html block, got {:?}", blocks[0]);
        };
        assert!(raw.contains("<h1 align=\"center\">Lagrange</h1>"));
        assert!(matches!(blocks[1], Block::Paragraph(_)));
    }

    #[test]
    fn self_closing_html_is_a_single_line_block() {
        let blocks = parse("<p align=\"center\"><img src=\"logo.webp\" /></p>");
        assert!(
            matches!(&blocks[..], [Block::Html(_)]),
            "expected a single Html block, got {:?}",
            blocks
        );
    }

    #[test]
    fn gfm_table_row_with_many_bold_cells_does_not_explode() {
        // A run full of `**bold**` spans (as inside GFM table cells) used to
        // send the recursive emphasis/strong grammar into exponential
        // backtracking. It must now parse in bounded time and surface every
        // bold run. (Without a separator line this is a paragraph, not a
        // table — that is fine; we only care about the bold spans.)
        let row = "| **L2** coord | **2a** peers | **2b** lease | **fork** |";
        let blocks = parse(row);
        let Block::Paragraph(inlines) = &blocks[0] else {
            panic!("expected a Paragraph, got {:?}", blocks);
        };
        let bold_count = inlines
            .iter()
            .filter(|i| matches!(i, Inline::Strong(_)))
            .count();
        assert_eq!(bold_count, 4, "inlines: {:?}", inlines);
    }

    #[test]
    fn underscores_are_not_emphasis() {
        // `snake_case` / `my_var` identifiers must stay literal — `_` is not an
        // emphasis delimiter (only `*` is).
        let blocks = parse("see my_var and snake_case_name here");
        let Block::Paragraph(inlines) = &blocks[0] else {
            panic!("expected a Paragraph, got {:?}", blocks);
        };
        assert!(
            inlines.iter().all(|i| matches!(i, Inline::Text(_))),
            "underscores leaked into emphasis: {:?}",
            inlines
        );
        // The text is reconstructed verbatim.
        let joined: String = inlines
            .iter()
            .map(|i| match i {
                Inline::Text(s) => s.clone(),
                _ => String::new(),
            })
            .collect();
        assert_eq!(joined, "see my_var and snake_case_name here");
    }

    #[test]
    fn asterisk_emphasis_still_works() {
        let blocks = parse("a *italic* and **bold** z");
        let Block::Paragraph(inlines) = &blocks[0] else {
            panic!("expected a Paragraph, got {:?}", blocks);
        };
        assert!(inlines.iter().any(|i| matches!(i, Inline::Emphasis(_))));
        assert!(inlines.iter().any(|i| matches!(i, Inline::Strong(_))));
    }

    fn joined_text(inlines: &[Inline]) -> String {
        inlines
            .iter()
            .map(|i| match i {
                Inline::Text(s) => s.clone(),
                Inline::Strong(inner) | Inline::Emphasis(inner) => joined_text(inner),
                _ => String::new(),
            })
            .collect()
    }

    #[test]
    fn named_entities_decode_to_text() {
        let blocks = parse("GitHub &nbsp;·&nbsp; Docs &amp; more &mdash; done");
        let Block::Paragraph(inlines) = &blocks[0] else {
            panic!("expected a Paragraph, got {:?}", blocks[0]);
        };
        assert_eq!(
            joined_text(inlines),
            "GitHub \u{00A0}·\u{00A0} Docs & more — done"
        );
    }

    #[test]
    fn numeric_entities_decode_to_text() {
        let blocks = parse("&#65;&#x42;&amp;#63;");
        let Block::Paragraph(inlines) = &blocks[0] else {
            panic!("expected a Paragraph, got {:?}", blocks[0]);
        };
        // &#65; → A, &#x42; → B, &amp; → & then a literal #63;
        assert_eq!(joined_text(inlines), "AB&#63;");
    }

    #[test]
    fn unknown_or_invalid_entities_pass_through_literally() {
        let blocks = parse("a &nosuchentity; b &#xD800; c &dangling");
        let Block::Paragraph(inlines) = &blocks[0] else {
            panic!("expected a Paragraph, got {:?}", blocks[0]);
        };
        assert_eq!(
            joined_text(inlines),
            "a &nosuchentity; b &#xD800; c &dangling"
        );
    }

    #[test]
    fn entities_work_inside_emphasis() {
        let blocks = parse("**a &nbsp; b**");
        let Block::Paragraph(inlines) = &blocks[0] else {
            panic!("expected a Paragraph, got {:?}", blocks[0]);
        };
        assert_eq!(joined_text(inlines), "a \u{00A0} b");
    }

    #[test]
    fn hash_glued_to_text_is_paragraph_content_not_a_wedge() {
        // A soft-wrapped line starting with '#604' (an issue reference, no
        // space after the hash) is not an ATX heading. It used to break
        // parse_paragraph on its own line while no detector consumed it,
        // wedging the block loop in an unbounded spin (the 2026-10 wowsp
        // docs outage). It must parse in bounded time and stay merged into
        // the surrounding paragraph, per CommonMark lazy continuation.
        let blocks = parse("intro line\n#604). tail text\n\nnext paragraph");
        assert_eq!(blocks.len(), 2);
        let Block::Paragraph(inlines) = &blocks[0] else {
            panic!("expected a Paragraph, got {:?}", blocks[0]);
        };
        let text = joined_text(inlines);
        assert!(text.contains("intro line"), "inlines: {:?}", inlines);
        assert!(text.contains("#604)."), "inlines: {:?}", inlines);
        assert!(matches!(blocks[1], Block::Paragraph(_)));
    }

    #[test]
    fn hash_glued_to_text_alone_still_parses() {
        let blocks = parse("#604");
        assert!(
            matches!(&blocks[..], [Block::Paragraph(_)]),
            "expected one Paragraph, got {:?}",
            blocks
        );
    }

    fn text_contains_image(inlines: &[Inline], alt: &str, url_part: &str) -> bool {
        inlines.iter().any(|i| match i {
            Inline::Image { alt: a, url } => a == alt && url.contains(url_part),
            Inline::Strong(inner) | Inline::Emphasis(inner) => {
                text_contains_image(inner, alt, url_part)
            }
            _ => false,
        })
    }
}