quillmark-typst 0.94.0

Typst backend for Quillmark
Documentation
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
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
//! Content → Typst-markup emitter that records a per-segment source map.
//!
//! The codegen tier of the richtext seam (Option A): the one place a source map
//! can be produced, because it is the only place that both lowers the content and
//! knows the resulting byte layout. It walks a
//! [`Content`](quillmark_content::Content) to Typst markup — via
//! [`escape_markup`](crate::emit::escape_markup) /
//! [`escape_string`](crate::emit::escape_string), never re-parsing markdown — and
//! records, per segment, the generated byte window plus one `(content ↔ gen)`
//! pair per text run. This is the **only** markup-producing path in the render
//! engine; no code parses markdown at render time.
//!
//! ## Grammar (one intentional divergence)
//!
//! - **Segment.** A maximal run of lines joined by
//!   [`Line::continues`](quillmark_content::model::Line::continues) — one
//!   paragraph, one heading, one whole code fence, one island line. A region
//!   keys on one segment; this is what "paragraph-level" means against the content.
//! - **Blocks.** `Heading{level}` → `=`×`level`; a `continues` paragraph joins its
//!   lines with `#linebreak()`; a code fence buffers its lines into one
//!   `#raw(block: true, lang:, "…")`; a block island renders its slot.
//! - **Marks.** A boundary sweep with open priority `(start, longer-first,
//!   kind-ord)` and close-and-reopen at overlap boundaries (Peritext free overlap
//!   → properly nested Typst). `strong/emph/underline/strike` →
//!   `#strong[`/`#emph[`/`#underline[`/`#strike[`; `link{url}` → `#link("…")[`;
//!   `code` → `#raw("…")`. `anchor`/`unknown` emit nothing.
//! - **Islands.** `table` → `#table(columns:, align:, table.header(…), …)`;
//!   `image` → `#image("url", alt:)`; unknown types emit nothing.
//! - **Block quotes render**, not flatten: `Container::Quote` →
//!   `#quote(block: true)[…]` (a superset behavior, a tested design decision).
//! - **Line-anchored text.** [`escape_markup`](crate::emit::escape_markup)
//!   neutralizes inline markup but is position-blind; Typst's heading `= `, list
//!   `- `/`+ `/`N. `, and term `/ ` are line-anchored — only special as the
//!   first token of a source line. A paragraph (or quote/list-item body) whose
//!   text opens with one lands at column 0 and would render as that block, so
//!   the emitter prefixes a single `\` there (`opens_line_anchor`). Styling-only:
//!   `#`, `[`, `$` are already escaped, so nothing here is a code-execution vector.
//!
//! ## The 2→4 escape coupling
//!
//! Each run records only its `(content, gen)` pair; per-char spans are
//! **recomputed** by a one-scan that treats `//`→`\/\/` as a 2-char/4-byte
//! cluster and every other char as its own. The `escape_tripwire` test pins that
//! scan against [`escape_markup`](crate::emit::escape_markup) /
//! [`escape_string`](crate::emit::escape_string) byte-for-byte, so a future
//! escape-rule change fails loud.

use quillmark_core::error::MAX_NESTING_DEPTH;
use quillmark_content::model::{Container, LineKind, Mark, MarkKind, Content, ISLAND_SLOT};
use std::ops::Range;

/// Escape text for a Typst **markup** context, neutralizing every markup-special
/// character so document text cannot inject markup, layout (`~`), references
/// (`@`), or comments (`//`). Backslash is escaped first so the later insertions
/// are not themselves re-escaped.
pub fn escape_markup(s: &str) -> String {
    s.replace('\\', "\\\\")
        .replace("//", "\\/\\/")
        .replace('~', "\\~") // Non-breaking space in Typst
        .replace('*', "\\*")
        .replace('_', "\\_")
        .replace('`', "\\`")
        .replace('#', "\\#")
        .replace('[', "\\[")
        .replace(']', "\\]")
        .replace('{', "\\{")
        .replace('}', "\\}")
        .replace('$', "\\$")
        .replace('<', "\\<")
        .replace('>', "\\>")
        .replace('@', "\\@")
}

/// Escape text for embedding inside a Typst **string literal** (`"…"`): only `"`
/// and `\` are structural, newlines/tabs get their escape, and other ASCII
/// controls become `\u{..}`.
pub fn escape_string(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '\\' => out.push_str("\\\\"),
            '"' => out.push_str("\\\""),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if c.is_control() => {
                use std::fmt::Write as _;
                let _ = write!(out, "\\u{{{:x}}}", c as u32);
            }
            c => out.push(c),
        }
    }
    out
}

/// Does `s` open a **line-anchored** Typst block — one only special as the first
/// token of a source line? Heading `= ` (one or more `=` then space), bullet
/// `- `, enum `+ ` or `N. ` (ASCII digits then `.` then space), term `/ `. A
/// paragraph whose text starts with one of these, emitted at column 0, would
/// render as that block instead of literal text ([`emit_inline`] escapes it).
/// The trailing space is required — `=foo`, `-5`, `and/or`, `1.item` are inert,
/// so this leaves ordinary prose untouched.
fn opens_line_anchor(s: &str) -> bool {
    let b = s.as_bytes();
    match b.first().copied() {
        Some(b'=') => {
            let n = b.iter().take_while(|&&c| c == b'=').count();
            b.get(n) == Some(&b' ')
        }
        Some(b'-') | Some(b'+') | Some(b'/') => b.get(1) == Some(&b' '),
        Some(c) if c.is_ascii_digit() => {
            let n = b.iter().take_while(|&&c| c.is_ascii_digit()).count();
            b.get(n) == Some(&b'.') && b.get(n + 1) == Some(&b' ')
        }
        _ => false,
    }
}

/// The escape discipline a text run was generated under — the recomputation key
/// for inverting a run's per-char span. `//`→`\/\/` couples 2 content chars to 4
/// generated bytes under **both** disciplines; every other rule differs, so the
/// context picks which scan inverts a run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EscapeCtx {
    /// [`escape_markup`] — Typst markup body (`\*`, `\#`, `\/\/`, …).
    Markup,
    /// [`escape_string`] — inside a `"…"` literal (`\"`, `\\`, `\n`, `\/\/` no-op).
    StringLit,
}

/// One cluster of a generated run: the generated byte span of one content char,
/// except the markup `//`→`\/\/` coupling, which is a single 2-char/4-byte
/// cluster. Reads the escape structure back off the generated text — a lone `\/`
/// only ever arises from that coupling, `\X` escapes are self-delimiting, and
/// `\u{..}` closes on its brace — so a scan needs no stored per-char table and
/// no content text. Returns `(content_chars, byte_len)` for the cluster at byte
/// `i` of `gen`; mirrors [`escape_markup`]/[`escape_string`], kept aligned by
/// the `escape_tripwire` tests.
fn gen_cluster(gen: &str, i: usize, ctx: EscapeCtx) -> (usize, usize) {
    let rest = &gen[i..];
    match ctx {
        EscapeCtx::Markup => {
            // `\/\/` — the `//` coupling: two content chars, four bytes, one cluster.
            if rest.as_bytes().starts_with(br"\/\/") {
                return (2, 4);
            }
            let mut chars = rest.chars();
            let c = chars.next().expect("i is a char boundary within gen");
            if c == '\\' {
                // A `\X` escape: backslash plus one (ASCII, 1-byte) escaped char.
                (1, 1 + chars.next().map(char::len_utf8).unwrap_or(0))
            } else {
                (1, c.len_utf8())
            }
        }
        EscapeCtx::StringLit => {
            let mut chars = rest.chars();
            let c = chars.next().expect("i is a char boundary within gen");
            if c == '\\' {
                match chars.next() {
                    // `\u{..}` control escape — consume through the closing brace.
                    Some('u') => (1, rest.find('}').map(|b| b + 1).unwrap_or(rest.len())),
                    // `\n`/`\r`/`\t`/`\\`/`\"` — two bytes.
                    Some(c2) => (1, 1 + c2.len_utf8()),
                    None => (1, 1),
                }
            } else {
                (1, c.len_utf8())
            }
        }
    }
}

