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
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
//! Recover schema-field regions from *glyph spans* — the origin every drawn
//! frame item already carries.
//!
//! Every `Text` glyph (and `Shape`/`Image` item) in the laid-out frames
//! carries a [`Span`] pointing at the source expression that produced it.
//! Content fields are codegen'd as markup **block** bindings (`#let _qm_cN =
//! [ .. ]`) in the generated helper `lib.typ`; the file parser parses each
//! block, so every glyph carries its own syntax node's span (word/run
//! granularity) — all nested inside the block's byte range. The backend
//! records each block's **byte window** plus a per-**segment** source map at
//! generation time ([`FieldWindow`]) and classifies a frame item **two-tier**:
//! which window its resolved range nests inside, then which of that window's
//! segments (a paragraph, a heading, a whole code fence) contains it. Per-node
//! spans and a single uniform span both fall inside the same window/segment, so
//! classification is by containment, not identity. A region keys on a
//! `(window, segment)` pair, so a field breaks into one box per segment and the
//! whole-field highlight is the consumer's union of them (#829); a span between
//! segments — a field's own structural ink (brackets, container-open syntax) —
//! is transparent, accruing no box. A scalar the plate interpolates directly
//! (`#data.subject`) needs no codegen and carries no segments: its whole first
//! placement is one span-less region, windowed by [`scalar_windows`] from the
//! plate's syntax tree. Spans survive *any* content rebuild (a `show`-rule pass
//! that captures paragraphs into a state buffer and re-emits them) because they
//! are a property of the glyph, not a sibling element a rebuild can drop.
//!
//! Navigation reads the same map the other way: [`position_at`] hits a glyph,
//! adds `glyph.span.1` to its resolved node start for the exact generated byte,
//! and inverts the owning run's escape scan to a cluster-exact content offset
//! (degrading to segment start where a node nests in no single run — a
//! multi-line `#raw` block); [`locate`] forward-maps a content offset to a
//! generated byte and returns the covering glyph's box.
//!
//! **Resolution goes through the compile's own helper source.** The session
//! serves reads from its last-good compile even after a failed `apply`, but a
//! failed apply has already written the *next* injection's helper text into
//! the world — resolving the served document's spans against that text would
//! shift or drop every byte range. The scan therefore resolves helper-file
//! spans against the [`Source`] snapshot the served document was compiled
//! from, and only non-helper spans (the plate, vendored packages — sources
//! that never change within a session) through the live world.
//!
//! **First placement only.** Each `(window, segment)` key's region is its first
//! maximal run of consecutive matching frame items in document order — one
//! region per page that run touches, in page order. Span data cannot
//! distinguish "package chrome between two placements of one segment" from "a
//! second placement of the same value" (both are a gap of foreign spans), so
//! later runs are not enumerated; the first run is the true start of that
//! segment's content, and shrinks (never lies) when foreign ink interrupts it
//! mid-page. One tolerance keeps continuation pages covered: page marginals
//! (headers, footers, page numbers) walk between one page's body and the
//! next's, so a run interrupted by foreign ink may resume on the **immediately
//! following page** — a same-page gap still ends the run (that is exactly the
//! twice-placed case), at the cost that a *second* placement opening at the
//! top of the next page reads as a continuation (an over-report of that field's
//! own ink, never another field's). A field's own inter-segment ink is the one
//! exception to "any hit suspends the current run": it is transparent while its
//! own window's segment is the run, but still suspends a *different* field's
//! run (else interleaved placements merge into one lying box). The other
//! exception is **detached-span** ink — Typst's synthesized text decorations
//! (the `underline`/`strike` line, a `Shape` drawn mid-run) and list markers:
//! anonymous, attributable to no field, so it breaks no run at all (#936). A
//! scalar referenced at several distinct plate sites costs nothing: each site
//! is its own window, so each surfaces independently.
//!
//! Geometry composes the group-transform stack exactly like
//! `typst_layout::introspect::discover_frame`, transforming all four corners
//! of each item box (the stack may rotate or scale). Boxes are computed only
//! for classified ink — foreign items matter to the scan solely as
//! run-breakers.

use std::collections::HashMap;
use std::ops::Range;

use typst::layout::{Frame, FrameItem, Point, Transform};
use typst::syntax::ast::{self, AstNode};
use typst::syntax::{DiagSpan, DiagSpanKind, FileId, LinkedNode, Source, Span, SyntaxKind};
use typst::World;
use typst_layout::PagedDocument;

use quillmark_core::{ContentHit, HitGranularity, RenderedRegion};

use crate::emit::SegmentMap;
use crate::world::QuillWorld;

/// A tracked byte window in a compiled source: the schema field whose content
/// resolves into `range` of `file`. Content fields point at their generated
/// markup block (`#let _qm_cN = [ .. ]`) in the helper `lib.typ`; scalar
/// reference sites point at their expression in the plate.
#[derive(Debug, Clone)]
pub(crate) struct FieldWindow {
    pub path: String,
    pub file: FileId,
    pub range: Range<usize>,
    /// The content block's per-segment source map (`gen` ranges index the helper
    /// `lib.typ`), **empty for scalar reference sites**. The two-tier
    /// classifier resolves a span into the innermost segment; regions key on a
    /// segment's content range and navigation ([`position_at`]/[`locate`])
    /// inverts a run's escape scan through it. A segment-less window is a
    /// scalar/widget site — its whole first placement is one span-less region.
    pub segments: Vec<SegmentMap>,
}

/// An axis-aligned box accumulated in page-space (top-left origin) pt.
#[derive(Clone, Copy)]
struct Aabb {
    min_x: f64,
    min_y: f64,
    max_x: f64,
    max_y: f64,
}

impl Aabb {
    fn of(corners: [Point; 4], ts: Transform) -> Self {
        let mut b = Self {
            min_x: f64::INFINITY,
            min_y: f64::INFINITY,
            max_x: f64::NEG_INFINITY,
            max_y: f64::NEG_INFINITY,
        };
        for c in corners {
            let p = c.transform(ts);
            let (x, y) = (p.x.to_pt(), p.y.to_pt());
            b.min_x = b.min_x.min(x);
            b.min_y = b.min_y.min(y);
            b.max_x = b.max_x.max(x);
            b.max_y = b.max_y.max(y);
        }
        b
    }

    fn union(&mut self, o: Aabb) {
        self.min_x = self.min_x.min(o.min_x);
        self.min_y = self.min_y.min(o.min_y);
        self.max_x = self.max_x.max(o.max_x);
        self.max_y = self.max_y.max(o.max_y);
    }

    fn contains(&self, x: f64, y: f64) -> bool {
        self.min_x <= x && x <= self.max_x && self.min_y <= y && y <= self.max_y
    }
}

/// Flip a page-space (top-left origin) box to a PDF-space (bottom-left origin)
/// `[min_x, min_y, max_x, max_y]` rect, given the page height in pt.
fn pdf_rect(b: &Aabb, page_h: f64) -> [f32; 4] {
    [
        b.min_x as f32,
        (page_h - b.max_y) as f32,
        b.max_x as f32,
        (page_h - b.min_y) as f32,
    ]
}

/// One drawn frame item, classified into the two-tier key space, plus — for
/// window-classified ink — its page-space box.
struct Hit {
    page: usize,
    class: HitClass,
    /// `Some` for any window-classified ink (both boxable and transparent),
    /// `None` for foreign ink — matching `HitClass::window`'s `is_some()`, so
    /// [`field_at`] hit-testing is unaffected by the two-tier split.
    rect: Option<Aabb>,
}

/// Where a hit falls in the flattened key space `(window, Option<segment>)`.
#[derive(Clone, Copy)]
enum HitClass {
    /// Accrues a box under `key`: a content segment `(w, Some(s))`, or a
    /// segment-less window's whole placement `(w, None)` (a scalar site).
    Boxable { key: (usize, Option<usize>) },
    /// A content window's ink between its segments (brackets, container-open
    /// syntax) — the field's own ink, attributable to no one segment. Suspends
    /// a *different* window's current run like foreign ink, but is transparent
    /// (a no-op) while its own window's segment is the run — else an
    /// interleaved second placement of another field would merge across the gap
    /// into one lying box.
    Transparent { window: usize },
    /// **Detached-span** ink — a `Span` carrying no source location: Typst's
    /// synthesized text decorations (the `underline`/`strike`/`overline` line,
    /// drawn as a `Shape` mid-run) and list/enum marker glyphs. Anonymous by
    /// construction — attributable to no field — and, unlike [`Foreign`],
    /// **never a run-breaker**: a `#underline[..]` decoration drawn between a
    /// field's own text glyphs would otherwise suspend the run and orphan the
    /// rest of the line (#936). A marker preceding a list item's text is a
    /// no-op for the same reason, harmlessly — the next item is a different
    /// segment key that ends the run on its own.
    ///
    /// [`Foreign`]: HitClass::Foreign
    Anonymous,
    /// No window, but a *resolvable* span — page chrome, another field's text,
    /// vendored-package output. Real attributable ink from elsewhere, so it
    /// breaks a run (the twice-placed / interleaved-field guard).
    Foreign,
}

impl HitClass {
    /// The window a hit resolved to, if any — the field key [`field_at`]
    /// answers with.
    fn window(self) -> Option<usize> {
        match self {
            HitClass::Boxable { key } => Some(key.0),
            HitClass::Transparent { window } => Some(window),
            HitClass::Anonymous | HitClass::Foreign => None,
        }
    }
}

/// Fold a resolved `(window, Option<segment>)` classification into the run
/// machine's key space, given whether the originating span was **detached**.
/// `(w, None)` splits by window kind: on a **segment-less** window
/// (scalar/widget site) it is the whole placement's boxable key; on a
/// **content** window it is transparent inter-segment ink. A resolved span
/// matching no window is [`Foreign`](HitClass::Foreign); an unresolved
/// (detached) span is [`Anonymous`](HitClass::Anonymous) decoration/marker ink.
fn hit_class(
    resolved: Option<(usize, Option<usize>)>,
    detached: bool,
    windows: &[FieldWindow],
) -> HitClass {
    match resolved {
        None if detached => HitClass::Anonymous,
        None => HitClass::Foreign,
        Some((w, Some(s))) => HitClass::Boxable { key: (w, Some(s)) },
        Some((w, None)) if windows[w].segments.is_empty() => HitClass::Boxable { key: (w, None) },
        Some((w, None)) => HitClass::Transparent { window: w },
    }
}