/// Invert a generated byte offset back to a **content** USV offset within one
/// run — cluster floor. `gen` is the run's generated slice, `target` a byte
/// offset into it; the returned USV offset is relative to the run's content
/// start. A `target` inside a multi-byte cluster (an escape, the `//` coupling,
/// a wide UTF-8 char) floors to that cluster's first content char, matching how
/// `glyph.span.1` is computed once per shaped cluster.
///
/// "Cluster" here is the escape/USV cluster, not the Unicode grapheme cluster:
/// the floor is per Unicode scalar value, so a caret can in principle resolve
/// *between* a base character and a following combining mark. This is the
/// model's granularity — the content indexes USV offsets throughout — so the
/// navigation API is USV-exact, not grapheme-exact, by design; consumers place
/// carets on scalar boundaries.
pub(crate) fn invert_gen_offset(gen: &str, ctx: EscapeCtx, target: usize) -> usize {
    let (mut byte, mut content) = (0usize, 0usize);
    while byte < gen.len() {
        let (cc, bl) = gen_cluster(gen, byte, ctx);
        if target < byte + bl {
            return content;
        }
        byte += bl;
        content += cc;
    }
    content
}

/// Forward-map a **content** USV offset within one run to a generated byte
/// offset — the inverse of [`invert_gen_offset`]. `content_off` is relative to
/// the run's content start; the returned byte offset is into `gen`. An offset
/// landing inside the `//` coupling maps past the whole cluster (the coupling
/// is atomic).
pub(crate) fn forward_content_offset(gen: &str, ctx: EscapeCtx, content_off: usize) -> usize {
    let (mut byte, mut content) = (0usize, 0usize);
    while byte < gen.len() {
        if content >= content_off {
            return byte;
        }
        let (cc, bl) = gen_cluster(gen, byte, ctx);
        content += cc;
        byte += bl;
    }
    byte
}

/// One segment's source map: its content range, its generated window, and the
/// per-text-run correspondence between them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SegmentMap {
    /// The segment's range in the content, in USV (Unicode scalar values).
    pub content: Range<usize>,
    /// The segment's window in [`Emission::markup`], in bytes.
    pub gen: Range<usize>,
    /// One `(content USV range, gen byte range, escape context)` per text run —
    /// the plain-text spans between marks/islands/line-breaks. Structural bytes
    /// (delimiters, container syntax, `#linebreak()`) fall between runs and are
    /// covered by [`Self::gen`] but no run.
    pub runs: Vec<(Range<usize>, Range<usize>, EscapeCtx)>,
}

/// The emitter's output: the Typst markup plus its ordered per-segment source map.
#[derive(Debug, Clone)]
pub struct Emission {
    /// The lowered Typst markup.
    pub markup: String,
    /// One entry per emitted segment, in generation order.
    pub segments: Vec<SegmentMap>,
}

/// Emission failures. The content is normally already within
/// [`MAX_NESTING_DEPTH`] (import capped it), so this fires only on a hand-built
/// content that skipped that guard.
#[derive(Debug, thiserror::Error)]
pub enum EmitError {
    /// Container nesting exceeded the maximum allowed.
    #[error("Nesting too deep: {depth} levels (max: {max} levels)")]
    NestingTooDeep {
        /// Actual depth.
        depth: usize,
        /// Maximum allowed.
        max: usize,
    },
}

/// Lower a content to Typst markup and its per-segment source map.
pub fn emit_content(rt: &Content) -> Result<Emission, EmitError> {
    let max_depth = rt
        .lines
        .iter()
        .map(|l| l.containers.len())
        .max()
        .unwrap_or(0);
    if max_depth > MAX_NESTING_DEPTH {
        return Err(EmitError::NestingTooDeep {
            depth: max_depth,
            max: MAX_NESTING_DEPTH,
        });
    }
    let mut e = Emit::new(rt);
    let n = rt.lines.len();
    e.emit_block_level(0..n, 0);
    Ok(Emission {
        markup: e.out,
        segments: e.segments,
    })
}

/// Lower a `richtext(inline)` content — the [`is_inline`] shape: exactly one
/// `Para`, in no container, with no islands — to **pure inline** Typst markup,
/// omitting the block terminator the block walk appends (`\n\n`, a `parbreak()`).
/// So the field composes in an inline slot (`par(..)`, a signature line, a grid
/// cell, `measure`) without emitting Typst's non-fatal "parbreak may not occur
/// inside of a paragraph" warning (#872). The single segment's source map is
/// identical to the block path's — only the trailing separator differs.
///
/// A content that is *not* [`is_inline`] (never produced for an inline field once
/// coercion has run, but reachable from a hand-built content) falls back to block
/// [`emit_content`], so it still renders rather than silently dropping structure.
///
/// [`is_inline`]: quillmark_content::Content::is_inline
pub(crate) fn emit_content_inline(rt: &Content) -> Result<Emission, EmitError> {
    if !rt.is_inline() {
        return emit_content(rt);
    }
    // `is_inline` guarantees one `Para` in no container, so nesting is depth 0 —
    // the depth guard `emit_content` runs is trivially satisfied here. Emit that
    // one segment's inline content and stop: no block terminator, no `parbreak`.
    let mut e = Emit::new(rt);
    e.emit_segment(0..rt.lines.len());
    Ok(Emission {
        markup: e.out,
        segments: e.segments,
    })
}

// ---------------------------------------------------------------------------
// Emitter
// ---------------------------------------------------------------------------

struct Emit<'a> {
    rt: &'a Content,
    /// Content text as USV, so a `[start, end)` USV range slices in O(1).
    chars: Vec<char>,
    /// Per line: its `[start, end)` USV range (text only, excluding the `\n`
    /// separators, which sit at each non-last line's `end`).
    line_usv: Vec<(usize, usize)>,
    /// USV positions of every [`ISLAND_SLOT`] char, ascending — so an island
    /// slot maps to its island index by a binary search, not a content rescan.
    slot_offsets: Vec<usize>,
    out: String,
    segments: Vec<SegmentMap>,
    /// Whether `out` currently ends at a fresh line, tracked so block
    /// separators land consistently.
    end_newline: bool,
}

impl<'a> Emit<'a> {
    fn new(rt: &'a Content) -> Self {
        let chars: Vec<char> = rt.text.chars().collect();
        // Per-line USV `[start, end)` from the shared segmentation — including
        // the malformed-content padding — so the two crates cannot drift.
        let line_usv: Vec<(usize, usize)> = quillmark_content::export::line_segments(rt)
            .iter()
            .map(|s| (s.start, s.end))
            .collect();
        let slot_offsets: Vec<usize> = chars
            .iter()
            .enumerate()
            .filter_map(|(i, &c)| (c == ISLAND_SLOT).then_some(i))
            .collect();
        Emit {
            rt,
            chars,
            line_usv,
            slot_offsets,
            out: String::new(),
            segments: Vec::new(),
            end_newline: true,
        }
    }

    // ---- block-tree walk (terminator model) ----

    /// Emit the sibling blocks in `range`, all sharing the container prefix of
    /// length `depth`. Leaf blocks terminate with `\n\n`; lists and quotes carry
    /// their own whitespace. This is the top-level / in-quote discipline; list
    /// *item* bodies use [`Self::emit_item_body`] instead.
    fn emit_block_level(&mut self, range: Range<usize>, depth: usize) {
        let mut i = range.start;
        while i < range.end {
            if let Some(j) = self.try_emit_container(range.clone(), depth, i) {
                i = j;
                continue;
            }
            let j = self.segment_end(range.clone(), depth, i);
            self.emit_leaf_terminated(i..j);
            i = j;
        }
    }

    /// If the block at `i` opens a list or quote container at `depth`, emit the
    /// whole run and return its end index; return `None` for a leaf, leaving the
    /// caller to emit it under its own discipline (top-level terminated vs list
    /// item body). The container dispatch shared by [`Self::emit_block_level`]
    /// and [`Self::emit_item_body`].
    fn try_emit_container(&mut self, range: Range<usize>, depth: usize, i: usize) -> Option<usize> {
        match self.rt.lines[i].containers.get(depth).cloned() {
            Some(Container::ListItem { ordered, start, .. }) => {
                let j = self.list_run_end(range.clone(), depth, ordered, start, i);
                self.emit_list(i..j, depth, ordered, start);
                Some(j)
            }
            Some(Container::Quote) => {
                let j = self.quote_run_end(range.clone(), depth, i);
                self.emit_quote(i..j, depth);
                Some(j)
            }
            _ => None,
        }
    }

    /// End of the leaf segment starting at `i` at `depth`: `i` plus every
    /// following line at the same depth that continues it (a hard-break run or a
    /// code fence's lines).
    fn segment_end(&self, range: Range<usize>, depth: usize, i: usize) -> usize {
        let mut j = i + 1;
        while j < range.end
            && self.rt.lines[j].containers.len() == depth
            && self.rt.lines[j].continues
        {
            j += 1;
        }
        j
    }

    /// End of the list run starting at `i`: the maximal span of lines whose
    /// container at `depth` is a `ListItem` of the same `(ordered, start)` shape.
    /// Different-shape adjacent lists stay separate (same-shape ones already
    /// merged at import).
    fn list_run_end(
        &self,
        range: Range<usize>,
        depth: usize,
        ordered: bool,
        start: u64,
        i: usize,
    ) -> usize {
        let mut j = i + 1;
        while j < range.end {
            match self.rt.lines[j].containers.get(depth) {
                Some(Container::ListItem {
                    ordered: o,
                    start: s,
                    ..
                }) if *o == ordered && *s == start => j += 1,
                _ => break,
            }
        }
        j
    }

    /// End of the quote run starting at `i`: the maximal span of lines whose
    /// container at `depth` is a `Quote`.
    fn quote_run_end(&self, range: Range<usize>, depth: usize, i: usize) -> usize {
        let mut j = i + 1;
        while j < range.end
            && matches!(
                self.rt.lines[j].containers.get(depth),
                Some(Container::Quote)
            )
        {
            j += 1;
        }
        j
    }

    /// A leaf block terminated with `\n\n`. An empty paragraph emits nothing;
    /// every other block — including an empty heading (`= `) or empty code
    /// fence — still renders.
    fn emit_leaf_terminated(&mut self, range: Range<usize>) {
        let first = &self.rt.lines[range.start];
        let (lo, _) = self.line_usv[range.start];
        let (_, hi) = self.line_usv[range.end - 1];
        if matches!(first.kind, LineKind::Para) && lo == hi {
            return;
        }
        self.emit_segment(range);
        self.out.push_str("\n\n");
        self.end_newline = true;
    }

    /// A list: the Start(List) fresh-line guard, each item, then a
    /// trailing `\n` only when this is the outermost list (no ancestor list item).
    fn emit_list(&mut self, range: Range<usize>, depth: usize, ordered: bool, start: u64) {
        if !self.end_newline {
            self.out.push('\n');
            self.end_newline = true;
        }
        let outermost = !self.rt.lines[range.start].containers[..depth]
            .iter()
            .any(|c| matches!(c, Container::ListItem { .. }));
        let mut k = range.start;
        while k < range.end {
            let key = self.rt.lines[k].containers[depth].clone();
            let mut m = k + 1;
            while m < range.end && self.rt.lines[m].containers.get(depth) == Some(&key) {
                m += 1;
            }
            let ordinal = match &key {
                Container::ListItem { ordinal, .. } => *ordinal,
                _ => 0,
            };
            self.emit_item(k..m, depth, ordered, start, ordinal == 0);
            k = m;
        }
        if outermost {
            self.out.push('\n');
            self.end_newline = true;
        }
    }

    /// One list item: `<indent><marker>` then the item's body, then End(Item)'s
    /// `\n` fresh-line guard. `indent` is `2×depth`; the marker is `- ` (bullet),
    /// the explicit `N. ` on the first item of an ordered list starting off-1, or
    /// `+ ` (Typst auto-numbers `+` from the first item's number).
    fn emit_item(
        &mut self,
        range: Range<usize>,
        depth: usize,
        ordered: bool,
        start: u64,
        first: bool,
    ) {
        let indent = "  ".repeat(depth);
        self.out.push_str(&indent);
        if ordered {
            if first && start != 1 {
                self.out.push_str(&format!("{}. ", start));
            } else {
                self.out.push_str("+ ");
            }
        } else {
            self.out.push_str("- ");
        }
        self.end_newline = false;
        self.emit_item_body(range, depth + 1);
        if !self.end_newline {
            self.out.push('\n');
            self.end_newline = true;
        }
    }

    /// A list item's body at `content_depth` (`= depth+1`): the first block flows
    /// straight off the marker; each later block is preceded by a blank line and
    /// the continuation indent (`2×content_depth`). Nested lists/quotes recurse.
    fn emit_item_body(&mut self, range: Range<usize>, content_depth: usize) {
        let cont_indent = "  ".repeat(content_depth);
        let mut first_block = true;
        let mut i = range.start;
        while i < range.end {
            if let Some(j) = self.try_emit_container(range.clone(), content_depth, i) {
                i = j;
                first_block = false;
                continue;
            }
            let j = self.segment_end(range.clone(), content_depth, i);
            if !first_block {
                // Continuation block: the previous block left one `\n`; this adds
                // a second plus the indent → blank line + indent.
                self.out.push('\n');
                self.out.push_str(&cont_indent);
                self.end_newline = false;
            }
            self.emit_segment(i..j);
            if !self.end_newline {
                self.out.push('\n');
                self.end_newline = true;
            }
            i = j;
            first_block = false;
        }
    }

    /// A block quote: `#quote(block: true)[…]` wrapping the quote's inner
    /// blocks, lowered under the block-level discipline — rendered
    /// structurally, not flattened.
    fn emit_quote(&mut self, range: Range<usize>, depth: usize) {
        if !self.end_newline {
            self.out.push('\n');
        }
        self.out.push_str("#quote(block: true)[\n");
        self.end_newline = true;
        self.emit_block_level(range, depth + 1);
        self.out.push(']');
        self.out.push_str("\n\n");
        self.end_newline = true;
    }

    // ---- segment content (no terminator, no marker) ----

    /// Emit one leaf segment's markup and record its [`SegmentMap`]. Leaves
    /// `end_newline` false — the caller owns the terminator.
    fn emit_segment(&mut self, range: Range<usize>) {
        let kind = self.rt.lines[range.start].kind.clone();
        let (lo, _) = self.line_usv[range.start];
        let (_, hi) = self.line_usv[range.end - 1];
        // A code fence buffers all its lines into one `#raw(...)` and records its
        // own window/runs; the remaining kinds share the record-and-push tail.
        if let LineKind::Code { lang } = &kind {
            self.emit_code(range, lang.as_deref(), lo, hi);
            self.end_newline = false;
            return;
        }
        // Each kind emits its prefix (heading marker, rule glyph, or nothing) and
        // its content runs; `g0` opens the recorded window after any prefix.
        let (g0, runs) = match kind {
            LineKind::Heading { level } => {
                self.out.push_str(&"=".repeat(level as usize));
                self.out.push(' ');
                let g0 = self.out.len();
                (g0, self.emit_inline(lo, hi))
            }
            LineKind::Island | LineKind::Para => {
                let g0 = self.out.len();
                (g0, self.emit_inline(lo, hi))
            }
            LineKind::Rule => {
                let g0 = self.out.len();
                self.out.push_str("#line(length: 100%)");
                (g0, Vec::new())
            }
            LineKind::Code { .. } => unreachable!("code handled by early return"),
        };
        let g1 = self.out.len();
        self.segments.push(SegmentMap {
            content: lo..hi,
            gen: g0..g1,
            runs,
        });
        self.end_newline = false;
    }

    /// A code fence: `#raw(block: true[, lang: "…"], "…")`. Every line's text
    /// rides in the one string literal joined by an escaped `\n`; each line's
    /// content is one `StringLit` run.
    fn emit_code(&mut self, range: Range<usize>, lang: Option<&str>, lo: usize, hi: usize) {
        let g0 = self.out.len();
        self.out.push_str("#raw(block: true");
        if let Some(l) = lang {
            self.out.push_str(", lang: \"");
            self.out.push_str(&escape_string(l));
            self.out.push('"');
        }
        self.out.push_str(", \"");
        let mut runs = Vec::new();
        for (idx, li) in range.clone().enumerate() {
            if idx > 0 {
                // Line separator: an escaped `\n`, structural (outside any run).
                self.out.push_str(&escape_string("\n"));
            }
            let (l0, l1) = self.line_usv[li];
            let content: String = self.chars[l0..l1].iter().collect();
            let rg0 = self.out.len();
            self.out.push_str(&escape_string(&content));
            let rg1 = self.out.len();
            runs.push((l0..l1, rg0..rg1, EscapeCtx::StringLit));
        }
        self.out.push_str("\")");
        let g1 = self.out.len();
        self.segments.push(SegmentMap {
            content: lo..hi,
            gen: g0..g1,
            runs,
        });
    }

    // ---- inline: marks + islands + line breaks, with the source map ----