/// Memoizing span → two-tier classifier. A block's glyphs carry a handful of
/// distinct per-node spans (not one uniform span), so the resolve + segment
/// search runs once per distinct span, not once per glyph. Helper-file spans
/// resolve against the served compile's own source snapshot (see the module
/// doc); everything else against the world.
struct Classifier<'a> {
    world: &'a QuillWorld,
    helper: &'a Source,
    windows: &'a [FieldWindow],
    memo: HashMap<Span, Option<(usize, Option<usize>)>>,
}

impl<'a> Classifier<'a> {
    fn new(world: &'a QuillWorld, helper: &'a Source, windows: &'a [FieldWindow]) -> Self {
        Self {
            world,
            helper,
            windows,
            memo: HashMap::new(),
        }
    }

    /// Resolve `span` to its byte range in whichever file it came from — the
    /// same unpack `WorldExt::range` performs, with the helper file routed to
    /// the served compile's snapshot instead of the world.
    fn resolve_range(&self, span: Span) -> Option<(FileId, Range<usize>)> {
        match DiagSpan::from(span).get() {
            DiagSpanKind::Detached => None,
            DiagSpanKind::Number { id, num, sub_range } => {
                let range = if id == self.helper.id() {
                    self.helper.range(num, sub_range)
                } else {
                    self.world
                        .source(id)
                        .ok()
                        .and_then(|s| s.range(num, sub_range))
                };
                range.map(|r| (id, r))
            }
            DiagSpanKind::Range { id, range } => Some((id, range)),
        }
    }

    /// Classify `span` to its owning window and — within it — the innermost
    /// segment whose `gen` range contains the resolved range, or `None` for
    /// inter-segment / segment-less ink. The memoized two-tier lookup both
    /// [`classify`](Self::classify) and the region/navigation walks share.
    fn classify_seg(&mut self, span: Span) -> Option<(usize, Option<usize>)> {
        if let Some(&c) = self.memo.get(&span) {
            return c;
        }
        let c = self.resolve_range(span).and_then(|(file, range)| {
            self.windows
                .iter()
                .position(|win| {
                    win.file == file && win.range.start <= range.start && range.end <= win.range.end
                })
                .map(|i| (i, self.seg_of(i, &range)))
        });
        self.memo.insert(span, c);
        c
    }

    /// The window's segment (if any) whose `gen` range contains `range`.
    /// Segments are `gen`-ordered and disjoint, so a binary search finds the
    /// sole candidate — the last segment starting at or before `range.start` —
    /// which is a hit only if it also covers `range.end`.
    fn seg_of(&self, window: usize, range: &Range<usize>) -> Option<usize> {
        let segs = &self.windows[window].segments;
        let i = segs.partition_point(|s| s.gen.start <= range.start);
        (i > 0 && segs[i - 1].gen.end >= range.end).then(|| i - 1)
    }
}

/// Walk one page frame in document order, emitting one [`Hit`] per drawn item
/// — per glyph for text (a text run may mix spans), per item for shapes and
/// images (each carries a single span). Boxes are computed for classified
/// ink only.
fn collect_page_hits(frame: &Frame, page: usize, cls: &mut Classifier, out: &mut Vec<Hit>) {
    walk_items(frame, Transform::identity(), page, &mut |page, span, _offset, aabb| {
        let class = hit_class(cls.classify_seg(span), span.is_detached(), cls.windows);
        // Boxes are computed for classified ink only; foreign ink still emits a
        // (rect-less) Hit so the run machine sees the full ink sequence.
        let rect = class.window().is_some().then(aabb);
        out.push(Hit { page, class, rect });
    });
}

/// Walk one page frame in document order, invoking `visit` once per drawn item
/// — per glyph for text (a run may mix spans), per item for shapes and images
/// (each carries a single span). `visit` receives the `page`, the item's
/// `span`, the intra-node byte `offset` (`glyph.span.1` for text, `0`
/// otherwise), and a thunk computing the item's page-space box on demand — so a
/// consumer that discards foreign ink pays no box arithmetic. This is the frame
/// geometry (group transform recursion, per-glyph cursor/advance/bbox,
/// shape/image extents) shared by the region scan ([`collect_page_hits`]) and
/// the content-position walk ([`walk_glyphs`]).
/// Per-item callback for [`walk_items`]: `(page, span, intra-node byte offset,
/// thunk computing the page-space box on demand)`.
type ItemVisitor<'a> = dyn FnMut(usize, Span, u16, &dyn Fn() -> Aabb) + 'a;

fn walk_items(frame: &Frame, ts: Transform, page: usize, visit: &mut ItemVisitor) {
    for (pos, item) in frame.items() {
        match item {
            FrameItem::Group(group) => {
                let ts = ts
                    .pre_concat(Transform::translate(pos.x, pos.y))
                    .pre_concat(group.transform);
                walk_items(&group.frame, ts, page, visit);
            }
            FrameItem::Text(text) => {
                let bb = text.bbox();
                let mut cursor = Point::zero();
                for glyph in &text.glyphs {
                    let advance =
                        Point::new(glyph.x_advance.at(text.size), glyph.y_advance.at(text.size));
                    let offset =
                        Point::new(glyph.x_offset.at(text.size), glyph.y_offset.at(text.size));
                    let lo = Point::new(cursor.x + offset.x, cursor.y + bb.min.y);
                    let hi = Point::new(cursor.x + offset.x + advance.x, cursor.y + bb.max.y);
                    let p = *pos;
                    visit(page, glyph.span.0, glyph.span.1, &|| item_aabb(p, lo, hi, ts));
                    cursor += advance;
                }
            }
            FrameItem::Shape(shape, span) => {
                let bb = shape.geometry.bbox(shape.stroke.as_ref());
                let p = *pos;
                visit(page, *span, 0, &|| item_aabb(p, bb.min, bb.max, ts));
            }
            FrameItem::Image(_, size, span) => {
                let sz = size.to_point();
                let p = *pos;
                visit(page, *span, 0, &|| item_aabb(p, Point::zero(), sz, ts));
            }
            _ => {}
        }
    }
}

/// An item box (corners `lo`..`hi` relative to the item anchor `pos`, in local
/// frame space) mapped to page space via `ts`. All four corners transform —
/// `ts` may rotate or scale.
fn item_aabb(pos: Point, lo: Point, hi: Point, ts: Transform) -> Aabb {
    Aabb::of(
        [
            Point::new(pos.x + lo.x, pos.y + lo.y),
            Point::new(pos.x + hi.x, pos.y + lo.y),
            Point::new(pos.x + lo.x, pos.y + hi.y),
            Point::new(pos.x + hi.x, pos.y + hi.y),
        ],
        ts,
    )
}

/// Per-window first-run state. The run currently accruing is not represented
/// here — at most one window can be in-run at a time (any hit forecloses
/// every other window's run), so the scan tracks it as a single cursor and
/// this enum carries only the out-of-run states.
#[derive(Clone, Copy, PartialEq)]
enum Run {
    NotSeen,
    /// Interrupted by foreign ink; may resume on page `last_page + 1` only.
    Suspended {
        last_page: usize,
    },
    Done,
}

/// Scan the compiled document and return each window's **first placement** —
/// one [`RenderedRegion`] per page the placement's run touches, PDF
/// bottom-left rects, sorted (page, field, window order). Best-effort like the
/// widget path: an unresolvable span simply matches no window.
pub(crate) fn scan(
    doc: &PagedDocument,
    world: &QuillWorld,
    helper: &Source,
    windows: &[FieldWindow],
) -> Vec<RenderedRegion> {
    if windows.is_empty() {
        return Vec::new();
    }
    let mut cls = Classifier::new(world, helper, windows);
    let mut hits = Vec::new();
    for (page, p) in doc.pages().iter().enumerate() {
        collect_page_hits(&p.frame, page, &mut cls, &mut hits);
    }

    let keys = flatten_keys(windows);
    let boxes = run_scan_machine(&keys, &hits);

    let mut out: Vec<(RenderedRegion, usize)> = Vec::new();
    for (ki, &(wi, seg)) in keys.iter().enumerate() {
        let window = &windows[wi];
        // A content segment carries its content range; a segment-less window
        // (scalar/widget site) carries none.
        let span = seg.map(|s| {
            let c = &window.segments[s].content;
            [c.start, c.end]
        });
        for (page, b) in &boxes[ki] {
            let Some(page_h) = doc.pages().get(*page).map(|p| p.frame.size().y.to_pt()) else {
                continue;
            };
            out.push((
                RenderedRegion {
                    field: window.path.clone(),
                    page: *page,
                    rect: pdf_rect(b, page_h),
                    span,
                },
                ki,
            ));
        }
    }
    // `ki` orders window-major then segment-ascending, a stable tiebreak.
    out.sort_by(|(a, ai), (b, bi)| (a.page, &a.field, *ai).cmp(&(b.page, &b.field, *bi)));
    out.into_iter().map(|(r, _)| r).collect()
}

/// The flattened two-tier key space: each content window contributes one key
/// per segment; a segment-less window (scalar/widget site) contributes one
/// `(w, None)` key. Window-major, segment-ascending — the order regions sort by.
fn flatten_keys(windows: &[FieldWindow]) -> Vec<(usize, Option<usize>)> {
    let mut keys = Vec::new();
    for (wi, w) in windows.iter().enumerate() {
        if w.segments.is_empty() {
            keys.push((wi, None));
        } else {
            keys.extend((0..w.segments.len()).map(|s| (wi, Some(s))));
        }
    }
    keys
}