    /// Emit the inline content of a segment's USV range `[lo, hi)`, returning its
    /// text runs. Wrapping marks nest via a close-and-reopen boundary sweep;
    /// `code` marks render atomically as `#raw("…")`; island slots render their
    /// island; interior `\n`s (continuation breaks) render as `#linebreak()`.
    fn emit_inline(
        &mut self,
        lo: usize,
        hi: usize,
    ) -> Vec<(Range<usize>, Range<usize>, EscapeCtx)> {
        let mut runs = Vec::new();

        // Wrapping marks (nest) and atomic code marks, clipped to [lo, hi) — the
        // same construction cells use, here over the content marks windowed to
        // this segment.
        let (mut wraps, codes) = wraps_and_codes(&self.rt.marks, lo, hi);
        // Atomic code spans can't carry partial styling; clip wraps out of their
        // interiors so overlapping wrap+code lowers to balanced markup.
        clip_wraps_to_codes(&mut wraps, &codes);

        // Sweep the marks with the shared boundary walk, filling a scratch buffer
        // whose bytes land at `base` once appended — so each run's generated span
        // is `base + buf.len()` (absolute into `self.out`). The content callback
        // owns the segment-specific bits: `#linebreak()`, island slots, atomic
        // `#raw(...)` code, and escaped plain runs (recorded).
        let base = self.out.len();
        // Whether this segment's markup opens at column 0 of a generated source
        // line — the only place Typst's line-anchored syntax (heading `= `, list
        // `- `/`+ `/`N. `, term `/ `) is active. True for a paragraph/island
        // (preceded by `\n\n`, or the very first block) and a quote/list-item
        // body's first line (preceded by `[\n`/`\n` + indent); false for heading
        // content (preceded by its `= ` marker) and any run after inline markup.
        let at_col0 = self.out.trim_end_matches([' ', '\t']).ends_with('\n') || self.out.is_empty();
        let mut buf = String::new();
        sweep_marks(lo, hi, &wraps, &mut buf, |buf, pos| {
            let c = self.chars[pos];
            if c == '\n' {
                buf.push_str("#linebreak()");
                return pos + 1;
            }
            if c == ISLAND_SLOT {
                let markup = self.island_markup(pos);
                buf.push_str(&markup);
                return pos + 1;
            }
            if let Some(&(cs, ce)) = codes.iter().find(|(s, _)| *s == pos) {
                let content: String = self.chars[cs..ce].iter().collect();
                buf.push_str("#raw(\"");
                let rg0 = base + buf.len();
                buf.push_str(&escape_string(&content));
                let rg1 = base + buf.len();
                buf.push_str("\")");
                runs.push((cs..ce, rg0..rg1, EscapeCtx::StringLit));
                return ce;
            }
            // Plain text run up to the next boundary.
            let re = next_boundary(pos, hi, &self.chars, &wraps, &codes);
            let content: String = self.chars[pos..re].iter().collect();
            // A run landing at column 0 whose text opens a line-anchored token
            // renders as that block, not literal text. Neutralize with one `\`
            // — a valid escape for every trigger char, verified to render the
            // exact literal — emitted *outside* the run's `gen` window, so
            // `gen == escape_markup(content)` (and the escape-scan) stay exact.
            // `buf.is_empty()` gates to the segment's first content: any wrap
            // (`#strong[`) already opened here would put the token mid-line.
            if at_col0 && buf.is_empty() && opens_line_anchor(&content) {
                buf.push('\\');
            }
            let rg0 = base + buf.len();
            buf.push_str(&escape_markup(&content));
            let rg1 = base + buf.len();
            runs.push((pos..re, rg0..rg1, EscapeCtx::Markup));
            re
        });
        self.out.push_str(&buf);
        runs
    }

    /// The island backing the slot at USV position `pos`, rendered to Typst.
    fn island_markup(&self, pos: usize) -> String {
        let idx = self.slot_offsets.partition_point(|&p| p < pos);
        let Some(isl) = self.rt.islands.get(idx) else {
            return String::new();
        };
        match isl.island_type.as_str() {
            "image" => image_markup(&isl.props),
            "table" => table_markup(&isl.props),
            // Unknown island types emit nothing (parallel to the HTML rule).
            _ => String::new(),
        }
    }
}

/// A wrapping mark clipped to a segment: its span, kind-ord tie-break, and open
/// delimiter (its close is always `]`).
struct Wrap {
    start: usize,
    end: usize,
    ord: u8,
    open: String,
}

fn wrap_open(kind: &MarkKind) -> String {
    match kind {
        MarkKind::Strong => "#strong[".to_string(),
        MarkKind::Emph => "#emph[".to_string(),
        MarkKind::Underline => "#underline[".to_string(),
        MarkKind::Strike => "#strike[".to_string(),
        _ => String::new(),
    }
}

/// Clip wrapping marks so none crosses the interior of an atomic `#raw(...)`
/// code span (`start`→`ce`, `end`→`cs`), then drop any wrap a span swallowed
/// whole. Enforces the #846 balance via the shared
/// [`clip_range_to_atomic`](quillmark_content::export::clip_range_to_atomic) —
/// the same rule this crate's inline emitter and richtext's export both apply,
/// here against code spans only (export also clips against link text).
fn clip_wraps_to_codes(wraps: &mut Vec<Wrap>, codes: &[(usize, usize)]) {
    for w in wraps.iter_mut() {
        quillmark_content::export::clip_range_to_atomic(&mut w.start, &mut w.end, codes);
    }
    wraps.retain(|w| w.start < w.end);
}

/// The mark boundary sweep, shared by prose inline emission and table-cell
/// rendering. Walks `[lo, hi)` opening `wraps` (longer span first, then kind-ord)
/// and closing-and-reopening deeper survivors at overlaps — free overlap →
/// proper nesting. Wrapping delimiters/`]` go to `out`; `emit_run(out, pos)`
/// writes the content at `pos` (plain run, atomic code, island slot, line break)
/// and returns the next position. Records nothing itself — the caller's callback
/// owns any source-map bookkeeping. `wraps` must already be clipped against the
/// code spans ([`clip_wraps_to_codes`]) so no wrap `end` hides inside a span the
/// callback's cursor jumps over.
fn sweep_marks(
    lo: usize,
    hi: usize,
    wraps: &[Wrap],
    out: &mut String,
    mut emit_run: impl FnMut(&mut String, usize) -> usize,
) {
    // Indices into `wraps` for the marks currently open, outermost first. Storing
    // the index (not just `(end, ord)`) keeps each open mark's identity, so a
    // reopened mark re-emits its OWN delimiter: two same-`(ord, end)` links with
    // distinct URLs must not collapse onto whichever mark a bare `(ord, end)`
    // lookup would hit first.
    let mut stack: Vec<usize> = Vec::new();
    let mut pos = lo;
    while pos <= hi {
        // Close every mark ending at `pos`; reopen any deeper survivors that do
        // not (free overlap → proper nesting).
        if let Some(idx) = stack.iter().position(|&wi| wraps[wi].end == pos) {
            let mut reopen: Vec<usize> = Vec::new();
            while stack.len() > idx {
                let wi = stack.pop().unwrap();
                out.push(']');
                if wraps[wi].end != pos {
                    reopen.push(wi);
                }
            }
            for wi in reopen.into_iter().rev() {
                out.push_str(&wraps[wi].open);
                stack.push(wi);
            }
        }
        if pos == hi {
            break;
        }
        // Open marks starting at `pos`: longer span first, then kind-ord.
        let mut opening: Vec<usize> = (0..wraps.len()).filter(|&wi| wraps[wi].start == pos).collect();
        opening.sort_by(|&a, &b| wraps[b].end.cmp(&wraps[a].end).then(wraps[a].ord.cmp(&wraps[b].ord)));
        for wi in opening {
            out.push_str(&wraps[wi].open);
            stack.push(wi);
        }
        pos = emit_run(out, pos);
    }
    // Drain any mark still open when the sweep runs off the end. The codegen
    // embeds this markup in a `#let _qm = [ .. ]` content block that a single
    // unclosed `[` would break — failing the whole helper file's parse, not just
    // this field — so a trailing open must always close. Clipping keeps every
    // wrap `end` reachable, so this normally drains nothing; it is the final
    // stack-drain guard, belt to the clip's braces.
    while stack.pop().is_some() {
        out.push(']');
    }
}

/// The next position after `pos` at which a plain run must stop: any mark
/// start/end, any code start, an interior `\n`, an island slot, or `hi`.
fn next_boundary(
    pos: usize,
    hi: usize,
    chars: &[char],
    wraps: &[Wrap],
    codes: &[(usize, usize)],
) -> usize {
    let mut p = pos + 1;
    while p < hi {
        let c = chars[p];
        if c == '\n' || c == ISLAND_SLOT {
            break;
        }
        if wraps.iter().any(|w| w.start == p || w.end == p) {
            break;
        }
        if codes.iter().any(|(s, _)| *s == p) {
            break;
        }
        p += 1;
    }
    p
}