/// The single-cursor two-tier run machine — same states, single global cursor,
/// and page-`+1` continuation tolerance as before, now keyed on
/// `(window, Option<segment>)`. Returns each key's first placement as per-page
/// boxes, indexed parallel to `keys`. `current` is the one key whose run is
/// accruing; a boxable hit for a different key (or foreign ink) suspends it, and
/// a suspended run resumes only on the immediately following page.
/// [`HitClass::Transparent`] — a field's own inter-segment ink — is a no-op
/// while that same window's segment is the run, else a suspension like foreign
/// ink; [`HitClass::Anonymous`] — detached decoration/marker ink — is an
/// unconditional no-op (see [`HitClass`]).
fn run_scan_machine(keys: &[(usize, Option<usize>)], hits: &[Hit]) -> Vec<Vec<(usize, Aabb)>> {
    let key_index: HashMap<(usize, Option<usize>), usize> =
        keys.iter().enumerate().map(|(i, k)| (*k, i)).collect();
    let mut state = vec![Run::NotSeen; keys.len()];
    let mut boxes: Vec<Vec<(usize, Aabb)>> = vec![Vec::new(); keys.len()];
    let mut current: Option<(usize, usize)> = None; // (key index, last_page)

    for hit in hits {
        match hit.class {
            HitClass::Boxable { key } => {
                let ki = key_index[&key];
                if current.map(|(c, _)| c) == Some(ki) {
                    accrue(&mut boxes[ki], hit);
                    current = Some((ki, hit.page));
                } else {
                    if let Some((c, last_page)) = current.take() {
                        state[c] = Run::Suspended { last_page };
                    }
                    match state[ki] {
                        Run::NotSeen => {
                            accrue(&mut boxes[ki], hit);
                            current = Some((ki, hit.page));
                        }
                        Run::Suspended { last_page } if hit.page == last_page + 1 => {
                            accrue(&mut boxes[ki], hit);
                            current = Some((ki, hit.page));
                        }
                        Run::Suspended { .. } => state[ki] = Run::Done,
                        Run::Done => {}
                    }
                }
            }
            HitClass::Transparent { window } => match current {
                // Transparent only while this field's own segment is the run;
                // a different field's run is still suspended (else interleaved
                // placements merge into one lying box).
                Some((c, _)) if keys[c].0 == window => {}
                _ => {
                    if let Some((c, last_page)) = current.take() {
                        state[c] = Run::Suspended { last_page };
                    }
                }
            },
            // Detached decoration/marker ink is anonymous — it breaks no run,
            // so a `#underline[..]`/`#strike[..]` line drawn mid-run does not
            // orphan the rest of its line (#936).
            HitClass::Anonymous => {}
            HitClass::Foreign => {
                if let Some((c, last_page)) = current.take() {
                    state[c] = Run::Suspended { last_page };
                }
            }
        }
    }
    boxes
}

/// Union `hit` into the run's box for its page, opening a new per-page box at
/// a page transition (pages are nondecreasing in walk order).
fn accrue(boxes: &mut Vec<(usize, Aabb)>, hit: &Hit) {
    let rect = hit.rect.expect("classified hits carry a box");
    match boxes.last_mut() {
        Some((page, b)) if *page == hit.page => b.union(rect),
        _ => boxes.push((hit.page, rect)),
    }
}

/// The schema field under a point — the forward (click → field) direction.
/// `x`/`y` are PDF points with a **bottom-left** origin, the same convention
/// as [`RenderedRegion::rect`]. Unlike [`scan`], every placement answers, not
/// just the first: a concrete point identifies one frame item, whose span is
/// unambiguous however many times its field is placed. Among tracked ink the
/// later-painted item wins; untracked ink never occludes — a decorative
/// overlay does not swallow clicks on the field beneath it.
pub(crate) fn field_at(
    doc: &PagedDocument,
    world: &QuillWorld,
    helper: &Source,
    windows: &[FieldWindow],
    page: usize,
    x: f32,
    y: f32,
) -> Option<String> {
    if windows.is_empty() {
        return None;
    }
    let frame = &doc.pages().get(page)?.frame;
    let page_h = frame.size().y.to_pt();
    let (x, y) = (x as f64, page_h - y as f64);

    let mut cls = Classifier::new(world, helper, windows);
    let mut hits = Vec::new();
    collect_page_hits(frame, page, &mut cls, &mut hits);

    hits.iter()
        .rev()
        .find(|h| h.rect.is_some_and(|r| r.contains(x, y)))
        .and_then(|h| h.class.window())
        .map(|w| windows[w].path.clone())
}

/// One drawn glyph (or shape/image) carrying enough to resolve a content
/// position: its page box, resolved node range and intra-node offset
/// (`glyph.span.1`), and two-tier classification. The finer counterpart to
/// [`Hit`], used by [`position_at`]/[`locate`], which need the node/offset a
/// region scan discards.
struct GlyphHit {
    page: usize,
    rect: Aabb,
    node: Range<usize>,
    /// Byte offset within the resolved node, straight from `glyph.span.1` —
    /// Typst types the intra-node span offset as `u16`, so a single text node
    /// wider than 64 KiB saturates it. Graceful degrade, not a panic: the offset
    /// floors to the last representable byte, so a caret in an overlong node
    /// resolves to the cluster/segment boundary rather than the exact glyph. No
    /// emitted node approaches this bound (paragraphs split into per-line runs).
    offset: u16,
    window: usize,
    seg: Option<usize>,
}

/// Walk one frame collecting a [`GlyphHit`] per window-classified drawn item.
/// Walk one page frame emitting a [`GlyphHit`] for each item that classifies to
/// a content window *and* resolves to a node range — the content-position twin of
/// [`collect_page_hits`], sharing [`walk_items`]' geometry. Foreign and
/// unresolvable ink is skipped (no content address), so unlike the region scan
/// it emits nothing for them.
///
/// `only` restricts emission to a single `(window, seg)` — the caret path knows
/// its target segment up front, so it skips the box arithmetic and the
/// `GlyphHit` allocation for every other glyph in the document. `None` emits all
/// classified+resolved ink (the point-hit path needs the full set).
fn walk_glyphs(
    frame: &Frame,
    page: usize,
    cls: &mut Classifier,
    only: Option<(usize, Option<usize>)>,
    out: &mut Vec<GlyphHit>,
) {
    walk_items(frame, Transform::identity(), page, &mut |page, span, offset, aabb| {
        let Some((w, seg)) = cls.classify_seg(span) else {
            return;
        };
        if only.is_some_and(|t| t != (w, seg)) {
            return;
        }
        if let Some((_, node)) = cls.resolve_range(span) {
            out.push(GlyphHit {
                page,
                rect: aabb(),
                node,
                offset,
                window: w,
                seg,
            });
        }
    });
}

/// A point → **content position** in a content field. Hit the later-painted
/// content glyph under `(x, y)`, resolve its node range + `glyph.span.1` to a
/// generated byte, and invert the owning run's escape scan to a cluster-exact
/// USV offset. Degrades to the segment's content start when the resolved node
/// nests inside no single run (a multi-line `#raw` block, or structural ink) —
/// segment-level correctness kept, finer precision unavailable. `None` off all
/// content ink or on scalar/widget ink (no content address). `x`/`y` are PDF
/// points, bottom-left origin, as [`RenderedRegion::rect`].
pub(crate) fn position_at(
    doc: &PagedDocument,
    world: &QuillWorld,
    helper: &Source,
    windows: &[FieldWindow],
    page: usize,
    x: f32,
    y: f32,
) -> Option<ContentHit> {
    if windows.is_empty() {
        return None;
    }
    let frame = &doc.pages().get(page)?.frame;
    let page_h = frame.size().y.to_pt();
    let (px, py) = (x as f64, page_h - y as f64);

    let mut cls = Classifier::new(world, helper, windows);
    let mut hits = Vec::new();
    walk_glyphs(frame, page, &mut cls, None, &mut hits);

    // Later-painted content ink wins; scalar/structural ink (no segment) has no
    // content position to report.
    let hit = hits
        .iter()
        .rev()
        .find(|g| g.seg.is_some() && g.rect.contains(px, py))?;
    let window = &windows[hit.window];
    let segmap = &window.segments[hit.seg?];
    let (pos, granularity) = invert_hit(helper, segmap, &hit.node, hit.offset);
    Some(ContentHit {
        field: window.path.clone(),
        pos,
        granularity: Some(granularity),
    })
}

/// The content USV offset a glyph's generated position maps to, plus how
/// precisely it resolved. The **owning run** is the one whose `gen` range
/// contains the whole resolved node; when present the offset is
/// [`HitGranularity::Cluster`] (cluster-exact, floored to the escape scan's
/// cluster). Absent (the `#raw` multi-line case, where every line shares one
/// node wider than any run, or structural ink) the safe degrade is the
/// **segment**'s content start — [`HitGranularity::Segment`] — not a node-start
/// computation that could land outside every line's own text.
fn invert_hit(
    helper: &Source,
    segmap: &SegmentMap,
    node: &Range<usize>,
    offset: u16,
) -> (usize, HitGranularity) {
    let Some((content_r, gen_r, ctx)) = segmap
        .runs
        .iter()
        .find(|(_, g, _)| g.start <= node.start && node.end <= g.end)
    else {
        return (segmap.content.start, HitGranularity::Segment);
    };
    // `node.start + glyph.span.1` is the exact generated byte for markup text;
    // clamp inside the run against a boundary-hugging offset.
    let abs = (node.start + offset as usize)
        .min(gen_r.end.saturating_sub(1))
        .max(gen_r.start);
    let gen_text = &helper.text()[gen_r.clone()];
    let pos = content_r.start + crate::emit::invert_gen_offset(gen_text, *ctx, abs - gen_r.start);
    (pos, HitGranularity::Cluster)
}

/// A content position → **caret rect**. Find `field`'s content window and the
/// segment covering `pos`, forward-map `pos` to a generated byte, then return
/// the box of the frame glyph whose resolved node covers that byte —
/// page-indexed, `span` collapsed to `[pos, pos]`. `None` when `field` places
/// no tracked content or `pos` maps to no drawn glyph.
pub(crate) fn locate(
    doc: &PagedDocument,
    world: &QuillWorld,
    helper: &Source,
    windows: &[FieldWindow],
    field: &str,
    pos: usize,
) -> Option<RenderedRegion> {
    if windows.is_empty() {
        return None;
    }
    let (wi, window) = windows
        .iter()
        .enumerate()
        .find(|(_, w)| w.path == field && !w.segments.is_empty())?;
    let seg_idx = window
        .segments
        .iter()
        .position(|s| s.content.start <= pos && pos <= s.content.end)?;
    let target_gen = forward_pos(helper, &window.segments[seg_idx], pos);

    let mut cls = Classifier::new(world, helper, windows);
    let mut hits = Vec::new();
    for (page, p) in doc.pages().iter().enumerate() {
        // Only this field's target segment allocates a hit — the caret needs no
        // other ink.
        walk_glyphs(&p.frame, page, &mut cls, Some((wi, Some(seg_idx))), &mut hits);
    }

    // The glyph of this segment whose node covers `target_gen`, its caret byte
    // (`node.start + span.1`) the greatest value ≤ `target_gen`; a covering
    // glyph always wins a non-covering one (`!covers` sorts first), so a caret
    // near a run edge still resolves. `min_by_key` keeps the first on ties.
    let g = hits
        .iter()
        .min_by_key(|g| {
            let covers = g.node.start <= target_gen && target_gen < g.node.end;
            let caret = g.node.start + g.offset as usize;
            (
                !covers,
                caret > target_gen,
                (caret as isize - target_gen as isize).unsigned_abs(),
            )
        })?;
    let page_h = doc.pages().get(g.page)?.frame.size().y.to_pt();
    Some(RenderedRegion {
        field: field.to_string(),
        page: g.page,
        rect: pdf_rect(&g.rect, page_h),
        span: Some([pos, pos]),
    })
}

/// The generated byte a content position forward-maps to: the run containing
/// `pos` inverts through its escape scan; a position in a structural gap (or at
/// the segment edge) falls back to the segment's generated window start.
fn forward_pos(helper: &Source, segmap: &SegmentMap, pos: usize) -> usize {
    match segmap
        .runs
        .iter()
        .find(|(c, _, _)| c.start <= pos && pos < c.end)
    {
        Some((content_r, gen_r, ctx)) => {
            let gen_text = &helper.text()[gen_r.clone()];
            gen_r.start + crate::emit::forward_content_offset(gen_text, *ctx, pos - content_r.start)
        }
        None => segmap.gen.start,
    }
}

/// Byte windows for the plate's direct scalar references. Two windows per
/// reference site where they differ:
///
/// - the **chain** window — the `data.<field>` / `data.at("<field>")` access
///   widened to the outermost postfix chain it heads (`data.refs.at(0)`,
///   `data.name.upper()`) — matching ink whose span is the reference
///   expression itself; and
/// - the **enclosing-expression** window — widened through surrounding call
///   arguments and operators (`#upper(data.subject)`, `#str(data.count)`) —
///   matching ink stamped with the whole wrapping expression's span. Emitted
///   only when exactly one reference sits inside it: an expression mixing two
///   fields (`data.a + data.b`) has no single owner and is not attributed.
///
/// Chain windows sort first, so ink resolving to the reference itself is
/// never claimed by a wider window. Each reference site is independent — a
/// field shown in both header and footer surfaces both sites. Not chased: a
/// value laundered through `#let s = data.x` carries the binding's span, and
/// card fields read from the per-card loop variable (`card.from`) have one
/// shared expression site across every card instance — no per-instance
/// identity exists in span data; a card *content* or *date* field is covered by
/// its per-instance generated site instead (a content block, or a date
/// value-object's `text(..)` closure — #990). Content- and date-field
/// references also match harmlessly: their rendered glyphs carry the helper
/// site's span, which no plate window contains, so a scalar window over
/// `data.issued` is inert once its ink migrates to the generated closure.
pub(crate) fn scalar_windows(source: &Source, fields: &[String]) -> Vec<(String, Range<usize>)> {
    let mut anchors: Vec<(String, Range<usize>, Range<usize>)> = Vec::new();
    collect_anchors(&LinkedNode::new(source.root()), fields, &mut anchors);

    let mut out: Vec<(String, Range<usize>)> = anchors
        .iter()
        .map(|(path, chain, _)| (path.clone(), chain.clone()))
        .collect();
    for (path, chain, wide) in &anchors {
        if wide == chain {
            continue;
        }
        let inside = anchors
            .iter()
            .filter(|(_, c, _)| wide.start <= c.start && c.end <= wide.end)
            .count();
        if inside == 1 {
            out.push((path.clone(), wide.clone()));
        }
    }
    out
}

/// Recurse the whole tree collecting `(path, chain range, enclosing range)`
/// per reference site. Recursion continues into matched subtrees — a
/// reference nested in another chain's arguments is its own site.
fn collect_anchors(
    node: &LinkedNode,
    fields: &[String],
    out: &mut Vec<(String, Range<usize>, Range<usize>)>,
) {
    if let Some((path, anchor)) = data_access(node, fields) {
        // Chain: the outermost postfix chain headed by this access.
        let mut chain = anchor.clone();
        while let Some(parent) = chain.parent() {
            match parent.kind() {
                SyntaxKind::FieldAccess | SyntaxKind::FuncCall => chain = parent.clone(),
                _ => break,
            }
        }
        // Enclosing expression: widened through argument and operator
        // context, stopping at any statement/markup boundary.
        let mut wide = chain.clone();
        while let Some(parent) = wide.parent() {
            match parent.kind() {
                SyntaxKind::FieldAccess
                | SyntaxKind::FuncCall
                | SyntaxKind::Args
                | SyntaxKind::Named
                | SyntaxKind::Spread
                | SyntaxKind::Parenthesized
                | SyntaxKind::Unary
                | SyntaxKind::Binary => wide = parent.clone(),
                _ => break,
            }
        }
        out.push((path, chain.range(), wide.range()));
    }
    for child in node.children() {
        collect_anchors(&child, fields, out);
    }
}