/// Build the wrapping/atomic marks overlapping the USV window `[lo, hi)`,
/// clamped to it. Shared by the prose inline emitter — which passes the content
/// marks and a segment window — and cell rendering — a flat run, `lo = 0`,
/// `hi = chars.len()`. A mark entirely outside the window is dropped; one
/// straddling it is clipped to the window edges.
fn wraps_and_codes(marks: &[Mark], lo: usize, hi: usize) -> (Vec<Wrap>, Vec<(usize, usize)>) {
    let mut wraps = Vec::new();
    let mut codes = Vec::new();
    for m in marks {
        if m.end <= lo || m.start >= hi {
            continue;
        }
        let s = m.start.max(lo);
        let e = m.end.min(hi);
        if s >= e {
            continue;
        }
        match &m.kind {
            MarkKind::Code => codes.push((s, e)),
            MarkKind::Strong | MarkKind::Emph | MarkKind::Underline | MarkKind::Strike => {
                wraps.push(Wrap {
                    start: s,
                    end: e,
                    ord: m.kind.ord(),
                    open: wrap_open(&m.kind),
                });
            }
            MarkKind::Link { url } => wraps.push(Wrap {
                start: s,
                end: e,
                ord: m.kind.ord(),
                open: format!("#link(\"{}\")[", escape_string(url)),
            }),
            MarkKind::Anchor { .. } | MarkKind::Unknown { .. } => {}
        }
    }
    codes.sort_unstable();
    (wraps, codes)
}

/// Render one table cell's `{text, marks}` to Typst markup via the SAME
/// [`sweep_marks`] walk prose runs use: wrapping marks nest, `code` marks render
/// atomically as `#raw("…")`. A cell is flat inline — no islands, no line breaks
/// — so its markup carries no source-map runs (like other island markup).
fn cell_markup(text: &str, marks: &[Mark]) -> String {
    let chars: Vec<char> = text.chars().collect();
    let (mut wraps, codes) = wraps_and_codes(marks, 0, chars.len());
    clip_wraps_to_codes(&mut wraps, &codes);
    let mut out = String::new();
    sweep_marks(0, chars.len(), &wraps, &mut out, |out, pos| {
        if let Some(&(cs, ce)) = codes.iter().find(|(s, _)| *s == pos) {
            let content: String = chars[cs..ce].iter().collect();
            out.push_str("#raw(\"");
            out.push_str(&escape_string(&content));
            out.push_str("\")");
            return ce;
        }
        let re = next_boundary(pos, chars.len(), &chars, &wraps, &codes);
        let content: String = chars[pos..re].iter().collect();
        out.push_str(&escape_markup(&content));
        re
    });
    out
}

/// `#image("url"[, alt: "…"])` from an image island's props.
fn image_markup(props: &serde_json::Value) -> String {
    let url = props.get("url").and_then(|v| v.as_str()).unwrap_or("");
    let alt = props.get("alt").and_then(|v| v.as_str()).unwrap_or("");
    let mut out = format!("#image(\"{}\"", escape_string(url));
    if !alt.trim().is_empty() {
        out.push_str(&format!(", alt: \"{}\"", escape_string(alt.trim())));
    }
    out.push(')');
    out
}