/// If `node` is a `data.<field>` access or a `data.at("<field>")` call head
/// with a declared field, its schema path and the node to widen from.
fn data_access<'a>(node: &LinkedNode<'a>, fields: &[String]) -> Option<(String, LinkedNode<'a>)> {
    if node.kind() != SyntaxKind::FieldAccess {
        return None;
    }
    let access = node.cast::<ast::FieldAccess>()?;
    let ast::Expr::Ident(target) = access.target() else {
        return None;
    };
    if target.as_str() != "data" {
        return None;
    }
    let field = access.field();
    if fields.iter().any(|f| f == field.as_str()) {
        return Some((field.as_str().to_string(), node.clone()));
    }
    // `data.at("field")`: the parent call carries the field name as its first
    // positional string argument.
    if field.as_str() == "at" {
        let parent = node.parent()?;
        let call = parent.cast::<ast::FuncCall>()?;
        let ast::Expr::FieldAccess(callee) = call.callee() else {
            return None;
        };
        if callee.to_untyped() != node.get() {
            return None;
        }
        let first = call.args().items().find_map(|arg| match arg {
            ast::Arg::Pos(ast::Expr::Str(s)) => Some(s.get().to_string()),
            _ => None,
        })?;
        if fields.contains(&first) {
            return Some((first, parent.clone()));
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::compile::compile_document;
    use crate::world::QuillWorld;
    use quillmark_core::{FileTreeNode, Quill};
    use std::collections::HashMap as Map;
    use typst::World;

    fn quill(yaml: &str, plate: &str) -> Quill {
        let mut files = Map::new();
        files.insert(
            "Quill.yaml".to_string(),
            FileTreeNode::File {
                contents: yaml.as_bytes().to_vec(),
            },
        );
        files.insert(
            "plate.typ".to_string(),
            FileTreeNode::File {
                contents: plate.as_bytes().to_vec(),
            },
        );
        Quill::from_tree(FileTreeNode::Directory { files }).expect("load quill")
    }

    /// The premise the whole mechanism stands on: content produced by a
    /// generated markup **block** binding (`#let _qm_cN = [ .. ]`) resolves
    /// into that block's recorded byte window in the helper `lib.typ` — a
    /// *package* source, not a plate file — through the production classifier.
    #[test]
    fn block_output_spans_resolve_into_the_helper_file() {
        const YAML: &str = r#"
quill:
  name: span_probe
  version: 0.1.0
  backend: typst
  description: helper-file span resolution probe
typst:
  plate_file: plate.typ
main:
  fields:
    intro:
      type: richtext
      description: a probe field
"#;
        const PLATE: &str = r#"
#import "@local/quillmark-helper:0.1.0": data
#set page(width: 400pt, height: 400pt, margin: 40pt)
#data.intro
"#;
        let q = quill(YAML, PLATE);
        let plate = crate::read_plate(&q).expect("plate");
        let schema = quillmark_core::quill::build_transform_schema(q.config());
        let meta = crate::SchemaMeta::from_schema_json(schema.as_json());
        // The seam carries the content, not markdown.
        let rt = quillmark_content::import::from_markdown("A probe paragraph, PROBETOKEN.")
            .expect("import");
        let data =
            serde_json::json!({ "intro": quillmark_content::serial::to_canonical_value(&rt) });
        let transformed = crate::transformed_data(&meta, &data).expect("transform");
        let mut world = QuillWorld::new(&q, &plate).expect("world");
        let windows = world
            .inject_helper_package(transformed.as_ref(), &meta)
            .expect("inject");
        let (doc, _) = compile_document(&world).expect("compile");
        let helper = world
            .source(QuillWorld::helper_fid("lib.typ"))
            .expect("helper source");

        let intro_idx = windows
            .iter()
            .position(|w| w.path == "intro")
            .expect("intro window");
        let mut cls = Classifier::new(&world, &helper, &windows);
        let mut hits = Vec::new();
        for (page, p) in doc.pages().iter().enumerate() {
            collect_page_hits(&p.frame, page, &mut cls, &mut hits);
        }
        assert!(
            hits.iter().any(|h| h.class.window() == Some(intro_idx)),
            "block output glyphs must classify into the helper file's recorded window {:?}",
            windows[intro_idx].range
        );
    }

    /// #936 end-to-end: an `underline`/`strike` mark must not truncate its
    /// line's `$body` region. Typst lowers all four wrapping marks the same way
    /// (`#strong[`/`#emph[`/`#underline[`/`#strike[`), but `underline`/`strike`
    /// additionally draw a decoration **`Shape` with a detached span** between
    /// the decorated glyphs and the trailing plain run. Before the fix that
    /// shape classified `Foreign` and suspended the run, so the region stopped
    /// at the mark's start and lost the whole trailing run; here every mark's
    /// region must span essentially the full line, like the undecorated marks.
    #[test]
    fn decoration_marks_do_not_truncate_the_region() {
        use quillmark_content::model::{Line, LineKind, Mark, MarkKind, Content};
        const YAML: &str = r#"
quill:
  name: deco_probe
  version: 0.1.0
  backend: typst
  description: underline and strike region truncation probe
typst:
  plate_file: plate.typ
main:
  fields:
    body:
      type: richtext
      description: one paragraph with one decorated run
"#;
        const PLATE: &str = r#"
#import "@local/quillmark-helper:0.1.0": data
#set page(width: 400pt, height: 400pt, margin: 40pt)
#data.body
"#;
        // The mark [6,11) over "uline" leaves a long trailing plain run — the
        // part the truncation used to swallow.
        const TEXT: &str = "Start uline and then a long trailing plain run of text.";
        let region_width = |kind: MarkKind| -> f32 {
            let rt = Content {
                text: TEXT.to_string(),
                lines: vec![Line {
                    containers: vec![],
                    kind: LineKind::Para,
                    continues: false,
                }],
                marks: vec![Mark {
                    start: 6,
                    end: 11,
                    kind,
                }],
                islands: vec![],
            };
            let q = quill(YAML, PLATE);
            let plate = crate::read_plate(&q).expect("plate");
            let schema = quillmark_core::quill::build_transform_schema(q.config());
            let meta = crate::SchemaMeta::from_schema_json(schema.as_json());
            let data =
                serde_json::json!({ "body": quillmark_content::serial::to_canonical_value(&rt) });
            let transformed = crate::transformed_data(&meta, &data).expect("transform");
            let mut world = QuillWorld::new(&q, &plate).expect("world");
            let windows = world
                .inject_helper_package(transformed.as_ref(), &meta)
                .expect("inject");
            let (doc, _) = compile_document(&world).expect("compile");
            let helper = world
                .source(QuillWorld::helper_fid("lib.typ"))
                .expect("helper source");
            let regions = scan(&doc, &world, &helper, &windows);
            regions
                .iter()
                .filter(|r| r.field == "body")
                .map(|r| r.rect[2] - r.rect[0])
                .fold(0.0f32, f32::max)
        };

        // `strong` is a stand-in for "no decoration shape": its region is the
        // full paragraph width. Every mark should land within a hair of it.
        let baseline = region_width(MarkKind::Strong);
        assert!(
            baseline > 150.0,
            "sanity: full-line region is wide: {baseline}"
        );
        for kind in [MarkKind::Emph, MarkKind::Underline, MarkKind::Strike] {
            let w = region_width(kind.clone());
            assert!(
                w >= baseline * 0.9,
                "{kind:?} region width {w} truncated vs {baseline} baseline (#936)"
            );
        }
    }

    #[test]
    fn scalar_windows_track_chains_and_single_owner_enclosing_expressions() {
        let src = Source::detached(
            r#"
#import "@local/quillmark-helper:0.1.0": data
#data.subject
#data.at("subject")
#data.refs.at(0)
#upper(data.subject)
#(data.subject + data.other)
#let s = data.other
"#,
        );
        let fields = vec![
            "subject".to_string(),
            "refs".to_string(),
            "other".to_string(),
        ];
        let wins = scalar_windows(&src, &fields);
        let text = src.text();
        let spans: Vec<(&str, &str)> = wins
            .iter()
            .map(|(p, r)| (p.as_str(), &text[r.clone()]))
            .collect();
        for expected in [
            ("subject", "data.subject"),
            ("subject", "data.at(\"subject\")"),
            ("refs", "data.refs.at(0)"),
            ("other", "data.other"),
            // A wrapping call with a single reference owns its whole
            // expression: ink stamped with the outer call's span attributes
            // to the field.
            ("subject", "upper(data.subject)"),
        ] {
            assert!(spans.contains(&expected), "missing {expected:?}: {spans:?}");
        }
        // An expression mixing two fields has no single owner — no enclosing
        // window for either.
        assert!(
            !spans
                .iter()
                .any(|(_, t)| t.contains("data.subject + data.other")),
            "multi-reference expressions are not attributed: {spans:?}"
        );
        // Chain windows precede enclosing-expression windows, so ink at the
        // reference itself is never claimed by a wider window.
        let chain_pos = spans
            .iter()
            .position(|s| *s == ("subject", "data.subject"))
            .unwrap();
        let wide_pos = spans
            .iter()
            .position(|s| *s == ("subject", "upper(data.subject)"))
            .unwrap();
        assert!(chain_pos < wide_pos, "chains sort before wides: {spans:?}");
    }

    // -----------------------------------------------------------------
    // Two-tier `(window, Option<segment>)` classification and the run-machine
    // transparency arm (#829). The tests below drive the production
    // `Classifier::classify_seg` and `run_scan_machine` directly, pinning a
    // transparent same-window arm that still suspends across fields against
    // the shipped code, not a re-derived copy.
    // -----------------------------------------------------------------

    /// Every drawn item's span in a frame, geometry dropped — classification
    /// is all this probe needs.
    fn collect_spans(frame: &Frame, out: &mut Vec<Span>) {
        for (_, item) in frame.items() {
            match item {
                FrameItem::Group(group) => collect_spans(&group.frame, out),
                FrameItem::Text(text) => out.extend(text.glyphs.iter().map(|g| g.span.0)),
                FrameItem::Shape(_, span) => out.push(*span),
                FrameItem::Image(_, _, span) => out.push(*span),
                _ => {}
            }
        }
    }

    /// A real two-item list lowers to two segments (`segment_shape` in
    /// `emit.rs` pins this). Proves the two-tier construction classifies real
    /// compiled output correctly on the half that *is* exercised: each
    /// item's own ink resolves to its own segment.
    ///
    /// The other half — genuine `(window, None)` ink from container-open
    /// syntax — does **not** materialize here: Typst's synthesized list
    /// marker carries a **detached** span (`DiagSpanKind::Detached`, printed
    /// as `Span(1)` below), not one resolving into the helper file, so it
    /// lands in the plain "no window at all" bucket alongside package
    /// chrome — already-correct, unchanged behavior. A block-quote wrapper
    /// (`#quote(block: true)[...]`) draws no extra ink at all by default. Both
    /// were probed by hand (temporarily swapping this test's markdown input
    /// and eyeballing `Classifier::resolve_range` per glyph) before writing
    /// this comment; see the findings doc for the transcript. The
    /// `(window, None)` *mechanism* is still real and still needed — proved
    /// directly, independent of whichever container syntax does or doesn't
    /// exercise it today, by
    /// [`classify_two_tier_resolves_field_only_ink_between_segments`].
    #[test]
    fn two_tier_classification_resolves_each_segment_independently() {
        const YAML: &str = r#"
quill:
  name: two_tier_probe
  version: 0.1.0
  backend: typst
  description: PR-F Unknown-1 two-tier classification probe
typst:
  plate_file: plate.typ
main:
  fields:
    body:
      type: richtext
      description: a two-item list
"#;
        const PLATE: &str = r#"
#import "@local/quillmark-helper:0.1.0": data
#set page(width: 400pt, height: 400pt, margin: 40pt)
#data.body
"#;
        let q = quill(YAML, PLATE);
        let plate = crate::read_plate(&q).expect("plate");
        let schema = quillmark_core::quill::build_transform_schema(q.config());
        let meta = crate::SchemaMeta::from_schema_json(schema.as_json());
        let rt =
            quillmark_content::import::from_markdown("- Item ONE\n- Item TWO").expect("import");
        let data =
            serde_json::json!({ "body": quillmark_content::serial::to_canonical_value(&rt) });
        let transformed = crate::transformed_data(&meta, &data).expect("transform");
        let mut world = QuillWorld::new(&q, &plate).expect("world");
        let windows = world
            .inject_helper_package(transformed.as_ref(), &meta)
            .expect("inject");
        let (doc, _) = compile_document(&world).expect("compile");
        let helper = world
            .source(QuillWorld::helper_fid("lib.typ"))
            .expect("helper source");

        let win_idx = windows
            .iter()
            .position(|w| w.path == "body")
            .expect("body window");
        assert_eq!(
            windows[win_idx].segments.len(),
            2,
            "one segment per list item"
        );

        let mut cls = Classifier::new(&world, &helper, &windows);
        let mut spans = Vec::new();
        for p in doc.pages().iter() {
            collect_spans(&p.frame, &mut spans);
        }

        let mut seg_hits = [0usize; 2];
        let mut field_only_hits = 0usize;
        let mut untracked_hits = 0usize;
        for span in spans {
            match cls.classify_seg(span) {
                Some((w, Some(s))) if w == win_idx => seg_hits[s] += 1,
                Some((w, None)) if w == win_idx => field_only_hits += 1,
                _ => untracked_hits += 1,
            }
        }
        assert!(
            seg_hits[0] > 0 && seg_hits[1] > 0,
            "each list item's own ink resolves to its own segment: {seg_hits:?}"
        );
        assert_eq!(
            field_only_hits, 0,
            "list markers do not produce (window, None) ink — see the doc comment"
        );
        assert!(
            untracked_hits > 0,
            "the two markers are hit but resolve to no window (detached span)"
        );
    }

    /// The mechanism itself, independent of whether any *current* `emit.rs`
    /// container produces it: a real, resolvable span strictly between two
    /// recorded segments, but still inside the block window, must classify
    /// `(window, None)`.
    ///
    /// A real compile of "before **BOLD** after" gives three distinct,
    /// genuinely resolvable spans in one paragraph (a bold run is its own
    /// content child, so it and its plain-text neighbors carry different
    /// spans — unlike the undifferentiated multi-word prose in the sibling
    /// test above, which Typst folds into one span per paragraph). This test
    /// takes those three real spans and re-windows them by hand — segment 0
    /// = "before", segment 1 = "after", the bold run deliberately excluded —
    /// so the excluded span must classify `(window, None)`: real Typst spans,
    /// a synthetic window, proving `classify_two_tier`'s containment logic
    /// without depending on which container syntax does or doesn't produce
    /// such ink today.
    #[test]
    fn classify_two_tier_resolves_field_only_ink_between_segments() {
        const YAML: &str = r#"
quill:
  name: two_tier_mechanism_probe
  version: 0.1.0
  backend: typst
  description: PR-F Unknown-1 classify_two_tier mechanism probe
typst:
  plate_file: plate.typ
main:
  fields:
    body:
      type: richtext
      description: one paragraph, one bold run
"#;
        const PLATE: &str = r#"
#import "@local/quillmark-helper:0.1.0": data
#set page(width: 400pt, height: 400pt, margin: 40pt)
#data.body
"#;
        let q = quill(YAML, PLATE);
        let plate = crate::read_plate(&q).expect("plate");
        let schema = quillmark_core::quill::build_transform_schema(q.config());
        let meta = crate::SchemaMeta::from_schema_json(schema.as_json());
        let rt =
            quillmark_content::import::from_markdown("before **BOLD** after").expect("import");
        let data =
            serde_json::json!({ "body": quillmark_content::serial::to_canonical_value(&rt) });
        let transformed = crate::transformed_data(&meta, &data).expect("transform");
        let mut world = QuillWorld::new(&q, &plate).expect("world");
        let windows = world
            .inject_helper_package(transformed.as_ref(), &meta)
            .expect("inject");
        let (doc, _) = compile_document(&world).expect("compile");
        let helper = world
            .source(QuillWorld::helper_fid("lib.typ"))
            .expect("helper source");
        let real_win = windows
            .iter()
            .find(|w| w.path == "body")
            .expect("body window");
        assert_eq!(real_win.segments.len(), 1, "one paragraph, one segment");

        let cls = Classifier::new(&world, &helper, &windows);
        let mut spans = Vec::new();
        for p in doc.pages().iter() {
            collect_spans(&p.frame, &mut spans);
        }
        // Group by resolved (file, range) in first-seen (document) order —
        // one entry per distinct real Typst node inside the field's window.
        let mut nodes: Vec<(Span, Range<usize>)> = Vec::new();
        for span in spans {
            if let Some((file, range)) = cls.resolve_range(span) {
                if file == real_win.file
                    && real_win.range.start <= range.start
                    && range.end <= real_win.range.end
                    && !nodes.iter().any(|(_, r)| *r == range)
                {
                    nodes.push((span, range));
                }
            }
        }
        nodes.sort_by_key(|(_, r)| r.start);
        // Word-level granularity: plain text and the space beside it are
        // separate nodes too (an empirical Unknown-2 finding — see the
        // findings doc), so "before" contributes more than one node. Split
        // on the node whose text is exactly "BOLD".
        let text = helper.text();
        let bold_idx = nodes
            .iter()
            .position(|(_, r)| &text[r.clone()] == "BOLD")
            .expect("a node holding exactly \"BOLD\": {nodes:?}");
        assert!(
            bold_idx > 0 && bold_idx + 1 < nodes.len(),
            "ink on both sides of BOLD: {nodes:?}"
        );
        let before = &nodes[..bold_idx];
        let (bold_span, _) = nodes[bold_idx].clone();
        let after = &nodes[bold_idx + 1..];

        // Re-window by hand: segment 0 spans the "before" nodes, segment 1
        // spans the "after" nodes, the bold run deliberately excluded from
        // both — the boundaries a real two-tier classifier would compute
        // from `emit.rs`'s recorded segment range, reconstructed here from
        // the real node ranges either side of it.
        let synthetic = vec![FieldWindow {
            path: "body".to_string(),
            file: real_win.file,
            range: real_win.range.clone(),
            segments: vec![
                SegmentMap {
                    content: 0..0,
                    gen: before.first().unwrap().1.start..before.last().unwrap().1.end,
                    runs: vec![],
                },
                SegmentMap {
                    content: 0..0,
                    gen: after.first().unwrap().1.start..after.last().unwrap().1.end,
                    runs: vec![],
                },
            ],
        }];
        let mut synthetic_cls = Classifier::new(&world, &helper, &synthetic);
        for (span, range) in before {
            assert_eq!(
                synthetic_cls.classify_seg(*span),
                Some((0, Some(0))),
                "a \"before\"-side node ({range:?}) -> segment 0"
            );
        }
        for (span, range) in after {
            assert_eq!(
                synthetic_cls.classify_seg(*span),
                Some((0, Some(1))),
                "an \"after\"-side node ({range:?}) -> segment 1"
            );
        }
        assert_eq!(
            synthetic_cls.classify_seg(bold_span),
            Some((0, None)),
            "the excluded bold run sits inside the block window but outside every segment"
        );
    }

    fn aabb(min_x: f64, min_y: f64, max_x: f64, max_y: f64) -> Aabb {
        Aabb {
            min_x,
            min_y,
            max_x,
            max_y,
        }
    }

    fn boxable_hit(page: usize, key: (usize, Option<usize>), rect: Aabb) -> Hit {
        Hit {
            page,
            class: HitClass::Boxable { key },
            rect: Some(rect),
        }
    }

    fn transparent_hit(page: usize, window: usize) -> Hit {
        Hit {
            page,
            class: HitClass::Transparent { window },
            rect: None,
        }
    }

    fn foreign_hit(page: usize) -> Hit {
        Hit {
            page,
            class: HitClass::Foreign,
            rect: None,
        }
    }

    fn anonymous_hit(page: usize) -> Hit {
        Hit {
            page,
            class: HitClass::Anonymous,
            rect: None,
        }
    }

    /// Each key's accrued pages, in order, dropping never-accrued keys — the
    /// production [`run_scan_machine`] read as page sequences.
    fn key_pages(
        keys: &[(usize, Option<usize>)],
        hits: &[Hit],
    ) -> HashMap<(usize, Option<usize>), Vec<usize>> {
        run_scan_machine(keys, hits)
            .into_iter()
            .enumerate()
            .filter(|(_, b)| !b.is_empty())
            .map(|(i, b)| (keys[i], b.into_iter().map(|(p, _)| p).collect()))
            .collect()
    }

    /// The crux: transparent same-window ink between two hits of one segment
    /// keeps the run — both accrue into one unioned box — while foreign ink in
    /// the identical shape ends it, leaving only the first hit's extent.
    /// Distinct rects make the difference visible (same-page union vs.
    /// suppressed second hit).
    #[test]
    fn field_only_ink_is_transparent_but_foreign_ink_is_not() {
        let keys = vec![(0usize, Some(0usize))];
        let (a, b) = (aabb(0.0, 0.0, 1.0, 1.0), aabb(10.0, 10.0, 11.0, 11.0));

        let transparent = vec![
            boxable_hit(0, (0, Some(0)), a),
            transparent_hit(0, 0),
            boxable_hit(0, (0, Some(0)), b),
        ];
        let boxes = run_scan_machine(&keys, &transparent);
        assert_eq!(boxes[0].len(), 1, "one page-0 box");
        let (_, bx) = boxes[0][0];
        assert!(
            bx.min_x <= 0.0 && bx.max_x >= 11.0,
            "the box unions both hits — the run stayed unbroken"
        );

        let foreign = vec![
            boxable_hit(0, (0, Some(0)), a),
            foreign_hit(0),
            boxable_hit(0, (0, Some(0)), b),
        ];
        let boxes = run_scan_machine(&keys, &foreign);
        assert_eq!(boxes[0].len(), 1, "one page-0 box, unresumed");
        let (_, bx) = boxes[0][0];
        assert!(
            bx.max_x < 11.0,
            "only the first hit accrued — same-page foreign ink ends the run, exactly today's rule"
        );
    }

    /// #936: detached decoration ink (a `#underline`/`#strike` line) drawn
    /// between two hits of one segment must keep the run — both accrue into one
    /// unioned box — where identically-placed *foreign* ink would end it. The
    /// underline case is exactly this shape: `Start `, then the decorated run's
    /// glyphs, then the decoration `Shape` (detached span), then the trailing
    /// plain run, all one segment. Foreign ink here would truncate the region
    /// at the decoration, orphaning the trailing run.
    #[test]
    fn anonymous_ink_is_transparent_but_foreign_ink_is_not() {
        let keys = vec![(0usize, Some(0usize))];
        let (a, b) = (aabb(0.0, 0.0, 1.0, 1.0), aabb(10.0, 10.0, 11.0, 11.0));

        let anonymous = vec![
            boxable_hit(0, (0, Some(0)), a),
            anonymous_hit(0), // the underline/strike decoration Shape
            boxable_hit(0, (0, Some(0)), b),
        ];
        let boxes = run_scan_machine(&keys, &anonymous);
        assert_eq!(boxes[0].len(), 1, "one page-0 box");
        let (_, bx) = boxes[0][0];
        assert!(
            bx.min_x <= 0.0 && bx.max_x >= 11.0,
            "the box unions both hits — the decoration did not break the run"
        );

        let foreign = vec![
            boxable_hit(0, (0, Some(0)), a),
            foreign_hit(0),
            boxable_hit(0, (0, Some(0)), b),
        ];
        let boxes = run_scan_machine(&keys, &foreign);
        let (_, bx) = boxes[0][0];
        assert!(
            bx.max_x < 11.0,
            "foreign ink still ends the run — only detached ink is exempt"
        );
    }

    /// Two adjacent segments of one field are tracked independently, exactly as
    /// two distinct top-level fields are — the second item's transparent bullet
    /// ink between them is a no-op, not a merge.
    #[test]
    fn adjacent_segments_of_one_field_run_independently() {
        let keys = vec![(0, Some(0)), (0, Some(1))];
        let r = aabb(0.0, 0.0, 1.0, 1.0);
        let hits = vec![
            boxable_hit(0, (0, Some(0)), r),
            transparent_hit(0, 0), // e.g. the second item's bullet marker
            boxable_hit(0, (0, Some(1)), r),
        ];
        let pages = key_pages(&keys, &hits);
        assert_eq!(pages[&(0, Some(0))], vec![0]);
        assert_eq!(pages[&(0, Some(1))], vec![0]);
    }

    /// The scoping the plan text omits: transparency is relative to a
    /// *same-window* current run only. Field 1's segment mid-run, interrupted
    /// by *field 0's* own field-only ink, must still suspend — else an
    /// interleaved second placement of field 1 would merge across the gap into
    /// one lying box.
    #[test]
    fn field_only_ink_still_suspends_a_different_fields_current_run() {
        let keys = vec![(1, Some(0))];
        let r = aabb(0.0, 0.0, 1.0, 1.0);

        let cross_page = vec![
            boxable_hit(0, (1, Some(0)), r), // field 1's segment 0, page 0
            transparent_hit(0, 0),           // field 0's own structural ink
            boxable_hit(1, (1, Some(0)), r), // field 1's segment 0 resumes, page 1
        ];
        assert_eq!(
            key_pages(&keys, &cross_page)[&(1, Some(0))],
            vec![0, 1],
            "a foreign field's field-only ink suspends the running field \
             (the page-turn tolerance still lets it resume)"
        );

        let same_page = vec![
            boxable_hit(0, (1, Some(0)), r),
            transparent_hit(0, 0),
            boxable_hit(0, (1, Some(0)), r),
        ];
        assert_eq!(
            key_pages(&keys, &same_page)[&(1, Some(0))],
            vec![0],
            "no same-page resume — field-only ink is not a wildcard exception \
             to the foreign-ink suspension rule"
        );
    }

    // -----------------------------------------------------------------
    // Does `glyph.span.1` give usable per-character intra-node offsets, and
    // where does it degrade (raw string literals, list/enum numbering,
    // shaping clusters)? This test pins the empirical findings so a future Typst
    // upgrade cannot silently change them unnoticed.
    // -----------------------------------------------------------------

    /// One glyph's classification-relevant facts: the resolved node range
    /// (`glyph.span.0`, unpacked), the intra-node offset (`glyph.span.1`),
    /// and the glyph's own text slice (via `glyph.range()` into the
    /// `TextItem`'s text) — enough to check whether `node.start + offset`
    /// lands on the right generated byte, without needing the geometry
    /// `collect_page_hits` computes.
    struct GlyphProbe {
        node: Range<usize>,
        offset: u16,
        text: String,
    }

    fn collect_glyph_probes(
        frame: &Frame,
        cls: &Classifier,
        win: &FieldWindow,
        out: &mut Vec<GlyphProbe>,
    ) {
        for (_, item) in frame.items() {
            match item {
                FrameItem::Group(group) => collect_glyph_probes(&group.frame, cls, win, out),
                FrameItem::Text(text) => {
                    for g in &text.glyphs {
                        if let Some((file, range)) = cls.resolve_range(g.span.0) {
                            if file == win.file
                                && win.range.start <= range.start
                                && range.end <= win.range.end
                            {
                                out.push(GlyphProbe {
                                    node: range,
                                    offset: g.span.1,
                                    text: text.text[g.range()].to_string(),
                                });
                            }
                        }
                    }
                }
                _ => {}
            }
        }
    }

    /// A formatted paragraph (plain text + one `#strong[...]` run) plus a
    /// multi-line code fence, in one field — the two constructs the plan's
    /// risk 2 names. Findings pinned here (see the module-level comment
    /// above for the full write-up):
    ///
    /// - **Plain / bold markup text**: `glyph.span.1` is exact, byte-
    ///   granular, per character. Every resolved node nests inside exactly
    ///   one recorded `run`, and `run.gen.start + offset` (which for markup
    ///   text equals `node.start + offset`, since Typst's own node range is
    ///   already tight around that specific run) lands on the correct
    ///   generated byte, for every glyph tested.
    /// - **A multi-line `#raw(block: true, "...")` string literal**: every
    ///   line's glyphs resolve to the **identical** node range (the whole
    ///   call expression, not the string literal or any one line), and
    ///   `span.1` **resets to 0 at each physical line**. Two consequences,
    ///   pinned below: (a) `span.0` alone cannot tell which of the fence's N
    ///   lines a hit belongs to — the same `(node, offset)` pair is
    ///   ambiguous between lines; (b) the resolved node range does not fit
    ///   inside *any* recorded run's `gen` range (it is wider than every one
    ///   of them), so per-run inversion structurally fails — not just loses
    ///   precision. It *does* still fit inside the segment's `gen` range, so
    ///   segment-level classification (which segment, i.e. which field's
    ///   code fence) remains correct; only the finer run/line/char answer is
    ///   unavailable.
    #[test]
    fn glyph_span_1_precision_findings() {
        const YAML: &str = r#"
quill:
  name: span_precision_probe
  version: 0.1.0
  backend: typst
  description: PR-F Unknown-2 glyph.span.1 precision probe
typst:
  plate_file: plate.typ
main:
  fields:
    body:
      type: richtext
      description: a formatted paragraph plus a multi-line code fence
"#;
        const PLATE: &str = r#"
#import "@local/quillmark-helper:0.1.0": data
#set page(width: 400pt, height: 400pt, margin: 40pt)
#data.body
"#;
        // "difficult fickle" carries two "fi"/"ff"-adjacent clusters, probing
        // (inconclusively, see the findings doc) for shaping-ligature
        // collapse under Typst's default font.
        let md = "This is **bold** difficult fickle text.\n\n```\nfn add(a, b) {\n    return a + b;\n}\n```";
        let q = quill(YAML, PLATE);
        let plate = crate::read_plate(&q).expect("plate");
        let schema = quillmark_core::quill::build_transform_schema(q.config());
        let meta = crate::SchemaMeta::from_schema_json(schema.as_json());
        let rt = quillmark_content::import::from_markdown(md).expect("import");
        let data =
            serde_json::json!({ "body": quillmark_content::serial::to_canonical_value(&rt) });
        let transformed = crate::transformed_data(&meta, &data).expect("transform");
        let mut world = QuillWorld::new(&q, &plate).expect("world");
        let windows = world
            .inject_helper_package(transformed.as_ref(), &meta)
            .expect("inject");
        let (doc, _) = compile_document(&world).expect("compile");
        let helper = world
            .source(QuillWorld::helper_fid("lib.typ"))
            .expect("helper source");
        let win = windows
            .iter()
            .find(|w| w.path == "body")
            .expect("body window");
        assert_eq!(
            win.segments.len(),
            2,
            "one paragraph segment, one code segment"
        );
        let (para_seg, code_seg) = (&win.segments[0], &win.segments[1]);
        assert!(
            code_seg.runs.len() >= 2,
            "the fence's multiple lines each recorded their own run: {:?}",
            code_seg.runs
        );

        let cls = Classifier::new(&world, &helper, &windows);
        let mut probes = Vec::new();
        for p in doc.pages().iter() {
            collect_glyph_probes(&p.frame, &cls, win, &mut probes);
        }
        assert!(!probes.is_empty(), "the field must place some glyphs");

        // ---- plain/bold markup text: node.start + offset is exact ----
        let mut checked_para_glyph = false;
        for probe in &probes {
            if probe.node.start >= para_seg.gen.start && probe.node.end <= para_seg.gen.end {
                // The node nests inside exactly one recorded run, and that
                // run's own `gen.start` is what `offset` is relative to.
                let owning_run = para_seg
                    .runs
                    .iter()
                    .find(|(_, gen, _)| gen.start <= probe.node.start && probe.node.end <= gen.end)
                    .unwrap_or_else(|| {
                        panic!("markup node {:?} must nest inside some run", probe.node)
                    });
                let absolute = probe.node.start + probe.offset as usize;
                assert!(
                    absolute >= owning_run.1.start && absolute < owning_run.1.end + 1,
                    "node.start + offset ({absolute}) must land inside the owning run {:?} for {:?}",
                    owning_run.1,
                    probe.text,
                );
                // Byte-exact: the character at `absolute` in the generated
                // source is exactly this glyph's own text.
                assert_eq!(
                    &helper.text()[absolute..absolute + probe.text.len()],
                    probe.text,
                    "node.start + offset must point at this glyph's own bytes"
                );
                checked_para_glyph = true;
            }
        }
        assert!(
            checked_para_glyph,
            "at least one paragraph glyph must be checked"
        );

        // ---- multi-line #raw string literal: the per-line collapse ----
        let code_probes: Vec<&GlyphProbe> = probes
            .iter()
            .filter(|p| p.node.start >= code_seg.gen.start && p.node.end <= code_seg.gen.end)
            .collect();
        assert!(!code_probes.is_empty(), "the code fence must place glyphs");

        // (a) every line shares the identical resolved node — span.0 alone
        // cannot disambiguate which line a hit belongs to.
        let distinct_nodes: std::collections::HashSet<Range<usize>> =
            code_probes.iter().map(|p| p.node.clone()).collect();
        assert_eq!(
            distinct_nodes.len(),
            1,
            "every raw-block glyph shares one node range regardless of physical line: {distinct_nodes:?}"
        );
        let raw_node = distinct_nodes.into_iter().next().unwrap();

        // (b) offset resets to 0 more than once — once per physical line,
        // not once for the whole multi-line literal.
        let resets = code_probes
            .windows(2)
            .filter(|w| w[1].offset == 0 && w[0].offset != 0)
            .count();
        assert!(
            resets >= 1,
            "offset must reset at a line boundary at least once across 3 lines: {:?}",
            code_probes.iter().map(|p| p.offset).collect::<Vec<_>>()
        );

        // (c) the shared node does not fit inside any single run's `gen`
        // range (it is wider than every one of them) — per-run inversion by
        // containment structurally fails here, though the node still fits
        // the *segment's* gen range (segment-level classification holds).
        assert!(
            raw_node.start >= code_seg.gen.start && raw_node.end <= code_seg.gen.end,
            "the raw call's node still nests inside the code segment"
        );
        assert!(
            !code_seg
                .runs
                .iter()
                .any(|(_, gen, _)| gen.start <= raw_node.start && raw_node.end <= gen.end),
            "no single run should contain the whole-call node — it is coarser than every run"
        );
    }

    // -----------------------------------------------------------------
    // #990 verification spikes — the value-object date design's load-bearing
    // assumptions, pinned against Typst 0.15 (the driving-consumer gap: USAF
    // memo/indorsement dates place through `.display()`, and indorsements are
    // cards whose loop-variable ink `scalar_windows` deliberately does not
    // chase). The design emits each present date as a dict value-object whose
    // `display:` key holds a generated closure `(..args) => text(datetime(..)
    // .display(..args))`, so the glyphs are born inside a recorded helper
    // window. These four are the go/no-go gates — first commits, re-pinned as
    // tests per the #797 pattern.
    // -----------------------------------------------------------------

    /// Compile `plate` and return its concatenated frame text (glyph runs in
    /// document order) or the mapped compile error — the observable the
    /// language-behavior spikes assert on.
    fn compile_frame_text(plate: &str) -> Result<String, String> {
        const YAML: &str = r#"
quill:
  name: spike_990
  version: 0.1.0
  backend: typst
  description: date value-object verification spike (990)
typst:
  plate_file: plate.typ
"#;
        fn walk_text(frame: &Frame, out: &mut String) {
            for (_, item) in frame.items() {
                match item {
                    FrameItem::Group(g) => walk_text(&g.frame, out),
                    FrameItem::Text(t) => out.push_str(&t.text),
                    _ => {}
                }
            }
        }
        let q = quill(YAML, plate);
        let plate = crate::read_plate(&q).expect("plate");
        let world = QuillWorld::new(&q, &plate).expect("world");
        match compile_document(&world) {
            Ok((doc, _)) => {
                let mut s = String::new();
                for p in doc.pages() {
                    walk_text(&p.frame, &mut s);
                }
                Ok(s)
            }
            Err(e) => Err(format!("{e:?}")),
        }
    }

    /// The value-object's generated shape, for the language-behavior spikes:
    /// `d` is the dict a present date lowers to, `display` a closure forwarding
    /// its args to the native `datetime`.
    const VALUE_OBJECT: &str = "#set page(width: 400pt, height: 400pt, margin: 20pt)\n\
        #let d = (\
          value: datetime(year: 2026, month: 1, day: 2), \
          display: (..args) => text(datetime(year: 2026, month: 1, day: 2).display(..args)),\
        )\n";

    /// #990 spike 1 (go/no-go gate #1) — **dict-method-sugar does not forward.**
    ///
    /// The primary design's headline claim is that plates keep calling
    /// `card.on.display("…")` verbatim while `card.on` migrates from a native
    /// `datetime` to a value-object dict. This pins what Typst 0.15 actually
    /// does with that call site:
    ///
    /// - method sugar on the dict — `d.display("[year]")` — is a **hard
    ///   error**. Typst reserves `dict.key(..)` for built-in dict methods and
    ///   refuses to dispatch it to a stored closure ("cannot directly call
    ///   dictionary keys as functions"), hinting the parenthesized form;
    /// - the parenthesized call `(d.display)(..)` forwards its `..args`
    ///   faithfully: a format arg reaches `datetime.display`
    ///   (`[year]`→`2026`, `[month repr:long]`→`January`), and the no-arg
    ///   case takes the native default (`2026-01-02`).
    ///
    /// So the closure forwards — but **not through an unchanged call site**.
    /// "Plate code is unchanged for the display path" does not hold: every
    /// `card.on.display("…")` must become `(card.on.display)("…")`. The go
    /// decision must budget that plate edit (and the migration-guide entry).
    #[test]
    fn spike_990_dict_display_needs_parens_then_forwards_args() {
        // Method sugar on the dict field is rejected — the unchanged-plate
        // premise fails here.
        let sugar = compile_frame_text(&format!("{VALUE_OBJECT}#d.display(\"[year]\")"))
            .expect_err("dict method sugar must be a compile error on Typst 0.15");
        assert!(
            sugar.contains("cannot directly call dictionary keys as functions"),
            "the failure is Typst's dict-key-call restriction, not something else: {sugar}"
        );

        // The parenthesized call forwards args faithfully — same closure, a
        // format arg reaches the native `datetime.display`.
        assert_eq!(
            compile_frame_text(&format!("{VALUE_OBJECT}#(d.display)(\"[year]\")"))
                .expect("parenthesized call compiles")
                .trim(),
            "2026",
            "the `[year]` format arg forwards through the closure"
        );
        assert_eq!(
            compile_frame_text(&format!("{VALUE_OBJECT}#(d.display)(\"[month repr:long]\")"))
                .expect("parenthesized call compiles")
                .trim(),
            "January",
            "a different format arg yields a different result — args are forwarded, not ignored"
        );
        // The no-arg default-format case the spike calls out explicitly.
        assert_eq!(
            compile_frame_text(&format!("{VALUE_OBJECT}#(d.display)()"))
                .expect("no-arg call compiles")
                .trim(),
            "2026-01-02",
            "the no-arg call forwards an empty spread and takes datetime's default format"
        );
    }

    /// #990 spike 5 (the last go/no-go gate) — **the paren-call form is NOT
    /// uniform across the value-object dict and a native `datetime`; the mixed
    /// call site needs a normalization shim.**
    ///
    /// The value-object migration parenthesizes every date `.display(` call
    /// site — including inside the vendored `display-date` helper. But that
    /// helper also receives a **native** `datetime` (both target quills fall
    /// back to `datetime.today()` for a blank date:
    /// `usaf_memo/.../frontmatter.typ:45`, `cmu_letter/plate.typ:9`), so the
    /// parenthesized call would have to dispatch on *both* shapes. It cannot:
    /// grabbing `.display` off a native datetime without calling it — the
    /// `(dt.display)` the dict needs — is a hard compile error ("cannot access
    /// fields on type datetime"), because a native datetime exposes `display`
    /// only as method-call sugar, not as a first-class field. Spike 1's paren
    /// hint holds *only on a dict*.
    ///
    /// So a uniform paren edit is impossible at the mixed site. The migration
    /// instead dispatches on `type(date)` in `display-date`: `datetime` keeps
    /// `date.display(pattern)` (native sugar, `str`); the value-object dict
    /// takes `(date.display)(pattern)` (the closure, region-bearing `content`).
    #[test]
    fn spike_990_native_datetime_rejects_the_paren_display_grab() {
        const NATIVE: &str = "#set page(width: 400pt, height: 400pt, margin: 20pt)\n\
             #let dt = datetime(year: 2026, month: 1, day: 2)\n";
        // Grabbing `.display` off a native datetime is a compile error — so the
        // dict's paren form does not carry over to the today() fallback.
        let err = compile_frame_text(&format!("{NATIVE}#(dt.display)(\"[year]\")"))
            .expect_err("the paren grab on a native datetime must be a compile error");
        assert!(
            err.contains("cannot access fields on type datetime"),
            "the failure is the native-datetime field-access restriction: {err}"
        );
        // Native method sugar still works on a datetime — the branch the shim
        // keeps for the today() fallback.
        assert_eq!(
            compile_frame_text(&format!("{NATIVE}#dt.display(\"[year]\")"))
                .expect("native method sugar compiles on a datetime")
                .trim(),
            "2026",
            "a native datetime keeps method-call sugar"
        );
    }

    /// #990 spike 2 (go/no-go gate #2) — **`text()` over a programmatic string
    /// stamps its glyphs with the constructing node's span, which classifies
    /// into a recorded segment-less window.**
    ///
    /// This is the mechanism the whole design turns on: the `display:` closure
    /// returns `text(datetime(..).display(..))` — *content*, not a string — so
    /// its glyphs are born at the `text(..)` node's lexical site inside the
    /// generated helper, not at whatever reference laundered the value. The
    /// worry is that `text(str)` output might carry a **detached** span
    /// (`Anonymous`, like a decoration line or list marker), attributable to no
    /// field. It does not: every glyph carries one uniform, resolvable span —
    /// the `text(..)` call node — and a segment-less `FieldWindow` over that
    /// node surfaces one whole-placement region, exactly like a scalar site.
    ///
    /// Driven on the plate here (the design's site is the generated helper, but
    /// containment classification is file-agnostic — a plate window and a
    /// helper window resolve identically); the end-to-end shipping-API view is
    /// `tests/content_regions.rs`.
    #[test]
    fn spike_990_text_over_programmatic_string_classifies_into_recorded_window() {
        const PLATE: &str = "#set page(width: 400pt, height: 400pt, margin: 20pt)\n\
            #text(datetime(year: 2026, month: 1, day: 2).display(\"[year]\"))\n";
        let q = quill(
            "quill:\n  name: spike_990_text\n  version: 0.1.0\n  backend: typst\n  \
             description: text() span attribution spike\ntypst:\n  plate_file: plate.typ\n",
            PLATE,
        );
        let plate = crate::read_plate(&q).expect("plate");
        let world = QuillWorld::new(&q, &plate).expect("world");
        let (doc, _) = compile_document(&world).expect("compile");
        let main_id = world.main();
        let src = world.source(main_id).expect("main source");
        let text = src.text().to_string();

        // The `text(..)` call's byte window in the plate — the segment-less
        // window a `date_object` sibling of `content_block` would record.
        let start = text.find("text(").expect("the text() call");
        let end = text.rfind(')').expect("its close paren") + 1;
        let window_range = start..end;

        // Part 1: the glyphs' spans are non-detached, uniform, and resolve into
        // that window. An empty helper stands in — no glyph resolves there.
        let helper = Source::new(QuillWorld::helper_fid("lib.typ"), String::new());
        let cls = Classifier::new(&world, &helper, &[]);
        let mut spans = Vec::new();
        for p in doc.pages() {
            collect_spans(&p.frame, &mut spans);
        }
        assert!(!spans.is_empty(), "the date renders at least one glyph");
        for span in &spans {
            assert!(!span.is_detached(), "date glyphs are not detached ink");
            let (file, range) = cls
                .resolve_range(*span)
                .expect("a date glyph span resolves to a source range");
            assert_eq!(file, main_id, "the span resolves into the plate, not elsewhere");
            assert!(
                window_range.start <= range.start && range.end <= window_range.end,
                "the constructing `text(..)` node's span nests in the recorded window: \
                 {range:?} ⊄ {window_range:?}"
            );
        }

        // Part 2: a segment-less window over that node yields one
        // whole-placement region — the same shape a scalar site produces.
        let windows = vec![FieldWindow {
            path: "issued".to_string(),
            file: main_id,
            range: window_range,
            segments: vec![],
        }];
        let regions = scan(&doc, &world, &helper, &windows);
        let issued: Vec<_> = regions.iter().filter(|r| r.field == "issued").collect();
        assert_eq!(
            issued.len(),
            1,
            "the recorded window surfaces exactly one region: {regions:?}"
        );
        assert!(
            issued[0].rect[2] - issued[0].rect[0] > 0.0
                && issued[0].rect[3] - issued[0].rect[1] > 0.0,
            "the date region has positive area: {:?}",
            issued[0].rect
        );
    }

    /// #990 spike 3 — **`!= none` guards are invariant across the emission
    /// change.** A present date's zero stays `none` and its value migrates from
    /// a native `datetime` to a dict; both are `!= none`, so existing
    /// `#if data.issued != none` guards keep the same branch. Pins the three
    /// cases: native datetime, value-object dict, and the blank `none`.
    #[test]
    fn spike_990_none_guard_is_invariant_across_value_object_and_blank() {
        let out = compile_frame_text(
            "#set page(width: 400pt, height: 400pt, margin: 20pt)\n\
             DT#(datetime(year: 2026, month: 1, day: 2) != none)|\
             OBJ#((value: 1, display: (..a) => none) != none)|\
             NONE#(none != none)",
        )
        .expect("guard expressions compile");
        assert!(out.contains("DTtrue"), "a native datetime is != none: {out}");
        assert!(
            out.contains("OBJtrue"),
            "a value-object dict is != none, so present-date guards are untouched: {out}"
        );
        assert!(
            out.contains("NONEfalse"),
            "a blank date stays none, so blank-date guards are untouched: {out}"
        );
    }

    /// #990 spike 4 — **page hashes are unmoved when ink is identical.** Today a
    /// date's `.display("[year]")` interpolates a `str` into markup; the design
    /// wraps the same glyphs in `text(..)` (content). The #795/#801
    /// page-fingerprint is pixels-not-spans, so the two must hash identically —
    /// the emission change moves ink *provenance*, never ink. Asserted, not
    /// assumed.
    #[test]
    fn spike_990_text_wrapper_preserves_page_hash() {
        const YAML: &str = "quill:\n  name: spike_990_hash\n  version: 0.1.0\n  \
            backend: typst\n  description: page-hash invariance spike\ntypst:\n  \
            plate_file: plate.typ\n";
        let page_hash = |plate: &str| -> Vec<u128> {
            let q = quill(YAML, plate);
            let plate = crate::read_plate(&q).expect("plate");
            let world = QuillWorld::new(&q, &plate).expect("world");
            let (doc, _) = compile_document(&world).expect("compile");
            crate::page_hashes(&doc)
        };
        let bare = page_hash(
            "#set page(width: 400pt, height: 400pt, margin: 20pt)\n\
             #(datetime(year: 2026, month: 1, day: 2).display(\"[year]\"))\n",
        );
        let wrapped = page_hash(
            "#set page(width: 400pt, height: 400pt, margin: 20pt)\n\
             #text(datetime(year: 2026, month: 1, day: 2).display(\"[year]\"))\n",
        );
        assert_eq!(
            bare, wrapped,
            "wrapping identical glyphs in text() must not move the page fingerprint"
        );
    }
}