/// `#table(columns:, align:, table.header(…), …)` from a table island's props,
/// matching the table grammar. Each cell is canonical `{text, marks}`,
/// rendered through the same mark sweep prose runs use ([`cell_markup`]) — so a
/// formatted cell reaches `#strong[…]`/`#emph[…]`/`#raw(…)`/`#link(…)[…]` byte
/// parity with the oracle, no markdown re-parse.
fn table_markup(props: &serde_json::Value) -> String {
    let header = props.get("header").and_then(|v| v.as_array());
    let rows = props.get("rows").and_then(|v| v.as_array());
    let aligns = props.get("aligns").and_then(|v| v.as_array());
    // Column count is the widest row, not just the header: an editor-built table
    // island can carry an empty/short header over wider data rows, and a
    // `columns: 0` would fail to compile.
    let mut cols = header.map(|h| h.len()).unwrap_or(0);
    if let Some(rs) = rows {
        for row in rs {
            if let Some(r) = row.as_array() {
                cols = cols.max(r.len());
            }
        }
    }
    // A zero-column (empty) table has no renderable content and `columns: 0`
    // would fail to compile; emit nothing, matching the markdown export path
    // (`export::emit_table` early-returns on `cols == 0`). An empty table island
    // is well-formed (`Content::validate` accepts it), so this is reachable.
    if cols == 0 {
        return String::new();
    }

    let cell = |v: &serde_json::Value| {
        let (text, marks) = quillmark_content::serial::parse_cell(v);
        cell_markup(&text, &marks)
    };

    let mut out = String::from("#table(\n");
    out.push_str(&format!("  columns: {},\n", cols));
    if let Some(al) = aligns {
        if al
            .iter()
            .any(|a| a.as_str().map(|s| s != "none").unwrap_or(false))
        {
            out.push_str("  align: (");
            for (i, a) in al.iter().enumerate() {
                if i > 0 {
                    out.push_str(", ");
                }
                out.push_str(match a.as_str().unwrap_or("none") {
                    "left" => "left",
                    "center" => "center",
                    "right" => "right",
                    _ => "auto",
                });
            }
            out.push_str("),\n");
        }
    }
    out.push_str("  table.header(");
    if let Some(h) = header {
        for c in h {
            out.push('[');
            out.push_str(&cell(c));
            out.push_str("], ");
        }
    }
    out.push_str("),\n");
    if let Some(rs) = rows {
        for row in rs {
            if let Some(r) = row.as_array() {
                out.push_str("  ");
                for c in r {
                    out.push('[');
                    out.push_str(&cell(c));
                    out.push_str("], ");
                }
                out.push('\n');
            }
        }
    }
    out.push(')');
    out
}

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

    fn emit(md: &str) -> Emission {
        let rt = from_markdown(md).expect("import");
        assert_eq!(rt.validate(), Ok(()), "content invariants for {md:?}");
        emit_content(&rt).expect("emit")
    }

    /// A broad content of markdown inputs exercising every lowering path — the
    /// sample set the source-map alignment test ([`runs_map_content_to_generated_bytes`])
    /// scans. The emitter is the sole lowering path.
    fn sample_inputs() -> Vec<&'static str> {
        vec![
            // headings
            "# Heading 1",
            "## Heading 2",
            "### Heading 3",
            "#### Heading 4",
            "##### Heading 5",
            "###### Heading 6",
            "## Heading with **bold** and _italic_",
            "# Heading with $math$ and #functions",
            "# First\n\n## Second\n\n### Third",
            "# Heading\n\nThis is a paragraph.",
            "## Code example: `fn main()`",
            "#",
            // paragraphs / breaks
            "This is a paragraph.",
            "First paragraph.\n\nSecond paragraph.",
            "Line one  \nLine two",
            "Line one\\\nLine two",
            "a  \nb  \nc",
            "Line one\nLine two",
            "This is some\ntext on multiple\nlines",
            "P1.\n\nP2.\n\nP3.\n\nP4.\n\nP5.",
            // inline formatting
            "This is **bold**, _italic_, and ~~strikethrough~~ text.",
            "**bold**",
            "__bolded__",
            "*italic*",
            "~~strike~~",
            "**bold _and italic_**",
            "**_strong then emph_**",
            "**bold**text",
            "a*sdfasd*f",
            "word**bold**more",
            "*Write y*our paragraphs here.",
            "**a** __b__ **c**",
            "This is <u>underlined</u> text.",
            "pre<u>mid</u>post",
            "<U>upper</U>",
            "before <span class=\"x\">inner</span> after",
            "line1<br>line2",
            // inline code
            "`code`",
            "Text with `inline code` here",
            "`*#$<>`",
            "`` `code` ``",
            // links
            "[Link text](https://example.com)",
            "Visit [our site](https://example.com) for more.",
            "[Link](https://example.com/foo_bar)",
            "[Link](#anchor)",
            "[*bold* link](https://example.com)",
            "[Click 🎉](https://example.com)",
            "Check out https://example.com for more.",
            "// This should not be a comment",
            "Some text // with slashes in the middle",
            // escaping
            "Typst uses * for bold and # for functions.",
            "Use [brackets] and $math$ symbols.",
            "Text {{ content }}",
            "Hello~World",
            "Use path/to/file for the file",
            "Path: C:\\\\Users\\\\file",
            // thematic breaks
            "one\n\n---\n\ntwo",
            "one\n\n***\n\ntwo",
            "one\n\n___\n\ntwo",
            // lists
            "- Item 1\n- Item 2\n- Item 3",
            "1. First\n2. Second\n3. Third",
            "3. Three\n4. Four\n5. Five",
            "0. Zero\n1. One",
            "1. a\n2. b\n\ntext\n\n5. c\n6. d",
            "- Item 1\n- Item 2\n  - Nested item\n- Item 3",
            "- Level 1\n  - Level 2\n    - Level 3",
            "- Bullet item\n\n1. Ordered item\n2. Another ordered",
            "- **Bold** item\n- _Italic_ item\n- `Code` item",
            "- First line.\n\n  Second line.",
            "- Para 1.\n\n  Para 2.\n\n  Para 3.",
            "- Item 1\n\n  More text.\n\n- Item 2",
            "1. First para.\n\n   Second para.\n\n2. Next item.",
            "1. First\n   - Nested bullet\n   - Another bullet\n2. Second",
            "- Item text\n\n  ```\n  code here\n  ```",
            "- First para.\n\n  ```\n  code\n  ```\n\n  After code.",
            // code fences
            "```rust\nfn main() {}\n```",
            "```\nhello\n```",
            "````\n```\nnested\n```\n````",
            "```\n*bold* #heading $math$\n```",
            "    fn main() {}\n    println!()",
            "```rust#evil\ncode\n```",
            "```c++\ncode\n```",
            // images
            "![alt text](path/to/img.png)",
            "![](x.png)",
            "![a *b* `c`](x.png)",
            // tables (plain cells only — formatted cells are a residual)
            "| Name | Age |\n|------|-----|\n| Alice | 30 |\n| Bob | 25 |",
            "| A | B |\n|---|---|\n| 1 | 2 |",
            "| L | C | R |\n|:---|:---:|---:|\n| a | b | c |",
            "| L | D | R |\n|:---|---|---:|\n| a | b | c |",
            "| Name | Value |\n|------|-------|\n",
            "| A | B | C |\n|---|---|---|\n| | | |",
            "| A | B | C |\n|---|---|---|\n| 1 | 2 |",
            "| A | B |\n|---|---|\n| 1 | 2 | 3 |",
            "| H |\n|:--|\n| x |",
            "| L | C | R | D |\n|:---|:---:|---:|---|\n| a | b | c | d |",
            "| A | B | C | D | E | F |\n|---|---|---|---|---|---|\n| 1 | 2 | 3 | 4 | 5 | 6 |",
            "- item1\n- item2\n\n| A |\n|---|\n| 1 |",
            "| Status |\n|--------|\n| ✅ Done |",
            "Before.\n\n| A |\n|---|\n| 1 |\n\nAfter.",
            "# Title\n\n| A |\n|---|\n| 1 |",
            // formatted cells (Option A: cells carry {text, marks}, no re-parse)
            "| Name | Note |\n|------|------|\n| **bold** | _italic_ |",
            "| Func | Desc |\n|------|------|\n| `foo()` | does stuff |",
            "| Site |\n|------|\n| [Example](https://example.com) |",
            "| A |\n|---|\n| ~~deleted~~ |",
            "| A |\n|---|\n| **bold** and _italic_ |",
            "| A |\n|---|\n| <u>underlined</u> |",
            "| A |\n|---|\n| use #tag |",
            "| A |\n|---|\n| a\\|b |",
            "| A |\n|---|\n| $100 @ref ~space {brace} |",
            "| A |\n|---|\n| a // comment |",
            "| A |\n|---|\n| line1<br>line2 |",
            "| Bold | Link |\n|------|------|\n| **b** | [x](https://e.com) |",
            "| Mixed |\n|-------|\n| a **b** `c` [d](https://e.com) ~~e~~ |",
            // mixed
            "A paragraph with **bold** and a [link](https://example.com).\n\nAnother paragraph with `inline code`.\n\n- A list item\n- Another item",
            "# Title\n\nThis is a paragraph with **bold** and *italic* text.\n\n## Section\n\n- List item 1\n- List item 2 with [link](https://example.com)\n\nMore text with `inline code`.",
            // unicode
            "你好世界",
            "**你好** _世界_",
            "Hello 🎉 World 🚀",
            "مرحبا بالعالم",
        ]
    }

    /// Empty / whitespace-only input lowers to empty markup (no paragraph for
    /// empty content).
    #[test]
    fn empty_and_blank_emit_nothing() {
        for md in ["", "   ", "\n\n\n", "   \n   \n   "] {
            assert_eq!(emit(md).markup, "", "for {md:?}");
        }
    }

    // ---- inline lowering (richtext(inline), #872) ----

    /// A `richtext(inline)` content (one `Para`) lowers to pure inline markup —
    /// no trailing `\n\n` (a `parbreak`) — while the block path terminates the
    /// same paragraph with `\n\n`. The inline markup is exactly the paragraph's
    /// content, so it composes in `par(..)` / a grid cell without warning.
    #[test]
    fn inline_emits_no_block_terminator() {
        let rt = from_markdown("A **bold** subject").expect("import");
        assert!(rt.is_inline());
        let inline = emit_content_inline(&rt).expect("emit").markup;
        assert_eq!(inline, "A #strong[bold] subject");
        assert!(!inline.contains("\n\n"), "no parbreak in {inline:?}");
        let block = emit_content(&rt).expect("emit").markup;
        assert!(block.ends_with("\n\n"), "block path keeps its terminator");
    }

    /// A content that is not `is_inline` (a heading, a list, multiple paragraphs)
    /// falls back to the block lowering rather than dropping structure — the
    /// defensive path for a hand-built content on an inline field.
    #[test]
    fn inline_falls_back_to_block_for_non_inline_content() {
        for md in ["# Heading", "one\n\ntwo", "- item"] {
            let rt = from_markdown(md).expect("import");
            assert!(!rt.is_inline(), "{md:?} is not inline");
            assert_eq!(
                emit_content_inline(&rt).expect("emit").markup,
                emit_content(&rt).expect("emit").markup,
                "non-inline {md:?} must fall back to block lowering"
            );
        }
    }

    // ---- intentional divergence: block quotes render ----

    #[test]
    fn block_quote_renders_not_flattened() {
        let out = emit("> quoted text").markup;
        assert!(
            out.contains("#quote(block: true)["),
            "quote must render, got {out:?}"
        );
        assert!(out.contains("quoted text"), "quote body present: {out:?}");
    }

    // ---- thematic breaks ----

    #[test]
    fn thematic_break_renders_line() {
        for src in ["---", "***", "___"] {
            let out = emit(&format!("one\n\n{src}\n\ntwo")).markup;
            assert_eq!(
                out, "one\n\n#line(length: 100%)\n\ntwo\n\n",
                "source: {src}, got {out:?}"
            );
        }
    }

    // ---- structured table cells (Option A) ----

    /// A table cell carrying inline markdown lowers its marks through the same
    /// sweep prose runs use — `**bold**` → `#strong[bold]`, not an escaped
    /// literal — because the content stores the cell as `{text, marks}`.
    #[test]
    fn formatted_table_cell_renders_marks() {
        let md = "| Name | Note |\n|------|------|\n| **bold** | _italic_ |";
        let got = emit(md).markup;
        assert!(got.contains("#strong[bold]"), "got {got:?}");
        assert!(got.contains("#emph[italic]"), "got {got:?}");
    }

    /// An escaped pipe unescapes into the cell text at import and lowers as plain
    /// markup (`|` is not Typst-special).
    #[test]
    fn escaped_pipe_table_cell_renders_literally() {
        let md = "| A |\n|---|\n| a\\|b |";
        let got = emit(md).markup;
        assert!(got.contains("[a|b]"), "got {got:?}");
    }

    // ---- import canonicalizations: cataloged, not papered over ----

    /// Coincident `strong`+`emph` over the *same* range lose their source nesting
    /// order at import: `***x***`, `_**x**_`, and `**_x_**` all normalize to the
    /// identical content (two coincident marks). The emitter nests canonically by
    /// kind-ord (`strong` outer), so all three lower identically — the
    /// distinguishing bit is gone from the content by design.
    #[test]
    fn coincident_strong_emph_nests_canonically() {
        for m in ["**_x_**", "***x***", "_**x**_"] {
            assert_eq!(emit(m).markup, "#strong[#emph[x]]\n\n");
        }
    }

    /// An empty-text link (`[](url)`) drops at import: its mark is zero-width and
    /// `Content::normalize` drops zero-width formatting marks (`link` is
    /// formatting), leaving a blank paragraph, so the emitter yields "".
    /// Documented in `quillmark-content` (Spike-A rules).
    #[test]
    fn empty_text_link_dropped_at_import() {
        assert_eq!(emit("[](https://example.com)").markup, "");
    }

    // ---- escape tripwire: run alignment ----

    /// Reconstruct a run's generated bytes by a one-scan that treats `//`→`\/\/`
    /// as a 2-char/4-byte cluster and every other char as its own cluster, then
    /// assert the reconstruction equals `escape_markup`/`escape_string`
    /// byte-for-byte. Fails loud if an escape rule ever changes.
    fn scan_reconstruct(run: &str, ctx: EscapeCtx) -> String {
        let chars: Vec<char> = run.chars().collect();
        let mut out = String::new();
        let mut i = 0;
        while i < chars.len() {
            // The `//`→`\/\/` coupling is a *markup* rule only; `escape_string`
            // leaves `//` untouched, so it clusters solely under `Markup`.
            if ctx == EscapeCtx::Markup && chars[i] == '/' && chars.get(i + 1) == Some(&'/') {
                out.push_str("\\/\\/");
                i += 2;
                continue;
            }
            let s: String = chars[i].to_string();
            out.push_str(&match ctx {
                EscapeCtx::Markup => escape_markup(&s),
                EscapeCtx::StringLit => escape_string(&s),
            });
            i += 1;
        }
        out
    }

    #[test]
    fn escape_tripwire_markup() {
        let samples = [
            "plain text",
            "https://example.com",
            "a // b // c",
            "///",
            "Use * for _bold_ and # for @refs",
            "{braces} [brackets] $math$ <tags>",
            "C:\\Users\\file",
            "tilde~and`backtick`",
            "你好 🎉 mixed",
            "file://path//to//x",
        ];
        for s in samples {
            assert_eq!(
                scan_reconstruct(s, EscapeCtx::Markup),
                escape_markup(s),
                "markup scan != escape_markup for {s:?}"
            );
        }
    }

    #[test]
    fn escape_tripwire_string_lit() {
        let samples = [
            "plain text",
            "https://example.com",
            "a // b",
            "say \"hi\"\nnow\ttab",
            "C:\\Users\\file",
            "control\x07bell",
            "你好 🎉 mixed",
            "trailing//",
        ];
        for s in samples {
            assert_eq!(
                scan_reconstruct(s, EscapeCtx::StringLit),
                escape_string(s),
                "string scan != escape_string for {s:?}"
            );
        }
    }

    /// Record, per content char, the `(content_index, gen_byte_start)` of the
    /// cluster it opens — the ground truth the run inverters are checked
    /// against. Mirrors [`scan_reconstruct`]'s clustering (the `//` coupling is
    /// one 2-char cluster).
    fn cluster_starts(run: &str, ctx: EscapeCtx) -> (String, Vec<(usize, usize)>) {
        let chars: Vec<char> = run.chars().collect();
        let mut gen = String::new();
        let mut starts = Vec::new();
        let mut i = 0;
        while i < chars.len() {
            let byte_start = gen.len();
            if ctx == EscapeCtx::Markup && chars[i] == '/' && chars.get(i + 1) == Some(&'/') {
                starts.push((i, byte_start)); // the coupling opens at its first char
                gen.push_str("\\/\\/");
                i += 2;
                continue;
            }
            starts.push((i, byte_start));
            let s: String = chars[i].to_string();
            gen.push_str(&match ctx {
                EscapeCtx::Markup => escape_markup(&s),
                EscapeCtx::StringLit => escape_string(&s),
            });
            i += 1;
        }
        (gen, starts)
    }

    /// `invert_gen_offset` floors any byte inside a cluster to that cluster's
    /// content char, and `forward_content_offset` round-trips a cluster's content
    /// start back to its generated byte start — for markup and string-literal
    /// runs, over escapes, the `//` coupling, and wide UTF-8.
    #[test]
    fn run_offset_inversion_is_cluster_exact() {
        let cases = [
            (EscapeCtx::Markup, "plain"),
            (EscapeCtx::Markup, "a*b_c#d"),
            (EscapeCtx::Markup, "http://a//b"),
            (EscapeCtx::Markup, "///x"),
            (EscapeCtx::Markup, "你好*x*🎉"),
            (EscapeCtx::Markup, "C:\\x"),
            (EscapeCtx::StringLit, "fn add(a, b)"),
            (EscapeCtx::StringLit, "a\"b\\c"),
            (EscapeCtx::StringLit, "tab\there"),
            (EscapeCtx::StringLit, "bell\x07end"),
            (EscapeCtx::StringLit, "a//b"),
        ];
        for (ctx, run) in cases {
            let (gen, starts) = cluster_starts(run, ctx);
            // Every byte inside cluster k inverts to that cluster's content char.
            for w in 0..starts.len() {
                let (content_i, byte_start) = starts[w];
                let byte_end = starts.get(w + 1).map(|s| s.1).unwrap_or(gen.len());
                for b in byte_start..byte_end {
                    assert_eq!(
                        invert_gen_offset(&gen, ctx, b),
                        content_i,
                        "byte {b} of {run:?} ({ctx:?}) floors to cluster {content_i}"
                    );
                }
                // The cluster's content start forward-maps to its byte start.
                assert_eq!(
                    forward_content_offset(&gen, ctx, content_i),
                    byte_start,
                    "content {content_i} of {run:?} ({ctx:?}) → byte {byte_start}"
                );
            }
            // Past-the-end saturates at the run's extents both ways.
            let content_len: usize = run.chars().count();
            assert_eq!(invert_gen_offset(&gen, ctx, gen.len()), content_len);
            assert_eq!(forward_content_offset(&gen, ctx, content_len), gen.len());
        }
    }

    /// Every recorded run's generated bytes equal the escape of its content
    /// substring — the source map is byte-accurate against the emitted markup.
    #[test]
    fn runs_map_content_to_generated_bytes() {
        for md in sample_inputs() {
            let rt = from_markdown(md).unwrap();
            let ec = emit_content(&rt).unwrap();
            let chars: Vec<char> = rt.text.chars().collect();
            for seg in &ec.segments {
                // Segment window is within the markup and non-decreasing.
                assert!(seg.gen.start <= seg.gen.end && seg.gen.end <= ec.markup.len());
                for (content, gen, ctx) in &seg.runs {
                    let src: String = chars[content.clone()].iter().collect();
                    let expect = match ctx {
                        EscapeCtx::Markup => escape_markup(&src),
                        EscapeCtx::StringLit => escape_string(&src),
                    };
                    assert_eq!(
                        &ec.markup[gen.clone()],
                        expect,
                        "run bytes mismatch in {md:?}"
                    );
                    // Runs sit inside their segment's generated window.
                    assert!(gen.start >= seg.gen.start && gen.end <= seg.gen.end);
                }
            }
        }
    }

    /// Free-overlapping marks (Peritext; never produced by import, only by an
    /// editor) lower to properly nested Typst via close-and-reopen at the overlap
    /// boundary. `strong[0,4)` over `emph[2,6)` on "abcdef" →
    /// `#strong[ab#emph[cd]]#emph[ef]`.
    #[test]
    fn overlapping_marks_close_and_reopen() {
        use quillmark_content::model::{Line, Mark};
        let mut rt = Content {
            text: "abcdef".to_string(),
            lines: vec![Line {
                kind: LineKind::Para,
                containers: vec![],
                continues: false,
            }],
            marks: vec![
                Mark {
                    start: 0,
                    end: 4,
                    kind: MarkKind::Strong,
                },
                Mark {
                    start: 2,
                    end: 6,
                    kind: MarkKind::Emph,
                },
            ],
            islands: vec![],
        };
        rt.normalize();
        assert_eq!(rt.validate(), Ok(()));
        let out = emit_content(&rt).unwrap().markup;
        assert_eq!(out, "#strong[ab#emph[cd]]#emph[ef]\n\n");
        // Bracket-balanced regardless.
        assert_eq!(out.matches('[').count(), out.matches(']').count());
    }

    /// Build a single-paragraph content over `text` with hand-placed `marks`
    /// (the free-overlap shapes an editor can produce but import never does),
    /// normalize + validate it, and lower it.
    fn emit_marked(text: &str, marks: Vec<Mark>) -> String {
        use quillmark_content::model::Line;
        let mut rt = Content {
            text: text.to_string(),
            lines: vec![Line {
                kind: LineKind::Para,
                containers: vec![],
                continues: false,
            }],
            marks,
            islands: vec![],
        };
        rt.normalize();
        assert_eq!(rt.validate(), Ok(()), "content invariants");
        emit_content(&rt).unwrap().markup
    }

    fn balanced(out: &str) -> bool {
        out.matches('[').count() == out.matches(']').count()
    }

    use quillmark_content::model::Mark;

    /// A wrap that partially overlaps an atomic `code` mark lowers to balanced
    /// markup: `#raw(...)` can't carry partial styling, so the wrap clips to the
    /// text *outside* the code. Regression: a wrap `end` inside an atomic code
    /// span must still close its bracket, or the generated helper file fails to
    /// parse — the sweep's cursor must not jump straight from the code span's
    /// start to its end, skipping over the wrap `end` and trailing an unclosed
    /// `[`.
    #[test]
    fn wrap_over_atomic_code_stays_balanced() {
        // Wrap starts first, ends inside the code: strong[0,4) + code[2,6).
        let out = emit_marked(
            "abcdef",
            vec![
                Mark {
                    start: 0,
                    end: 4,
                    kind: MarkKind::Strong,
                },
                Mark {
                    start: 2,
                    end: 6,
                    kind: MarkKind::Code,
                },
            ],
        );
        assert_eq!(out, "#strong[ab]#raw(\"cdef\")\n\n");
        assert!(balanced(&out));

        // Code starts first, wrap starts inside it: code[0,4) + strong[2,6).
        let out = emit_marked(
            "abcdef",
            vec![
                Mark {
                    start: 0,
                    end: 4,
                    kind: MarkKind::Code,
                },
                Mark {
                    start: 2,
                    end: 6,
                    kind: MarkKind::Strong,
                },
            ],
        );
        assert_eq!(out, "#raw(\"abcd\")#strong[ef]\n\n");
        assert!(balanced(&out));

        // A code span fully inside a wrap still nests (neither wrap edge is
        // interior to the code, so nothing is clipped): strong[0,6) + code[2,4).
        let out = emit_marked(
            "abcdef",
            vec![
                Mark {
                    start: 0,
                    end: 6,
                    kind: MarkKind::Strong,
                },
                Mark {
                    start: 2,
                    end: 4,
                    kind: MarkKind::Code,
                },
            ],
        );
        assert_eq!(out, "#strong[ab#raw(\"cd\")ef]\n\n");
        assert!(balanced(&out));
    }

    /// A wrap still open when the sweep runs off the end closes cleanly — the
    /// stack-drain guard (belt to clipping's braces): strong[0,6) over "abcdef".
    #[test]
    fn wrap_trailing_to_end_closes() {
        let out = emit_marked(
            "abcdef",
            vec![Mark {
                start: 0,
                end: 6,
                kind: MarkKind::Strong,
            }],
        );
        assert_eq!(out, "#strong[abcdef]\n\n");
        assert!(balanced(&out));
    }

    /// Two overlapping `link` marks that share an `end` but carry distinct URLs
    /// reopen with their OWN URL, not whichever mark a bare `(ord, end)` lookup
    /// would hit first. `link{wrong}[0,6)` + `strong[0,4)` + `link{right}[2,6)`
    /// on "abcdef": at pos 4 the strong closes and the inner `link{right}`
    /// reopens — it must re-emit `right`, though `link{wrong}` shares its
    /// `(ord=5, end=6)`.
    #[test]
    fn overlapping_links_reopen_with_correct_url() {
        let out = emit_marked(
            "abcdef",
            vec![
                Mark {
                    start: 0,
                    end: 6,
                    kind: MarkKind::Link {
                        url: "wrong".into(),
                    },
                },
                Mark {
                    start: 0,
                    end: 4,
                    kind: MarkKind::Strong,
                },
                Mark {
                    start: 2,
                    end: 6,
                    kind: MarkKind::Link {
                        url: "right".into(),
                    },
                },
            ],
        );
        // The reopened tail after the strong closes carries the inner link's URL.
        assert!(
            out.contains("#link(\"right\")[ef]"),
            "reopened link keeps its own URL, got {out:?}"
        );
        assert!(
            !out.contains("#link(\"wrong\")[ef]"),
            "reopen must not borrow the outer link's URL, got {out:?}"
        );
        assert!(balanced(&out));
    }

    /// A table island's `columns:` count is the widest row, not just the header:
    /// an editor-built table with a short/empty header over wider data rows must
    /// not emit `columns: 0` (which fails to compile).
    #[test]
    fn table_columns_span_widest_row() {
        let cell = |t: &str| serde_json::json!({ "text": t, "marks": [] });
        let props = serde_json::json!({
            "header": [ cell("H") ],
            "rows": [ [ cell("a"), cell("b"), cell("c") ] ],
        });
        let out = table_markup(&props);
        assert!(out.contains("columns: 3,"), "got {out:?}");

        // Empty header, populated rows: still counts the rows.
        let props = serde_json::json!({
            "header": [],
            "rows": [ [ cell("a"), cell("b") ] ],
        });
        let out = table_markup(&props);
        assert!(out.contains("columns: 2,"), "got {out:?}");
    }

    /// A zero-column (empty) table emits nothing rather than `#table(columns: 0)`
    /// (which fails to compile), matching the markdown export path. Issue #904.
    #[test]
    fn empty_table_emits_nothing() {
        let props = serde_json::json!({ "header": [], "aligns": [], "rows": [] });
        assert_eq!(table_markup(&props), "");
    }

    /// A paragraph is one segment even across a hard break; a heading and a code
    /// fence are each one segment.
    #[test]
    fn segment_shape() {
        assert_eq!(
            emit("a  \nb  \nc").segments.len(),
            1,
            "hard-break paragraph"
        );
        assert_eq!(emit("```\nl1\nl2\nl3\n```").segments.len(), 1, "code fence");
        // A three-item list is three segments (one per item paragraph).
        assert_eq!(emit("- a\n- b\n- c").segments.len(), 3);
    }

    /// The line-anchor predicate: a trailing space is required, so the trigger
    /// set is narrow and ordinary prose is untouched.
    #[test]
    fn line_anchor_predicate() {
        for yes in ["= h", "== h", "- b", "+ n", "/ term: d", "1. i", "42. i"] {
            assert!(opens_line_anchor(yes), "{yes:?} should trigger");
        }
        for no in [
            "=foo", "==foo", "-5 degrees", "and/or", "1.item", "1) i", "hi", "", " = x",
        ] {
            assert!(!opens_line_anchor(no), "{no:?} should not trigger");
        }
    }

    /// A paragraph whose text opens with a line-anchored token gets a single `\`
    /// at column 0; the source map stays exact because the `\` sits *outside*
    /// every run's `gen` window, so each run still slices to `escape_markup` of
    /// its content. A wrap opening at the start (`#strong[…]`) puts the token
    /// mid-line, so no `\` is added there.
    #[test]
    fn line_anchor_paragraph_prefixes_backslash() {
        // Bare paragraph starts → escaped.
        assert_eq!(emit_marked("= x", vec![]), "\\= x\n\n");
        assert_eq!(emit_marked("- x", vec![]), "\\- x\n\n");
        assert_eq!(emit_marked("+ x", vec![]), "\\+ x\n\n");
        assert_eq!(emit_marked("/ t: d", vec![]), "\\/ t: d\n\n");
        assert_eq!(emit_marked("1. x", vec![]), "\\1. x\n\n");
        // Non-trigger prose is untouched.
        assert_eq!(emit_marked("hello = x", vec![]), "hello = x\n\n");
        assert_eq!(emit_marked("=x no space", vec![]), "=x no space\n\n");
        // A wrap at the start neutralizes the line-anchor already → no `\`.
        assert_eq!(
            emit_marked(
                "= x",
                vec![Mark { start: 0, end: 3, kind: MarkKind::Strong }],
            ),
            "#strong[= x]\n\n",
        );

        // Source-map integrity: every run's generated slice equals the escape of
        // its content, and the leading `\` is not inside any run.
        use quillmark_content::model::Line;
        let mut rt = Content {
            text: "= x".to_string(),
            lines: vec![Line { kind: LineKind::Para, containers: vec![], continues: false }],
            marks: vec![],
            islands: vec![],
        };
        rt.normalize();
        let ec = emit_content(&rt).unwrap();
        let chars: Vec<char> = rt.text.chars().collect();
        for seg in &ec.segments {
            for (content, gen, ctx) in &seg.runs {
                let src: String = chars[content.clone()].iter().collect();
                let expect = match ctx {
                    EscapeCtx::Markup => escape_markup(&src),
                    EscapeCtx::StringLit => escape_string(&src),
                };
                assert_eq!(&ec.markup[gen.clone()], expect, "run slices to its escape");
            }
        }
    }
}