tsv_svelte 0.8.0

Svelte formatter and parser compatible with Svelte's parse() — part of tsv
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
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
// Svelte printer - converts internal AST back to formatted source code
//
// ## Architecture
//
// This module is organized by concern to support future expansion:
//
// - **mod.rs** (this file): Core Printer struct and root-level printing orchestration
// - **nodes/**: Node-specific printing (elements, expressions, control flow, etc.)
// - **text.rs**: Text-analysis predicates (leading/trailing whitespace, blank lines)
// - **script_style.rs**: Script and style section printing
// - **attributes.rs**: HTML attribute and directive printing
// - **classification/**: HTML element classification adapters
//
// ## Design Principles
//
// 1. **Match Prettier**: Output matches prettier-plugin-svelte for compatibility
// 2. **Preserve Semantics**: Never change HTML whitespace rendering semantics
// 3. **Source Layout**: Preserve authorial intent via inline run grouping
// 4. **Modularity**: Each module has single responsibility for future maintainability

mod attributes;
mod classification;
mod frozen_body;
#[cfg(test)]
mod fused_spans_tests;
mod helpers;
mod lifted_runs;
mod nodes;
mod script_style;
mod text;

use crate::ast::{self, FragmentNode};
use nodes::AttrGaps;
use smallvec::SmallVec;
use std::cell::{Cell, OnceCell, RefCell};
use std::fmt::Write as _;
use std::ops::{Index, IndexMut};
use tsv_lang::doc::DocBuf;
use tsv_lang::doc::arena::{DocArena, DocId, GroupId};
use tsv_lang::printing::LineBreaks;
use tsv_lang::{
    Comment, CommentFreeWindow, EmbedContext, INDENT, LayoutMode, OutputBuffer, Span, TAB_WIDTH,
    comments_in_source_from, comments_on_page_from, comments_to_emit_from,
    has_comments_on_page_from, has_comments_to_emit_from, is_format_ignore_directive,
    is_format_ignore_range_end, is_format_ignore_range_start, is_honored_format_ignore,
    is_region_end_marker,
};
use tsv_lang::{FxHashMap, FxHashSet};
use tsv_ts::ast::{Expression, ExpressionKind};

/// A buffered run of comments from one gap — collected rather than iterated because the
/// callers ask two questions of it (how does each one lay out? and how did the run end?).
/// Mirrors `tsv_ts`'s `CommentVec`, which this crate can't see (`pub(crate)` there).
pub(in crate::printer) type CommentRun<'a> = SmallVec<[&'a Comment; 8]>;

/// A root section the printer lifts out of the fragment and prints at its canonical position.
/// A fragment comment travels with the nearest one that follows it in source order
/// ([`Printer::classify_fragment_comment`]), or stays in the template (`None` there).
#[derive(Debug, Clone, Copy, PartialEq)]
enum HoistedSection {
    Options,
    ModuleScript,
    InstanceScript,
    Style,
}

impl HoistedSection {
    /// The hoisted sections in canonical print order. **The single enumeration of what
    /// hoists**: [`root_sections`] maps over it, [`Self::slot`] indexes into it (the agreement
    /// is asserted at compile time below), and [`HoistedComments`] is laid out by it — so the
    /// comment-classification table ([`Printer::classify_fragment_comment`]) and the
    /// range-slice cuts ([`Printer::build_ignore_range_doc`], via `print_root`'s
    /// `hoisted`) read one list, and a section kind cannot join one and silently miss the
    /// other (a kind the cut missed would re-open the duplicate-section emit for exactly that
    /// kind).
    const ALL: [Self; 4] = [
        Self::Options,
        Self::ModuleScript,
        Self::InstanceScript,
        Self::Style,
    ];

    /// This section's index into [`Self::ALL`].
    const fn slot(self) -> usize {
        match self {
            Self::Options => 0,
            Self::ModuleScript => 1,
            Self::InstanceScript => 2,
            Self::Style => 3,
        }
    }

    /// The section's span in `root`, `None` when the component has no such section.
    fn span_in(self, root: &ast::Root<'_>) -> Option<Span> {
        match self {
            Self::Options => root.options.as_ref().map(|s| s.span),
            Self::ModuleScript => root.module.as_ref().map(|s| s.span),
            Self::InstanceScript => root.instance.as_ref().map(|s| s.span),
            Self::Style => root.css.as_ref().map(|s| s.span),
        }
    }
}

// `slot` and `ALL` are two spellings of one order; a drift between them is a compile error,
// not a debug-build assertion some fixture has to reach.
const _: () = {
    let mut k = 0;
    while k < HoistedSection::ALL.len() {
        assert!(
            HoistedSection::ALL[k].slot() == k,
            "`HoistedSection::slot` disagrees with `ALL`"
        );
        k += 1;
    }
};

/// The fragment comments one hoisted section prints: the run written directly ABOVE it
/// (`leading`, printed before the section in source order) and the region-end marker written
/// directly BELOW it (`trail`, printed after — [`Printer::region_end_trails`]).
#[derive(Default)]
struct SectionComments {
    leading: Vec<usize>,
    trail: Option<usize>,
}

/// [`SectionComments`] per hoisted section, indexed by the [`HoistedSection`] itself
/// ([`HoistedSection::ALL`] order).
#[derive(Default)]
struct HoistedComments([SectionComments; 4]);

impl Index<HoistedSection> for HoistedComments {
    type Output = SectionComments;

    fn index(&self, section: HoistedSection) -> &SectionComments {
        &self.0[section.slot()]
    }
}

impl IndexMut<HoistedSection> for HoistedComments {
    fn index_mut(&mut self, section: HoistedSection) -> &mut SectionComments {
        &mut self.0[section.slot()]
    }
}

impl HoistedComments {
    /// Which of the root fragment's `len` nodes travel with a hoisted section — a leading run
    /// or a region-end trail — indexed like the nodes.
    fn travelling(&self, len: usize) -> Vec<bool> {
        let mut travels = vec![false; len];
        for section in &self.0 {
            for &i in section.leading.iter().chain(&section.trail) {
                travels[i] = true;
            }
        }
        travels
    }
}

/// Append `ch` spelled as an uppercase-hex character reference (`&#xA0;`) — the one spelling
/// every respell the format path makes uses: a character the next parse would otherwise trim
/// from the document's end ([`Printer::template_tail_respell`], `Printer::lifted_runs_source`),
/// and the first character after a glued seam that would otherwise complete a reference the
/// text before it left open (`lifted_runs::glued_seam_respell`, written by the lifted-run
/// rewrite and by [`Printer::build_ignore_range_doc`]).
fn push_char_reference(out: &mut String, ch: char) {
    let _ = write!(out, "&#x{:X};", u32::from(ch));
}

/// Whether each hoisted section is frozen by a format-ignore directive
/// ([`Printer::section_is_frozen`]), in [`HoistedSection::ALL`] order. `<svelte:options>` is
/// never frozen.
type FrozenSections = [bool; 4];

/// The four root sections in canonical print order ([`HoistedSection::ALL`]), each with its
/// span when the component has it.
fn root_sections(root: &ast::Root<'_>) -> [(Option<Span>, HoistedSection); 4] {
    HoistedSection::ALL.map(|section| (section.span_in(root), section))
}

/// The root fragment's `format-ignore` ranges, paired once per document
/// ([`Printer::ignore_ranges`]) — the one pairing the freeze
/// ([`Printer::print_root_fragment`]), the lifted-run rewrite, the comment classification and
/// the region-end trail all read, so they cannot drift on which nodes a range holds.
///
/// A `…-start` opens a range when none is open, and the first `…-end` after it closes it: a
/// start inside an open range is part of the frozen slice, an end with no range open is an
/// ordinary comment, and a start no end follows (an unclosed one) freezes nothing — tsv
/// prints it as an ordinary comment rather than letting it pin everything after it. One
/// forward pass; every read is a lookup, where scanning from each start for its end is
/// quadratic in a template of unclosed starts.
struct IgnoreRanges {
    /// Each node's range marker ([`range_marker`]), `None` for every other node.
    markers: Vec<Option<RangeMarker>>,
    /// Each range as its (start marker, end marker) fragment indices, in source order.
    pairs: SmallVec<[(usize, usize); 2]>,
    /// The address of the fragment's first node — which fragment this pairs, so a read against
    /// another fails a debug assertion rather than answering for the wrong nodes.
    nodes_addr: usize,
}

impl IgnoreRanges {
    fn new(nodes: &[FragmentNode<'_>], source: &str) -> Self {
        let markers: Vec<Option<RangeMarker>> = nodes
            .iter()
            .map(|n| match n {
                FragmentNode::Comment(c) => range_marker(c, source),
                _ => None,
            })
            .collect();
        let mut pairs = SmallVec::new();
        let mut open = None;
        for (i, marker) in markers.iter().enumerate() {
            match (marker, open) {
                (Some(RangeMarker::Start), None) => open = Some(i),
                (Some(RangeMarker::End), Some(start)) => {
                    pairs.push((start, i));
                    open = None;
                }
                _ => {}
            }
        }
        Self {
            markers,
            pairs,
            nodes_addr: nodes.as_ptr() as usize,
        }
    }

    /// The end marker of the range the start marker at `i` opens — `None` when the node at `i`
    /// opens none.
    fn end_of(&self, i: usize) -> Option<usize> {
        self.pairs
            .binary_search_by_key(&i, |&(start, _)| start)
            .ok()
            .map(|k| self.pairs[k].1)
    }

    /// Whether the node at `i` sits **inside** a range — past its start marker, through its end
    /// marker, the slice the freeze prints verbatim.
    fn contains(&self, i: usize) -> bool {
        let k = self.pairs.partition_point(|&(start, _)| start < i);
        k > 0 && i <= self.pairs[k - 1].1
    }
}

/// The per-node facts [`Printer::classify_fragment_comment`] reads, taken for the whole
/// fragment in one pass — so classifying every comment of a document is linear. Asked per
/// comment instead, the range and barrier scans each walked the fragment again, which is
/// quadratic in a comment-heavy template.
struct CommentScan<'r> {
    /// The fragment's range markers and which nodes sit inside a range.
    ranges: &'r IgnoreRanges,
    /// The start of the first node after each one that pins a comment there to the template —
    /// a node other than whitespace text or an ordinary comment (a range marker is one).
    next_barrier: Vec<Option<u32>>,
}

impl<'r> CommentScan<'r> {
    fn new(fragment: &ast::Fragment<'_>, ranges: &'r IgnoreRanges) -> Self {
        let nodes = &fragment.nodes;
        let mut next_barrier = vec![None; nodes.len()];
        let mut barrier = None;
        for i in (0..nodes.len()).rev() {
            next_barrier[i] = barrier;
            let pins = match &nodes[i] {
                FragmentNode::Text(t) => !t.is_collapsible_ws_only,
                FragmentNode::Comment(_) => ranges.markers[i].is_some(),
                _ => true,
            };
            if pins {
                barrier = Some(nodes[i].span().start);
            }
        }
        Self {
            ranges,
            next_barrier,
        }
    }
}

/// A format-ignore **range marker**'s kind — the `…-start` / `…-end` pair that brackets a
/// frozen template region.
#[derive(Clone, Copy, PartialEq, Eq)]
enum RangeMarker {
    Start,
    End,
}

/// Classify `comment` as a format-ignore range marker; `None` for every ordinary comment.
///
/// The one spelling of the marker test — the range pairing ([`IgnoreRanges`], which the freeze
/// scan, the comment-classification barrier and the lifted-run rewrite all read) and the
/// region-end trail's exclusion ask it here, so they cannot drift on which comments count as
/// markers. A free function (not a method) because [`IgnoreRanges::new`] needs `source` alone.
fn range_marker(comment: &ast::HtmlComment, source: &str) -> Option<RangeMarker> {
    let content = comment.content(source);
    if is_format_ignore_range_start(content) {
        Some(RangeMarker::Start)
    } else if is_format_ignore_range_end(content) {
        Some(RangeMarker::End)
    } else {
        None
    }
}

/// A head's content doc plus whether that content **opens on its own line** — the pair every
/// head builder hands back, and the one argument [`Printer::build_prefixed_head_doc`]
/// assembles from.
///
/// **The rationale every head builder shares, stated once here.** The verdict comes back
/// OUT of the builder rather than going in, because it selects the head's whole layout
/// (space-less prefix, no tail hug, already broken) and those parts must never disagree —
/// a hugged one would pull the run flush against the `{`. Threading them as separate values
/// let a caller pass one and forget the other; as one value there is nothing to forget, and
/// a caller that can't supply the flag can't supply a wrong one.
///
/// **Two things open a head's content on its own line, and the layout is the same for both**
/// ([`Printer::head_layout`]):
///
/// - a **freeze** — flush against the `{` a directive sits in a placement the floor calls
///   inert, so the freeze it earned would be gone on the next pass;
/// - an **own-line leading `//`** — the comment leads the head's VALUE, so where the author
///   put it is authoring signal (conformance_prettier.md §Comment Position Philosophy) and
///   pulling it up onto the prefix's line would relocate it.
///
/// The first is why the field existed; the second is the ordinary form the freeze turned
/// out to be a special case of.
///
/// `doc` is the head's content in its **final shape** — an own-line one is already broken onto
/// its own indented lines ([`Printer::indent_own_line_head`]), because the block heads consume
/// it directly rather than through the prefixed-head assembler.
///
/// `ends_with_line_comment` records that the content's last emitted comment was a **line**
/// comment, whose doc ends in a `hardline` that already drops the closing token to the next
/// line. Every consumer that would otherwise supply its own break must skip it, or the two
/// breaks stack into a blank line — the three closer assemblers
/// ([`Printer::build_prefixed_head_doc`], `wrap_in_block_structure`,
/// `build_block_head`) all read it for exactly that. It is set by
/// [`Printer::trailing_comment_docs`] off the run it emits rather than re-derived from
/// source by each consumer, because the builder that *emitted* the run is the one that knows.
///
/// `owes_continuation_indent` is the one field that qualifies `doc`'s final-shape claim, and
/// only for the head whose *caller* chooses the layout ([`Printer::build_expression_content_with_comments`],
/// the unprefixed `{…}`). It says a leading line comment hangs this content one level in
/// ([`HeadLayout::HangsAfterOpen`]) and the builder could not apply the indent
/// itself, because its caller may already supply one: an assembler that block-wraps the
/// content (`wrap_in_block_structure`) has paid the debt, and one that hugs its braces has
/// not. Every builder that owns its own assembly applies the indent in place and returns
/// `false` — the debt is always settled exactly once. `false` for an own-line head, whose
/// [`Printer::indent_own_line_head`] is the same indent one level up.
#[derive(Clone, Copy)]
pub(in crate::printer) struct HeadExpr {
    pub(in crate::printer) doc: DocId,
    pub(in crate::printer) layout: HeadLayout,
    pub(in crate::printer) ends_with_line_comment: bool,
    pub(in crate::printer) owes_continuation_indent: bool,
}

/// An island value's trailing run ([`Printer::value_trailing_docs`]).
pub(in crate::printer) struct ValueTrailing {
    /// The run's docs, led by the embed end when there is one.
    pub(in crate::printer) docs: DocBuf,
    /// The `[from, to)` gap holds a comment: the run prints one after the value.
    pub(in crate::printer) gap_run: bool,
    /// The run's last comment is a `//` ([`HeadExpr::ends_with_line_comment`]).
    pub(in crate::printer) ends_with_line_comment: bool,
    /// The embed end ahead of the run, when the value may defer a run to its end — an
    /// `if_break_with_id` on it breaks exactly when a run flushed there.
    pub(in crate::printer) embed_end: Option<GroupId>,
}

/// How a braced head's content sits between its delimiters — the three states
/// [`Printer::head_layout`] resolves, as one value rather than two bools, because the fourth
/// combination (the opening literal sheds its space but the closer hugs) is not a shape.
///
/// The two hanging arms differ in **one** thing, and deliberately only that: where the run's
/// first comment sits. Everything downstream of it — the content's indent, the dangling
/// closer, the [`Printer::trailing_comment_docs`] `closer_owns_break` answer — is shared, so
/// the two authorings of one head produce the same geometry around a comment in two places.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(in crate::printer) enum HeadLayout {
    /// Nothing in the gap forces a break: the content stays on the head's line and the closer
    /// hugs it (`{@html expr}`).
    Inline,
    /// A `//` the author wrote **after the opening literal**: it keeps that line, the value
    /// hangs one level in, and the closer drops to the head's own column
    /// (`{@html // c⏎\texpr⏎}`).
    HangsAfterOpen,
    /// The content opens on its **own** line — a freeze, or a `//` the author put on its own
    /// line. As `HangsAfterOpen`, plus: the opening literal sheds its trailing space (the
    /// content supplies its own hardline) and the whole run hangs with the value
    /// (`{@html⏎\t// c⏎\texpr⏎}`).
    OpensOwnLine,
}

impl HeadLayout {
    /// Whether the content begins on a line of its own — the opening literal sheds its
    /// trailing space, and an unprefixed `{` needs no separator before the run.
    pub(in crate::printer) const fn opens_own_line(self) -> bool {
        matches!(self, Self::OpensOwnLine)
    }

    /// Whether anything **indents** this content — which is the same question as whether the
    /// closer drops to its own line, and as [`Printer::trailing_comment_docs`]'s
    /// `closer_owns_break`. One accessor so a caller cannot answer the three differently.
    pub(in crate::printer) const fn indents_content(self) -> bool {
        !matches!(self, Self::Inline)
    }
}

/// The open fragment build [`Printer::enter_fragment`] returns: restores
/// [`Printer::fragment_depth`] to its outer value when dropped.
pub(crate) struct FragmentScope<'p> {
    depth: &'p Cell<usize>,
    outer: usize,
}

impl Drop for FragmentScope<'_> {
    fn drop(&mut self) {
        self.depth.set(self.outer);
    }
}

/// Printer state for building output
pub(crate) struct Printer<'a> {
    /// Output buffer
    buffer: OutputBuffer,
    /// Current indentation level
    pub(crate) indent_level: usize,
    /// Embedding context (layout mode, offsets)
    embed: EmbedContext,
    /// Arena allocator for doc nodes (borrowed so a multi-file driver can reuse
    /// one arena across files; see [`DocArena::reset`]).
    pub(crate) arena: &'a DocArena,
    /// Source code (needed for preserving whitespace semantics)
    pub(crate) source: &'a str,
    /// Comments from scripts and template expressions
    comments: &'a [Comment],
    /// Whether any of `comments` is owned by a node (`owned_by_node`). Computed once
    /// per document at construction and handed to `tsv_ts` via `ts_inputs()`, so the
    /// embedded owned-comment path short-circuits per `{expr}` without an O(comments)
    /// rescan there. `owned_by_node` is set during the eager parse of embedded TS, so
    /// it is already final before printing.
    has_owned_comments: bool,
    /// Whether any of `comments` is a `format-ignore` directive. Computed once per document
    /// at construction and handed to `tsv_ts` via `ts_inputs()`, so the embedded
    /// `member_gap_frozen` short-circuits per `{expr}` without an O(comments)
    /// rescan there — the same per-`{expr}` trap `has_owned_comments` documents.
    has_format_ignore: bool,
    /// The document's line-break table with its verdict (`tsv_lang::printing::LineBreaks`):
    /// the verdict is taken once at construction, the table is filled only if a line
    /// question falls back to it, and every embedded island borrows it through
    /// [`Self::line_table`].
    line_breaks: LineBreaks<'a>,
    /// Whether a wrapped block-tag head may dangle its `}` (and, later, expand its
    /// body) in the current context. True almost everywhere — including inside
    /// inline elements / components, where the body-expand is render-safe because a
    /// block's *body-boundary* whitespace is non-significant (the sibling boundary,
    /// e.g. `</span>{#if …}`, stays hugged regardless, since the expand never injects
    /// whitespace there). Set false only while building the content of a
    /// whitespace-significant element (`<pre>` / `<textarea>`), where every injected
    /// whitespace would render. Save/restore discipline:
    /// `build_whitespace_sensitive_content_doc` sets it false for its children and
    /// restores the previous value on the way out (so nested contexts reset
    /// correctly).
    block_dangle_allowed: Cell<bool>,
    /// The nesting the printer's own parse of a nested `<script>` / `<style>` body starts
    /// from ([`ast::Root::nested_raw_text_nesting`]), so that parse shares the
    /// document's depth budget.
    pub(crate) nested_raw_text_nesting: Cell<u32>,
    /// Whether the fragment being built is a `<textarea>`'s content — RCDATA, which Svelte
    /// reads with `read_sequence`, where a `{/` opens an expression rather than closing a
    /// block. Read by [`Printer::build_text_expression_tag_doc`]; set (and restored) by the
    /// whitespace-sensitive element builder around a `<textarea>`.
    in_textarea_content: Cell<bool>,
    /// How many fragments' children are being built right now — the root fragment counts
    /// one, each container body inside it one more. A container's body is indented one level
    /// past the container (the uniform "each container adds a level" model — element and
    /// component bodies, every block section, special elements), so while a fragment's
    /// children are being built this is the indent level their bodies are EXPECTED to render
    /// at: the level a nested `<style>`'s CSS — written, not built as a doc — is formatted at
    /// ([`Printer::body_indent_level`]). It is a count, not a measurement: a parent that hugs
    /// its content without indenting it (`x<span><style>…</style></span>y`) renders shallower,
    /// which is why `build_nested_style_body_doc` formats a second time one level deeper and
    /// lets the host's renderer place each line rather than trusting this number — except
    /// where the deeper format wraps differently, when the body keeps this count. Maintained
    /// in ONE place, the three fragment builders every child list goes through
    /// ([`Printer::enter_fragment`]), never at the indent sites, so a new container cannot
    /// forget it.
    fragment_depth: Cell<usize>,
    /// The CSS printer's boundary-whitespace precondition over this whole document
    /// (`tsv_css::__private::HostBoundaryScan`), taken on the first `<style>` island that asks and
    /// shared by every other — one whole-source scan per component, however many nested
    /// `<style>` elements it holds. [`Printer::css_host_scan`] is the one reader.
    css_host_scan_cache: Cell<Option<tsv_css::__private::HostBoundaryScan>>,
    /// Span starts of control-flow blocks the root fragment marked as part of a **single-line
    /// inline run** (`{x}{#if c}…{/if}` with no newline). The unified
    /// [`Printer::build_nodes_doc_multiline`] builds these in inline context (long body
    /// inner-breaks) rather than multiline context (body drops to its own line), reproducing
    /// the root's pre-unification `build_nodes_doc` layout (the load-bearing
    /// single-line-run discriminator). Span-keyed, so it scopes to **root-level** runs only —
    /// element-nested blocks (different spans) keep the multiline body-drop divergence (e.g.
    /// `blocks/await/preceding_sibling_body_long`). Populated once by
    /// [`Printer::mark_root_inline_run_blocks`] before the root content is built.
    /// Hashed by `tsv_lang`'s `FxHasher` rather than SipHash — only
    /// `insert`/`contains`/`clear` are used, never iteration, so the hasher is
    /// unobservable (see `tsv_lang::hash`'s module docs).
    root_inline_run_block_starts: RefCell<FxHashSet<u32>>,
    /// The comment-free window this printer's searches drew (`tsv_lang::CommentFreeWindow`).
    /// Every comment lookup here reads it ahead of the search, through the
    /// `comments_*_between` / `has_*_between` wrappers below — never the free function
    /// over `self.comments` — and every island `tsv_ts` printer this one constructs starts
    /// from it and hands its own back ([`Self::ts_inputs`]), since the islands share this
    /// printer's comment array. On a real Svelte corpus three of this printer's own wide
    /// asks in four, and nine of the islands' first searches in ten, lay inside a window
    /// already drawn.
    comment_free_gap: CommentFreeWindow<'a>,
    /// Each fragment's extent and content-edge answer (`nodes::IndexedFragment`), keyed by the
    /// address of its first node — indexed once per document, top down, by
    /// [`Printer::index_fragment_edges`], since a block tag's body reads its edges from where the
    /// tag sits in its parent. A run of a fragment finds its fragment by address.
    fragment_edges: RefCell<std::collections::BTreeMap<usize, nodes::IndexedFragment>>,
    /// Each node slice's glue flags (`nodes::FragmentGlue`), computed on first ask.
    fragment_glue_cache: RefCell<FxHashMap<(usize, usize), std::rc::Rc<nodes::FragmentGlue>>>,
    /// The root fragment's `format-ignore` range pairing ([`Self::ignore_ranges`]), on first ask.
    ignore_ranges: OnceCell<IgnoreRanges>,
}

#[cfg(test)]
thread_local! {
    /// The tests' switch behind [`fuses_source_spans`].
    static FUSED_SOURCE_SPANS_OFF: Cell<bool> = const { Cell::new(false) };
}

/// Whether a builder may answer a construct that prints as its own source bytes with ONE
/// span over it, instead of assembling the construct's doc part by part.
///
/// Always `true` outside the crate's tests, where it folds away. Every such answer is an
/// optimization with no output of its own, so the tests turn it off
/// (`without_fused_source_spans`) to grade each one against the general builder it
/// stands in for.
#[inline]
pub(in crate::printer) fn fuses_source_spans() -> bool {
    #[cfg(test)]
    {
        !FUSED_SOURCE_SPANS_OFF.get()
    }
    #[cfg(not(test))]
    {
        true
    }
}

/// Run `f` with every fused-span answer declined ([`fuses_source_spans`]), so the general
/// builders print everything. The previous setting comes back when `f` returns or unwinds.
#[cfg(test)]
pub(crate) fn without_fused_source_spans<R>(f: impl FnOnce() -> R) -> R {
    struct Restore(bool);
    impl Drop for Restore {
        fn drop(&mut self) {
            FUSED_SOURCE_SPANS_OFF.set(self.0);
        }
    }
    let _restore = Restore(FUSED_SOURCE_SPANS_OFF.replace(true));
    f()
}

/// The span of an identifier that is a **plain reference**: a variable name with no `?`
/// and no binding extra (a type annotation, a decorator), spelled in plain ASCII with no
/// escape, whose node covers the name and nothing more. Such a node prints as those bytes
/// (`tsv_ts`'s identifier fast path), one column a byte.
///
/// `extra.is_none()` is the load-bearing clause: a typed block binding (`{#each xs as x: T}`)
/// keeps its span on the bare name with the annotation as a sibling, so nothing about the
/// span says the node prints more than its name.
fn plain_reference_span(id: &tsv_ts::ast::Identifier<'_>) -> Option<Span> {
    (id.name_plain_ascii
        && id.escaped_name.is_none()
        && !id.optional
        && id.extra.is_none()
        && id.span.end - id.span.start == u32::from(id.name_len))
    .then_some(id.span)
}

/// The span of an expression that is a **plain path** — `name`, or `name.prop` with the
/// two names one `.` apart, each a plain reference ([`plain_reference_span`]) — when the
/// expression's own span is exactly that.
///
/// A plain path prints as its own source bytes: a name is its node's doc, and a node whose
/// span is the path alone has no paren shell and no gap, so nothing between its ends can
/// hold a comment or a byte the printer respells. The dotted form is as far as that is
/// taken. A lone lookup off a bare identifier is a member chain `tsv_ts` builds as one
/// flat run with no break point (`lone_lookup_off_bare_base`), where a longer chain
/// (`a.b.c`), a `this`, `super` or `import.meta` base and a private lookup (`a.#b`) each
/// take a group that can break before the lookup, and so have a second printed form. The
/// remaining exclusions are conservative, kept so the gate names the one shape whose doc
/// is provably a single flat run: an optional lookup (`a?.b`) and a trailing `!` stay in
/// that flat arm, and a computed lookup breaks only inside its brackets. `!computed` and
/// the span equality below imply each other for `a[b]` — its names are also one byte
/// apart — so either one alone declines it, never neither (the span would stop short of
/// the `]`). The one thing a path's doc can carry from
/// outside the span is a block comment the path **owns** (`docs/comments.md` §Owned
/// comments), which sits glued ahead of it — a caller that prints the span instead of
/// building the doc owes the proof that none does.
pub(in crate::printer) fn plain_path_span(expr: &Expression<'_>) -> Option<Span> {
    let path = match &expr.kind {
        ExpressionKind::Identifier(id) => plain_reference_span(id)?,
        ExpressionKind::MemberExpression(member) if !member.computed && !member.optional => {
            let (ExpressionKind::Identifier(object), ExpressionKind::Identifier(property)) =
                (&member.object.kind, &member.property.kind)
            else {
                return None;
            };
            let object = plain_reference_span(object)?;
            let property = plain_reference_span(property)?;
            // One byte between the two names: the `.`, with no paren, gap or comment.
            if object.end + 1 != property.start {
                return None;
            }
            Span::new(object.start, property.end)
        }
        _ => return None,
    };
    (path == expr.span).then_some(path)
}

impl<'a> Printer<'a> {
    /// A printer over `source`, classifying its lines here (standalone layout) — the
    /// tests' constructor; the format entry points hand [`Self::with_line_breaks`] a
    /// table they took.
    #[cfg(test)]
    pub(crate) fn new(arena: &'a DocArena, source: &'a str, comments: &'a [Comment]) -> Self {
        let line_breaks = LineBreaks::new(source, arena.take_line_breaks_scratch());
        Self::with_line_breaks(
            arena,
            source,
            comments,
            EmbedContext::default(),
            line_breaks,
        )
    }

    /// Create a new printer with the given source, comments, embed context and line table.
    ///
    /// `line_breaks` is the document's one whole-source line table: every embedded island
    /// borrows it (`build_program_doc` for `<script>`/`{expr}` TS,
    /// `tsv_css::__private::format_embedded_in` for `<style>` CSS) — never re-classify per island.
    /// Its table, if a line question ever falls back to it, fills the arena-parked scratch
    /// (one warm table across a multi-file driver's files); `into_string` parks it back.
    /// The caller takes it (`format_svelte_in` classifies the source; the folded entry
    /// point `format_svelte_folded_in` carries the fold's own verdict) so a document is
    /// classified exactly once.
    pub(crate) fn with_line_breaks(
        arena: &'a DocArena,
        source: &'a str,
        comments: &'a [Comment],
        embed: EmbedContext,
        line_breaks: LineBreaks<'a>,
    ) -> Self {
        // The two document-level presence flags come from the one scan `tsv_ts` owns
        // (`PrinterInputs::for_document`); `ts_inputs()` copies them per island.
        let tsv_ts::__private::PrinterInputs {
            has_owned_comments,
            has_format_ignore,
            ..
        } = tsv_ts::__private::PrinterInputs::for_document(source, comments, line_breaks.table());
        Self {
            buffer: OutputBuffer::with_capacity(source.len()),
            indent_level: 0,
            embed,
            arena,
            source,
            comments,
            has_owned_comments,
            has_format_ignore,
            line_breaks,
            block_dangle_allowed: Cell::new(true),
            nested_raw_text_nesting: Cell::new(0),
            in_textarea_content: Cell::new(false),
            fragment_depth: Cell::new(0),
            css_host_scan_cache: Cell::new(None),
            root_inline_run_block_starts: RefCell::new(FxHashSet::default()),
            comment_free_gap: CommentFreeWindow::new(comments),
            fragment_edges: RefCell::new(std::collections::BTreeMap::new()),
            fragment_glue_cache: RefCell::new(FxHashMap::default()),
            ignore_ranges: OnceCell::new(),
        }
    }

    /// Whether `node` is a control-flow block the root marked as part of a single-line inline
    /// run — see [`Printer::root_inline_run_block_starts`]. Read by `build_nodes_doc_multiline`
    /// to build the block in inline (inner-break) rather than multiline (body-drop) context.
    pub(crate) fn is_root_inline_run_block(&self, node: &FragmentNode<'_>) -> bool {
        self.root_inline_run_block_starts
            .borrow()
            .contains(&node.span().start)
    }

    /// Get a reference to the doc arena (convenience for `self.arena`).
    #[inline]
    pub(crate) fn d(&self) -> &DocArena {
        self.arena
    }

    /// Whether a wrapped block-tag head may dangle its `}` in the current context.
    /// See [`Printer::block_dangle_allowed`] for the save/restore discipline.
    #[inline]
    pub(crate) fn block_dangle_allowed(&self) -> bool {
        self.block_dangle_allowed.get()
    }

    /// Set [`Printer::block_dangle_allowed`] to `allowed`, returning the previous
    /// value for the caller to restore. Used by the whitespace-sensitive element
    /// builder to gate the dangle off while building `<pre>` / `<textarea>` content.
    #[inline]
    pub(crate) fn set_block_dangle_allowed(&self, allowed: bool) -> bool {
        self.block_dangle_allowed.replace(allowed)
    }

    /// Whether the fragment being built is a `<textarea>`'s content
    /// ([`Printer::in_textarea_content`]).
    #[inline]
    pub(crate) fn in_textarea_content(&self) -> bool {
        self.in_textarea_content.get()
    }

    /// Open one fragment's child build for [`Printer::fragment_depth`]; the depth returns to
    /// its previous value when the guard drops, on every exit path. Called at the top of the
    /// three fragment builders (`build_nodes_doc_trimmed`, `build_container_content_doc`,
    /// `build_whitespace_sensitive_content_doc`) and nowhere else.
    pub(crate) fn enter_fragment(&self) -> FragmentScope<'_> {
        let outer = self.fragment_depth.get();
        self.fragment_depth.set(outer + 1);
        FragmentScope {
            depth: &self.fragment_depth,
            outer,
        }
    }

    /// The indent level at which the body of an element being built right now is expected to
    /// render: one past the element's own, which is its parent fragment's depth. See
    /// [`Printer::fragment_depth`] for when the element renders shallower than that.
    pub(crate) fn body_indent_level(&self) -> usize {
        self.indent_level + self.fragment_depth.get()
    }

    /// This document's `tsv_css::__private::HostBoundaryScan`, scanned on first use — see
    /// [`Printer::css_host_scan_cache`].
    pub(crate) fn css_host_scan(&self) -> tsv_css::__private::HostBoundaryScan {
        if let Some(scan) = self.css_host_scan_cache.get() {
            return scan;
        }
        let scan = tsv_css::__private::HostBoundaryScan::of(self.source);
        self.css_host_scan_cache.set(Some(scan));
        scan
    }

    /// Write a string to the buffer
    pub(crate) fn write(&mut self, s: &str) {
        self.buffer.write(s);
    }

    /// Write `span` of the source **verbatim** to the buffer.
    ///
    /// The format-ignore seam for a whole `<script>` / `<style>` section: the island's
    /// comments (which `Root.comments` holds) ride out inside the raw slice and never
    /// reach an emitter, so the ledger is told the range is covered. The doc-side
    /// verbatim seams use [`Self::source_span_covering_comments_doc`] (a frozen template node,
    /// a range) and [`Self::verbatim_source_doc`] (a frozen value inside a node).
    pub(crate) fn write_verbatim_span(&mut self, span: Span) {
        #[cfg(feature = "_internal_comment_check")]
        tsv_lang::comment_ledger::record_verbatim_range(self.source, span.start, span.end);

        self.write(span.extract(self.source));
    }

    /// A doc emitting `span` of the source **verbatim** and **layout-opaque** — the doc-side
    /// twin of [`Self::write_verbatim_span`] for a freeze of a JavaScript-level value inside a
    /// node: a braced head's value ([`Self::build_frozen_node_doc`]) and the `{@debug}`
    /// identifier list.
    ///
    /// Opaque to `will_break`, as prettier's `printIgnored` string is. The opacity changes no
    /// layout at these seams: a directive is honored there only on its own line in the head's
    /// gap, so the head opens its own line ([`Self::indent_own_line_head`]) and that hardline,
    /// not the slice, is what breaks the groups around the value. A frozen TEMPLATE node is not
    /// one of them — it takes [`Self::source_span_covering_comments_doc`], whose line breaks
    /// break the fragment holding it.
    pub(crate) fn verbatim_source_doc(&self, span: Span) -> DocId {
        #[cfg(feature = "_internal_comment_check")]
        tsv_lang::comment_ledger::record_verbatim_range(self.source, span.start, span.end);

        self.d().verbatim_source_span(span, self.source)
    }

    /// A doc emitting `span` of the source as an ordinary [`DocId`] source slice — an
    /// interior newline breaks the enclosing group, unlike [`Self::verbatim_source_doc`]'s
    /// layout-opaque one — that also registers every comment inside the span with the
    /// comment ledger as printed by the slice. For a slice whose bytes are printed as written
    /// and can hold comments no comment emitter reaches: a frozen template node (in flow
    /// content and inside `<pre>` alike), and a format-ignore range, whose frozen line breaks
    /// are line breaks in the output, as prettier-plugin-svelte's `literalline` makes them.
    pub(crate) fn source_span_covering_comments_doc(&self, span: Span) -> DocId {
        #[cfg(feature = "_internal_comment_check")]
        tsv_lang::comment_ledger::record_verbatim_range(self.source, span.start, span.end);

        self.d().source_span(span, self.source)
    }

    /// The frozen slice for a node the freeze resolved, **plus the owned-comment claim it
    /// owes** — the Svelte twin of `tsv_ts`'s `build_frozen_node_doc`, and the emitter
    /// every value-head freeze in this printer goes through.
    ///
    /// A block comment glued before the frozen node is *owned* by it, so the slice owes
    /// the claim ([`Self::claim_owned_leading_comment`]). It sits outside the slice's own
    /// span, so widening the slice is not the fix; the claim is. Prettier keeps the
    /// comment right where the author glued it, before the frozen value, and so does this.
    pub(in crate::printer) fn build_frozen_node_doc(&self, span: Span) -> DocId {
        self.claim_owned_leading_comment(self.verbatim_source_doc(span), span.start)
    }

    /// Prepend the block comment **owned** by the node beginning at `start`, when one is
    /// bound there (glued on the token's own line, or — for a JSDoc cast — from the line
    /// above its `(`) — the claim any builder owes that assembles a node's doc itself
    /// instead of routing through `tsv_ts`'s comment-aware expression builder (which
    /// makes the claim via `prepend_owned_leading_comment`).
    ///
    /// Two such builders exist in this printer: the freeze above, and the binding-pattern
    /// printer's object/array delimiter builders (`build_object_braces` /
    /// `build_array_brackets`, reached from [`Printer::build_pattern_doc`]). Both are
    /// docs/comments.md hazard 1 — the comment rides *inside* the doc these replace, and
    /// every gap emitter around it skips owned comments (the to-emit axis), so unless the
    /// builder prints it nothing does.
    ///
    /// ⚠️ The claim belongs to the node whose doc is being **assembled here**, never to a
    /// whole dispatch: two nested nodes can begin at the same offset (an
    /// `AssignmentPattern` and its `left`, a paren-less arrow and its parameter), and a
    /// claim made at both is a double print.
    ///
    /// ⚠️ **The separator is the author's, not a constant** — the same rule, and the same
    /// reason, as `tsv_ts`'s `prepend_owned_leading_comment_at`. Ownership's two producers
    /// bind at two different glues, so a claim that always writes a space is right only for
    /// the glued one: a JSDoc cast owns its comment from the line **above** its `(`, and
    /// pulling that comment up onto the `(`'s line is a relocation the unfrozen path does
    /// not make (`{@const a =⏎/** @type {T} */⏎(b)}` keeps the break, and so does prettier).
    /// Reading the newline off the source keeps the two claims answering with one rule.
    pub(in crate::printer) fn claim_owned_leading_comment(&self, doc: DocId, start: u32) -> DocId {
        if !self.has_owned_comments {
            return doc;
        }
        let Some(comment) = tsv_lang::owned_leading_comment_at(self.source, self.comments, start)
        else {
            return doc;
        };
        let d = self.d();
        let comment_doc = tsv_ts::__private::build_comment_doc(d, comment, &self.ts_inputs());
        let separator = if tsv_lang::printing::has_newline_between_scan(
            self.source.as_bytes(),
            self.line_table(),
            comment.span.end,
            start,
        ) {
            d.hardline()
        } else {
            d.text(" ")
        };
        d.concat(&[comment_doc, separator, doc])
    }

    /// A braced head's **value stage**: the frozen slice when the head's gap resolved a
    /// freeze, else the comment-aware TS expression doc built under `embed`.
    ///
    /// Every braced value in this printer asks exactly this question — the tags
    /// (`{@html …}`, `{@render …}`, `{@const … = …}`), the block heads (`{#if …}`,
    /// `{#each …}`, an `{#each}` key), the attribute `={…}` values, the `{expr}` tag, and
    /// the braced attribute heads (`{...rest}`, `{@attach …}`) — after each has resolved
    /// its own freeze verdict ([`Self::honored_directive_in_gap`]) and its own
    /// [`EmbedContext`]. One spelling, because the frozen arm owes the owned-comment claim
    /// ([`Self::build_frozen_node_doc`], docs/comments.md hazard 1) and a site that
    /// re-spells the branch is a site that can forget it.
    ///
    /// What stays with the caller is what genuinely differs per head, and each difference
    /// is load-bearing, so the bodies around this call are deliberately NOT shared:
    ///
    /// - the **`EmbedContext`** — three distinct recipes. The braced heads (block heads
    ///   and prefixed tags alike) share one, [`Self::head_embed`]; `{@const}`'s init
    ///   inherits the host's Standalone mode so a root binary stays flat under the
    ///   assignment layout; an attribute value starts from [`EmbedContext::default`],
    ///   not the host's.
    /// - the **post-processing** — `remove_lines` for an inline block head,
    ///   [`Self::indent_own_line_head`] for a prefixed head, nothing for the rest. The
    ///   leading-line-comment continuation indent is NOT in this list: it is a property
    ///   of the *comment*, not of the head, so it is [`Self::head_layout`] and every
    ///   braced head asks it.
    ///
    /// A value whose leading comment is a **JSDoc cast** rides one more per-head verdict:
    /// `EmbedContext::jsdoc_cast_cannot_hang`, the "answers the break by rule and CANNOT
    /// hang" value-gap category. A hugging braced head has no operator line to end — the
    /// value starts right after `{#if ` — so the hardline an own-line cast comment earns
    /// everywhere else would strand the `(` at the head's own column (no fixed point where
    /// the head's group flattens, a column-0 value where it can't); the flag makes the cast
    /// reflow to the glued one-line form instead (`{#if /** @type {A} */ (aa)}`). Every
    /// hugging head sets it in its embed recipe ([`Self::head_embed`], the block-head inline
    /// arm, the braced attribute heads, the expression tag); the two heads that CAN give the
    /// comment a real line keep it unset — `{@const}` hangs off its `=`, a directive value
    /// block-wraps. Prettier is no oracle here (it drops the cast comment outright at every
    /// one of these heads); see
    /// docs/conformance_prettier_svelte.md §Svelte: Own-line JSDoc cast at a braced head.
    ///
    /// ⚠️ **Hanging it instead is measured WRONG, not merely incomplete** — answering
    /// [`Self::head_layout`] a hanging arm for the shape indents the value but
    /// leaves the comment glued to `{#if ` (it is *owned*, riding inside the value's doc), so
    /// the output still reads as mid-line and still collapses — and it drags the heads whose
    /// group can't flatten into the same non-convergence. Measured on branch, reverted.
    pub(in crate::printer) fn build_head_value_doc(
        &self,
        expr: &Expression<'_>,
        frozen: bool,
        embed: &EmbedContext,
    ) -> DocId {
        if frozen {
            self.build_frozen_node_doc(expr.span())
        } else if let Some(path) = self.fused_plain_path(expr) {
            // A plain path that owns no comment prints as its own bytes under every embed —
            // a name has one printed form, and so does a lone lookup off one. Every value
            // built through this function takes the arm, a binding pattern's leaves and
            // keys included ([`Self::build_ts_expression_doc`]).
            self.plain_source_span_doc(path)
        } else {
            tsv_ts::__private::build_expression_doc(self.d(), expr, &self.ts_inputs(), *embed)
        }
    }

    /// The span of `expr` when it is a plain path ([`plain_path_span`]) that owns no comment
    /// and may print as its own bytes ([`fuses_source_spans`]) — the fast arm of
    /// [`Self::build_head_value_doc`].
    pub(in crate::printer) fn fused_plain_path(&self, expr: &Expression<'_>) -> Option<Span> {
        plain_path_span(expr)
            .filter(|path| !self.owns_leading_comment_at(path.start) && fuses_source_spans())
    }

    /// One text over `span`, for a construct a gate proved prints as its own source bytes
    /// ([`fuses_source_spans`]) **and** proved plain: no tab, no newline, no non-ASCII byte,
    /// so the text's width is its byte length and equals what its parts would measure to
    /// one by one. Asserts the claim in a debug build, as
    /// [`DocArena::source_span_plain`] asks of every caller.
    pub(in crate::printer) fn plain_source_span_doc(&self, span: Span) -> DocId {
        debug_assert!(
            !span
                .extract(self.source)
                .bytes()
                .any(tsv_lang::printing::is_width_relevant),
            "a fused span holds a byte its width depends on"
        );
        self.d().source_span_plain(span)
    }

    /// Whether the node beginning at `start` **owns** a block comment glued ahead of it —
    /// the comment its doc would print ([`Self::claim_owned_leading_comment`], `tsv_ts`'s
    /// `prepend_owned_leading_comment`). Opens on the document-level flag, like both claims.
    fn owns_leading_comment_at(&self, start: u32) -> bool {
        self.has_owned_comments
            && tsv_lang::owned_leading_comment_at(self.source, self.comments, start).is_some()
    }

    /// [`Self::build_head_value_doc`] for the one head whose value is an **assignment
    /// value** — `{@const}`'s initializer, which prettier prints as a VariableDeclarator's.
    ///
    /// The tag's own layout (`build_assignment_tag_doc`) is prettier's assignment layout, so
    /// the value owes the position-keyed rules an assignment value owes: an inlining logical
    /// chain with earlier operators indents them rather than sitting flat at the tag's column
    /// (`tsv_ts::__private::build_assignment_value_expression_doc`, whose doc states the contract).
    /// `{const}`/`{let}` reach the same rules through
    /// `tsv_ts::__private::build_variable_declaration_doc`, which marks the position itself — the
    /// two tags print one shape and must agree on it.
    ///
    /// The frozen arm is deliberately shared with the plain head: an honored directive emits
    /// the author's bytes, where no layout rule applies.
    pub(in crate::printer) fn build_assignment_value_doc(
        &self,
        expr: &Expression<'_>,
        frozen: bool,
        embed: &EmbedContext,
        value_gap_start: Option<u32>,
    ) -> DocId {
        if frozen {
            self.build_frozen_node_doc(expr.span())
        } else {
            tsv_ts::__private::build_assignment_value_expression_doc(
                self.d(),
                expr,
                &self.ts_inputs(),
                *embed,
                value_gap_start,
            )
        }
    }

    /// The [`EmbedContext`] every **braced head** builds its value under — a block head
    /// (`{#if …}`, `{#each …}`, an `{#each}` key) and a prefixed tag (`{@html …}`,
    /// `{@render …}`) alike. One recipe rather than a copy each, so the two hosts cannot
    /// read as deliberately different.
    ///
    /// `mode` is the load-bearing field: the expression-ROOT entry
    /// (`build_root_expression_doc`) reads `is_embedded()` to force ContinuationIndent on a
    /// root binary, overriding whatever its own position would otherwise answer.
    ///
    /// `jsdoc_cast_cannot_hang` is the recipe's second load-bearing field: a braced head's
    /// value hugs its prefix, so a leading cast's own-line hardline has no matching hang and
    /// must reflow (see [`Self::build_head_value_doc`]).
    ///
    /// ⚠️ `EmbedContext::root_sequence_indents` is deliberately **not** part of the recipe:
    /// the two heads have different oracles for a root sequence's wrap. Prettier
    /// width-wraps `{@html (a,⏎b)}` flush, so a prefixed tag must keep that shape; it never
    /// width-wraps a block head at all, so the block head owns its geometry and sets the
    /// field itself ([`Self::build_expression_doc_for_block`]). Everything the two heads do
    /// share stays here.
    pub(in crate::printer) fn head_embed(&self) -> EmbedContext {
        EmbedContext {
            mode: LayoutMode::Embedded,
            jsdoc_cast_cannot_hang: true,
            ..self.embed
        }
    }

    /// Resolve a braced head's [`HeadLayout`] from its `head`→value gap — the ONE spelling of
    /// that question, so the family cannot answer it three ways again.
    ///
    /// A **`//` in the gap** is what takes the head off `Inline`: it runs to end of line, so
    /// the value cannot stay on the head's line. Which hanging arm it takes is then the
    /// author's, read off the run's FIRST comment: written after the opening literal it keeps
    /// that line (`HangsAfterOpen`), written on its own line it keeps *that*
    /// (`OpensOwnLine`). The comment leads the head's VALUE, and own-line-ness is authoring
    /// signal for a leading position (conformance_prettier.md §Comment Position Philosophy),
    /// so collapsing the two would relocate one of them. Prettier collapses both onto the
    /// head's line, at every braced head.
    ///
    /// A **freeze** short-circuits to `OpensOwnLine`: an honored directive flush against the
    /// prefix is inert under the placement floor, so the break is what makes the freeze
    /// survive a second pass, not a nicety. It is the same shape the own-line authoring
    /// reaches on its own — the freeze is a special case of it, not a rule beside it.
    ///
    /// A leading **block** comment is deliberately excluded, multi-line or not. It ends with a
    /// space, never a hardline: a single-line one doesn't break the head at all, and a
    /// multi-line one's newlines live *inside* its verbatim source span, which renders with no
    /// context indent by design (the interior stays as authored), so its continuation is the
    /// comment's own line and there is nothing to indent. A gap holding only blocks is
    /// `Inline`.
    /// The far end of a braced head's leading-comment gap: the value's **printed** start
    /// (`tsv_ts::__private::expression_printed_start`), which is its span start advanced past every
    /// grouping paren the TS printer strips off its left spine.
    ///
    /// The one spelling of that end, because three seams read this gap and a shell run reaches
    /// each of them: [`Self::head_layout`]'s two callers and the `{@const}` init's
    /// `gap_comment_hangs_value`. A comment inside a stripped shell (`{#if ( // c⏎a).b}`) is
    /// *inside* the value's span, but the TS printer hoists it ahead of the node and prints it
    /// exactly where a comment in this gap lands — so bounding the scan at `span().start`
    /// makes the shell authoring and the paren-free one disagree about one layout
    /// (`docs/comments.md` §The left-spine shell run; the catalog entry is
    /// conformance_prettier.md §Uniform Forced-Continuation Indent, **Svelte braced heads**).
    ///
    /// ⚠️ **Layout gates only** — the run is printed by the value's own doc, so
    /// [`Self::leading_comment_docs`] must keep scanning to `span().start` or it prints the
    /// comment a second time. The two axes are the point: this asks what occupies the page,
    /// the emitter asks what it must print.
    pub(in crate::printer) fn head_gap_end(&self, value: &Expression<'_>) -> u32 {
        tsv_ts::__private::expression_printed_start(self.d(), value, &self.ts_inputs())
    }

    pub(in crate::printer) fn head_layout(
        &self,
        gap_start: u32,
        value_start: u32,
        frozen: bool,
    ) -> HeadLayout {
        if frozen {
            return HeadLayout::OpensOwnLine;
        }
        let mut run = self
            .comments_to_emit_between(gap_start, value_start)
            .peekable();
        let Some(first) = run.peek() else {
            return HeadLayout::Inline;
        };
        let first_own_line =
            tsv_lang::source_scan::has_newline_before_position(self.source, first.span.start);
        if !run.any(|c| !c.is_block) {
            return HeadLayout::Inline;
        }
        if first_own_line {
            HeadLayout::OpensOwnLine
        } else {
            HeadLayout::HangsAfterOpen
        }
    }

    /// The **clarity parens** an assignment used as a value needs (`{@html (a = b)}`,
    /// `prop={(a = b)}`, `{...(a = b)}`) — `value_doc` wrapped for an assignment, returned
    /// unchanged for every other expression, which prints whatever parens it needs itself.
    ///
    /// They are the *printer's* parens, not the author's, which is why they are applied here
    /// rather than inside [`Self::build_head_value_doc`]: a frozen slice keeps its interior
    /// exactly as authored and the parens are **re-synthesized around it**, the same way the
    /// prefix keyword and the closing `}` stay outside the freeze
    /// (docs/conformance_prettier_ignore.md §Format-ignore directive). Skipping them on the
    /// frozen arm doesn't preserve more of the
    /// author's text — it *deletes* the parens they wrote. They must also land inside the
    /// head's own break: applied after the head is assembled instead, a frozen `{@html`
    /// emitted `{@html(`.
    ///
    /// Every braced value position owes them **except `{@const}`'s initializer**, where the
    /// paren is fully redundant and prettier drops it (`{@const a = (b = c)}` →
    /// `{@const a = b = c}`, though the same tool keeps it for a `<script>`'s
    /// `const a = (b = c)`) — that site calls `build_head_value_doc` alone.
    pub(in crate::printer) fn wrap_value_clarity_parens(
        &self,
        expr: &Expression<'_>,
        value_doc: DocId,
    ) -> DocId {
        if Self::value_takes_clarity_parens(expr) {
            self.d().parens(value_doc)
        } else {
            value_doc
        }
    }

    /// Whether [`Self::wrap_value_clarity_parens`] gives the value its pair — so the
    /// value's printed form opens on a `(` of the host's own.
    pub(in crate::printer) fn value_takes_clarity_parens(expr: &Expression<'_>) -> bool {
        matches!(expr.kind, ExpressionKind::AssignmentExpression(_))
    }

    /// An own-line head's content, broken onto its own indented lines: a hardline, then the
    /// gap's comment run and the value one level in.
    ///
    /// The shape [`HeadLayout::OpensOwnLine`] selects, for both of its causes. A
    /// **frozen** head needs it because a directive flush against the prefix is inert under
    /// tsv's floor and the freeze would be gone on the second pass; an **own-line leading
    /// run** needs it because pulling the comment up onto the prefix's line relocates it. The
    /// unprefixed `{…}` values reach the same shape through `wrap_in_block_structure`, and the
    /// hardline here is also what breaks the enclosing head group — a
    /// [`Self::verbatim_source_doc`] slice is opaque to `will_break`, so a frozen value cannot
    /// break anything by itself.
    ///
    /// The caller supplies the prefix via [`Self::head_open_doc`] and its own closing token
    /// after the break.
    pub(in crate::printer) fn indent_own_line_head(&self, content: DocId) -> DocId {
        let d = self.d();
        d.indent_hardline(content)
    }

    /// A braced head's assembled content wearing whatever **indents** it — the one ladder
    /// every head builder's final shape comes out of.
    ///
    /// [`HeadLayout::OpensOwnLine`] takes [`Self::indent_own_line_head`], which also supplies
    /// the hardline that opens the line; [`HeadLayout::HangsAfterOpen`] takes the plain
    /// indent, the run's first comment having already ended the opening literal's line;
    /// [`HeadLayout::Inline`] stays where it is. The layout is resolved inside the builder
    /// that knows it rather than at the assembler, so every caller assembles the same shape
    /// ([`Self::build_prefixed_head_doc`]).
    ///
    /// ⚠️ [`HeadLayout::indents_content`] is also exactly what the builder owes
    /// [`Self::trailing_comment_docs`] as `closer_owns_break` — the indent applied here is
    /// literally the thing that question asks about. One ladder for both so the applied
    /// indent and the closer's break cannot disagree.
    pub(in crate::printer) fn indent_head_content(
        &self,
        content: DocId,
        layout: HeadLayout,
    ) -> DocId {
        match layout {
            HeadLayout::OpensOwnLine => self.indent_own_line_head(content),
            HeadLayout::HangsAfterOpen => self.d().indent(content),
            HeadLayout::Inline => content,
        }
    }

    /// The trailing run of an island value — [`Self::trailing_comment_docs`] over
    /// `[from, to)` — led by an **embed end** ([`DocArena::embed_end`]) when the value's own
    /// doc may carry a deferred run to its end.
    ///
    /// ⚠️ **A deferred run must not leave the island it was written in.** `tsv_ts` defers a
    /// comment it cannot print in place — a stripped redundant pair's interior run
    /// (`a || (b // c⏎)`), the sole hugged arrow's body — to wherever the enclosing line
    /// ends, and in a `<script>` that is the statement's own end. An island owns no such
    /// line: past its value the line is markup, so the run would flush as page text
    /// (`<p>{a || b}</p> // c`). The embed end is the last line end the value's document
    /// owns: a run still pending there flushes and, when it ends in a `//`, the closer drops
    /// below it — exactly the form the same code prints when the author writes the comment
    /// after the value (`{a || b // c⏎}`), which is what the next pass reads it as.
    ///
    /// Its break is the closer's when the run is empty — dedented under `closer_owns_break`,
    /// the same answer the run's last `//` takes — and the run's otherwise: a trailing
    /// comment behind it opens its line at the content's level, as the run's interior breaks
    /// do.
    ///
    /// The host's layout is answered statically, from [`DocArena::pending_run_at_end`]: a
    /// `//` that reaches the value's end in EVERY layout breaks the enclosing groups as a
    /// written trailing `//` does, while a run only SOME layouts carry there (a hugged last
    /// argument whose list may still break) leaves the host's ordinary layout in place, and
    /// the embed end sheds the host separator the render made redundant.
    pub(in crate::printer) fn value_trailing_docs(
        &self,
        value_doc: DocId,
        value_span: Span,
        from: u32,
        to: u32,
        closer_owns_break: bool,
    ) -> ValueTrailing {
        let (mut docs, ends_with_line_comment) =
            self.trailing_comment_docs(from, to, closer_owns_break);
        let d = self.d();
        let run_empty = docs.is_empty();
        if self.gap_known_comment_free(value_span.start, value_span.end)
            || !d.holds_line_suffix(value_doc)
        {
            return ValueTrailing {
                docs,
                gap_run: !run_empty,
                ends_with_line_comment,
                embed_end: None,
            };
        }
        let pending = d.pending_run_at_end(value_doc, self.source);
        let end = d.embed_end(pending, run_empty && closer_owns_break);
        if let Some(run) = pending
            && run.certain
            && run.has_line_comment
        {
            // The value ends on its deferred `//`: the enclosing groups break as a `//`
            // the author wrote after the value breaks them.
            docs.insert(0, d.break_parent());
        }
        docs.insert(0, end.doc());
        ValueTrailing {
            docs,
            gap_run: !run_empty,
            ends_with_line_comment,
            embed_end: Some(end),
        }
    }

    /// The **tail every braced head shares**: the leading run over the `head`→value gap, the
    /// value, the trailing run up to the closer, and the indent ladder — assembled from ONE
    /// `hangs` verdict, taken above the trailing run it governs and fed to both
    /// [`Self::trailing_comment_docs`]'s `closer_owns_break` and [`Self::indent_head_content`].
    ///
    /// The caller owns everything ABOVE this: the freeze verdict, the embed its value was
    /// measured under, the clarity parens, and any per-site post-processing (`remove_lines`
    /// for an inline block head). What it must not own is the pairing here — three builders
    /// each spelled this tail out and answered the hang three different ways, which is the
    /// whole reason the seam exists.
    ///
    /// `gap_start` is just past the head's opening literal, `content_end` just before the
    /// closer. The other braced heads stay out by construction, each for a stated reason: the
    /// unprefixed `{…}` ([`Self::build_expression_content_with_comments`]) cannot apply its own
    /// indent, since its caller picks the layout; a `{@const}` init takes `closer_owns_break`
    /// from the assignment layout rather than from a hang; and `{@debug}` interleaves its
    /// comments with an identifier list on the in-source axis.
    pub(in crate::printer) fn assemble_head_expr(
        &self,
        value_doc: DocId,
        gap_start: u32,
        value: &Expression<'_>,
        content_end: u32,
        frozen: bool,
    ) -> HeadExpr {
        let span = value.span();
        // The layout gate reads to the PRINTED start ([`Self::head_gap_end`]); the emitter
        // stops at the span start, since the value's own doc prints a hoisted shell run.
        let layout = self.head_layout(gap_start, self.head_gap_end(value), frozen);
        let leading_docs = self.leading_comment_docs(gap_start, span.start);
        let trailing = self.value_trailing_docs(
            value_doc,
            span,
            span.end,
            content_end,
            layout.indents_content(),
        );
        let body = self.concat_with_surrounding_comments(leading_docs, value_doc, trailing.docs);
        HeadExpr {
            doc: self.indent_head_content(body, layout),
            layout,
            ends_with_line_comment: trailing.ends_with_line_comment,
            owes_continuation_indent: false,
        }
    }

    /// The opening literal of a prefixed head, as a doc. A [`HeadLayout::OpensOwnLine`] head
    /// drops the literal's trailing space: its content
    /// begins with its own hardline, so the space would be trailing whitespace on the
    /// prefix's line.
    pub(in crate::printer) fn head_open_doc(
        &self,
        open: &'static str,
        opens_own_line: bool,
    ) -> DocId {
        self.d().text(if opens_own_line {
            open.trim_end()
        } else {
            open
        })
    }

    /// A whole prefixed head — the opening literal, the content, the closing token — for
    /// every head that owns its closing token directly: the tags (`{@html …}`,
    /// `{@render …}`, `{@debug …}`), the braced attribute heads (`{...}`, `{@attach}`), and
    /// an `{#each}` key's parens. **The single assembler for that shape**, so the frozen
    /// head's three coupled adjustments — space-less prefix, own-line content, dangling
    /// closer — cannot be applied at one site and forgotten at the next.
    ///
    /// The block heads are the deliberate exception: they close with their own tail (an
    /// `{#each}` ends `as item}`), so they take [`Self::head_open_doc`] and let their
    /// existing dangle supply the break. Both paths render the same content shape.
    ///
    /// `head.doc` is the content in its final shape — already through
    /// [`Self::indent_own_line_head`] when the content opens on its own line (see [`HeadExpr`]).
    /// `close` is the closing token's doc, built by the caller where its spelling is a
    /// literal; `open` stays the literal itself because the own-line layout trims it.
    pub(in crate::printer) fn build_prefixed_head_doc(
        &self,
        open: &'static str,
        head: HeadExpr,
        close: DocId,
    ) -> DocId {
        let d = self.d();
        if !head.layout.indents_content() {
            // Nothing indents this content, so a trailing line comment's own `hardline` is
            // already the break the `}` needs, on the right column.
            return d.concat(&[d.text(open), head.doc, close]);
        }
        // Whatever indented the content, the closer drops to the head's own column — the
        // question is [`HeadLayout::indents_content`], never which arm indented it, so the two
        // hanging authorings of one head differ in the comment's line and in nothing else.
        //
        // A run-final line comment already broke the line, dedented out of that indent
        // (`build_trailing_js_comment_doc`), so the closer reuses that break and lands where
        // it also lands with no trailing comment at all. A second break would render as a
        // blank line above it.
        let open_doc = self.head_open_doc(open, head.layout.opens_own_line());
        if head.ends_with_line_comment {
            return d.concat(&[open_doc, head.doc, close]);
        }
        d.concat(&[open_doc, head.doc, d.hardline(), close])
    }

    /// A head's content for an assembler that **hugs** its delimiters — the one seam that
    /// settles [`HeadExpr::owes_continuation_indent`], so a new hugging arm cannot silently
    /// leave a hung value flush. The block-wrapping arms take `head.doc` directly: their
    /// `indent(…)` already is the continuation indent, and a second would double it.
    pub(in crate::printer) fn hug_head_content(&self, head: HeadExpr) -> DocId {
        if head.owes_continuation_indent {
            self.d().indent(head.doc)
        } else {
            head.doc
        }
    }

    /// Get the source code
    pub(crate) fn source(&self) -> &str {
        self.source
    }

    /// The document's line table — what every embedded TypeScript island reads its line
    /// questions from (the table is the whole document's; spans are absolute).
    pub(crate) fn line_table(&self) -> tsv_lang::printing::LineTable<'_> {
        self.line_breaks.table()
    }

    /// Standard `tsv_ts::__private::PrinterInputs` for embedding TypeScript: this
    /// document's source, comments, and line breaks — and this printer's comment-free
    /// window, which the island takes at construction and hands back when it finishes.
    /// A call site that overrides `comments` (`PrinterInputs { comments: &[], .. }`) is
    /// handing the island a different array and must clear `comment_free_window` too: a
    /// window is a fact about one array, and `take_from` asserts as much in a debug build.
    pub(crate) fn ts_inputs(&self) -> tsv_ts::__private::PrinterInputs<'_> {
        tsv_ts::__private::PrinterInputs {
            source: self.source,
            comments: self.comments,
            line_table: self.line_table(),
            // The document-level owned-comment flag, computed once at construction
            // (never here — this is called per `{expr}`; see the field's doc).
            has_owned_comments: self.has_owned_comments,
            // Likewise the document-level format-ignore flag (computed once at construction).
            has_format_ignore: self.has_format_ignore,
            // The island reads this printer's window and hands its own back: one array, one
            // window (see the field).
            comment_free_window: Some(&self.comment_free_gap),
        }
    }

    /// Whether `[start, end)` is known to hold no comment of any kind **without a search**
    /// (`CommentFreeWindow::known_comment_free` over [`Self::comment_free_gap`]) — the
    /// `tsv_ts` printer's gate of the same name. The inline head of
    /// [`Self::first_index_between`], and the gate a builder puts ahead of work whose only
    /// product on a comment-free gap is "nothing".
    #[inline]
    pub(in crate::printer) fn gap_known_comment_free(&self, start: u32, end: u32) -> bool {
        self.comment_free_gap.known_comment_free(start, end)
    }

    /// The index a comment walk over `[start, end)` starts at: `len` (an empty walk) for a
    /// gap known to hold no comment ([`Self::gap_known_comment_free`]), else the outlined
    /// search — the same inline gate over one `#[inline(never)]` body the `tsv_ts` printer
    /// spells (see `CommentFreeWindow`).
    #[inline]
    fn first_index_between(&self, start: u32, end: u32) -> usize {
        if self.gap_known_comment_free(start, end) {
            self.comment_free_gap.comments().len()
        } else {
            self.first_index_between_wide(start)
        }
    }

    /// The search half of [`Self::first_index_between`] — one outlined copy, taking the
    /// printer.
    #[inline(never)]
    fn first_index_between_wide(&self, start: u32) -> usize {
        self.comment_free_gap.search_from(start)
    }

    /// **to emit**: the comments in `[start, end)` that *this* caller must print — an owned
    /// comment **skipped** (the node its token begins prints it). The printer's form of
    /// `tsv_lang::comments_to_emit_in_range`, reading the comment-free window
    /// ([`Self::comment_free_gap`]) ahead of the search; see `tsv_lang::comment` for the
    /// three axes.
    #[inline]
    pub(crate) fn comments_to_emit_between(
        &self,
        start: u32,
        end: u32,
    ) -> impl Iterator<Item = &'a Comment> + use<'a> {
        comments_to_emit_from(
            self.comment_free_gap.comments(),
            self.first_index_between(start, end),
            end,
        )
    }

    /// **on page**: every comment occupying the page in `[start, end)` — an owned comment
    /// **counted**. For a layout gate whose rule is per-comment.
    #[inline]
    pub(crate) fn comments_on_page_between(
        &self,
        start: u32,
        end: u32,
    ) -> impl Iterator<Item = &'a Comment> + use<'a> {
        comments_on_page_from(
            self.comment_free_gap.comments(),
            self.first_index_between(start, end),
            end,
        )
    }

    /// **in source**: every comment physically inside `[start, end)` — an owned comment
    /// **counted**. For a cursor stepping over comment *bytes*.
    #[inline]
    pub(crate) fn comments_in_source_between(
        &self,
        start: u32,
        end: u32,
    ) -> impl Iterator<Item = &'a Comment> + use<'a> {
        comments_in_source_from(
            self.comment_free_gap.comments(),
            self.first_index_between(start, end),
            end,
        )
    }

    /// **to emit**: whether *this* caller has a comment to print in `[start, end)`.
    #[inline]
    pub(crate) fn has_comments_to_emit_between(&self, start: u32, end: u32) -> bool {
        has_comments_to_emit_from(
            self.comment_free_gap.comments(),
            self.first_index_between(start, end),
            end,
        )
    }

    /// **on page**: whether any comment occupies the page in `[start, end)` — the existence
    /// check for a layout gate, an owned comment **counted**.
    #[inline]
    pub(crate) fn has_comments_on_page_between(&self, start: u32, end: u32) -> bool {
        has_comments_on_page_from(
            self.comment_free_gap.comments(),
            self.first_index_between(start, end),
            end,
        )
    }

    /// Write indentation based on current indent level
    pub(crate) fn write_indent(&mut self) {
        tsv_lang::write_indent(&mut self.buffer, self.indent_level, INDENT);
    }

    /// Get the formatted output
    ///
    /// Simply extracts the buffer. Whitespace stripping is handled by the doc rendering layer:
    /// - Normal elements: rendered with `arena_print_doc_with_indent_resolved_into` which strips
    /// - Whitespace-sensitive elements: rendered with
    ///   `arena_print_doc_with_indent_resolved_preserve_whitespace_into` which preserves
    pub(crate) fn into_string(self) -> String {
        // Park the line-break scratch back on the arena for the next format
        // (capacity retained, filled or not; see `with_embed`).
        self.arena
            .park_line_breaks_scratch(self.line_breaks.into_scratch());
        self.buffer.into_string()
    }

    /// Render a DocId immediately at current buffer position
    ///
    /// This is the foundation for doc-first formatting. Instead of using
    /// imperative printing, callers build a Doc and render it in one step.
    ///
    /// The doc is rendered starting at the current column position with
    /// the current indent level, so it seamlessly integrates with any
    /// preceding output.
    ///
    /// Always uses the preserve-whitespace variant because the doc tree may contain
    /// whitespace-sensitive elements (`<pre>`, `<textarea>`) whose trailing whitespace
    /// must be preserved. Normal elements have trailing whitespace stripped during
    /// doc building, not rendering.
    pub(crate) fn render_doc_immediate(&mut self, d: DocId) {
        let col = self.buffer.current_column(TAB_WIDTH);
        // Render into the arena-parked scratch: one warm buffer across the
        // document's root nodes instead of an alloc/free per node.
        let mut output = self.arena.take_render_scratch();
        // Pass the document source: the doc tree's verbatim leaves — this
        // printer's own markup text / comment slices plus any embedded
        // `tsv_ts` docs — are `DocText::SourceSpan` (host-absolute spans).
        tsv_lang::doc::arena_print_doc_with_indent_resolved_preserve_whitespace_into(
            self.arena,
            d,
            &self.embed,
            col,
            self.indent_level,
            self.source,
            &mut output,
        );
        self.write(&output);
        self.arena.park_render_scratch(output);
    }
}

impl<'a> Printer<'a> {
    /// Build a DocId for a TS expression (with comments) in our arena.
    ///
    /// Uses the standard parameters: self.comments, self.embed, self.line_breaks — i.e. the
    /// unfrozen arm of [`Self::build_head_value_doc`] under the host's own embed, spelled
    /// once there. For calls that need a custom embed context or empty comments, use the
    /// tsv_ts functions directly.
    pub(crate) fn build_ts_expression_doc(&self, expr: &Expression<'_>) -> DocId {
        self.build_head_value_doc(expr, false, &self.embed)
    }

    /// [`Self::build_ts_expression_doc`] for a **braced-head** value: the host's embed plus
    /// the leading-cast reflow every hugging braced head owes (`jsdoc_cast_cannot_hang` —
    /// see [`Self::build_head_value_doc`]). The `{#each}` key's fallback arm and the
    /// pattern printer's computed key use it; the main key arm reaches the same flag
    /// through [`Self::build_expression_doc_for_block`].
    pub(crate) fn build_ts_expression_doc_cannot_hang(&self, expr: &Expression<'_>) -> DocId {
        self.build_head_value_doc(expr, false, &self.cannot_hang_embed())
    }

    /// The host's embed plus `jsdoc_cast_cannot_hang` — the recipe for a hugging braced
    /// head measured where it sits (the block-head inline arm, a prefixed attribute
    /// head); the heads that re-base their measurement carry the flag in their own
    /// recipes instead ([`Self::head_embed`], the unprefixed value's default-based embed).
    pub(in crate::printer) fn cannot_hang_embed(&self) -> EmbedContext {
        EmbedContext {
            jsdoc_cast_cannot_hang: true,
            ..self.embed
        }
    }
}

/// Format a Svelte AST back to source code
pub(crate) fn format_svelte(root: &ast::Root<'_>, source: &str) -> String {
    let arena = DocArena::for_source(source);
    format_svelte_in(root, source, &arena)
}

/// Format a Svelte AST into a caller-provided doc arena (the reuse path).
pub(crate) fn format_svelte_in(root: &ast::Root<'_>, source: &str, arena: &DocArena) -> String {
    let line_breaks = LineBreaks::new(source, arena.take_line_breaks_scratch());
    format_root(
        root,
        source,
        line_breaks,
        arena,
        TailRespell::Allow,
        LiftRuns::Allow,
        Known::default(),
    )
}

/// [`format_svelte_in`] over a document the caller folded ahead of the parse: the line
/// verdict comes from the fold's own pass (`LineBreaks::of_folded`), not a second walk.
pub(crate) fn format_svelte_folded_in(
    root: &ast::Root<'_>,
    folded: &tsv_lang::printing::FoldedSource<'_>,
    arena: &DocArena,
) -> String {
    let line_breaks = LineBreaks::of_folded(folded, arena.take_line_breaks_scratch());
    format_root(
        root,
        folded.text(),
        line_breaks,
        arena,
        TailRespell::Allow,
        LiftRuns::Allow,
        Known::default(),
    )
}

/// Whether [`format_root`] may respell the template tail ([`format_respelled_tail`]).
#[derive(Clone, Copy, PartialEq, Eq)]
enum TailRespell {
    /// The entry points: respell when `Printer::template_tail_respell` asks for it.
    Allow,
    /// The respelled source: its tail ends in the reference's `;`, so it never asks again.
    Respelled,
    /// The respelled source did not parse, so the original prints unrespelled.
    Declined,
}

/// Whether [`format_root`] may move the component's mid-template lifted runs out of the
/// template ([`format_lifted_runs`]).
#[derive(Clone, Copy, PartialEq, Eq)]
enum LiftRuns {
    /// The entry points: rewrite when `Printer::lifted_runs_source` asks for it.
    Allow,
    /// A rewritten source (or a respelling of a source that had nothing to lift): no run sits
    /// between template nodes any more, so it never asks again.
    Lifted,
    /// The rewritten source did not parse, so the original prints with its runs in place.
    Declined,
}

/// What a caller of [`format_root`] already knows about the document it hands over: its
/// comment classification ([`Printer::hoisted_comments`]) and its sections' freeze verdicts
/// ([`FrozenSections`]). A rewrite carries the original's freeze verdicts, since it moves
/// sections past the comments a directive is read off.
#[derive(Default)]
struct Known {
    sections: Option<HoistedComments>,
    frozen: Option<FrozenSections>,
}

impl Known {
    fn frozen(frozen: FrozenSections) -> Self {
        Self {
            sections: None,
            frozen: Some(frozen),
        }
    }
}

/// The shared body of the two: build the printer on its line table, register the
/// document's comments, print the root, and write a BOM ahead of a leading content U+FEFF
/// (`tsv_lang::printing::encode_leading_zwnbsp`) — or, for a document with a hoisted section
/// written between template nodes, format the rewritten source that joins the neighbours
/// ([`format_lifted_runs`]); or, for a document whose template tail the reorder would expose
/// to the parse's end-of-document trim, the respelled source ([`format_respelled_tail`]).
fn format_root<'a>(
    root: &ast::Root<'_>,
    source: &'a str,
    line_breaks: LineBreaks<'a>,
    arena: &'a DocArena,
    tail: TailRespell,
    lift: LiftRuns,
    known: Known,
) -> String {
    debug_assert!(
        !source.contains('\r'),
        "a format entry point takes CR-folded text (`tsv_lang::printing::normalize_carriage_returns`)"
    );
    // The printer's comment VIEW (`tsv_lang::merge_nestled_block_comments`). Two facts are
    // this array's own: it serves both this printer and every TEMPLATE island it constructs
    // (`ts_inputs` hands it over), so one merge here reaches every `{expr}` — a `<script>`
    // body is the exception, building its own island-local environment (`build_program_doc`);
    // and it also holds Svelte's in-tag comments, which the merge declines, since prettier's
    // rule is a JS-parse postprocess and its own Svelte printer drops those outright, so
    // there is no oracle for them either way.
    let comments = tsv_lang::merge_nestled_block_comments(source, &root.comments);

    // The template printer deliberately leaves `EmbedContext::printer_owns_line` at its
    // default: after an island's closing `}` the rest of the line is this printer's markup,
    // so a `//` an island defers past its own doc would come out as page text. What carries
    // that to every island is the FIELD's default polarity, not a spread convention — the
    // recipes rebase on two different bases (`..self.embed` for the heads, a fresh
    // `EmbedContext::default()` in `build_unprefixed_value_doc`), and only both being false
    // makes them agree. `<script>` claims ownership by name instead (`script_style.rs`).
    let printer = Printer::with_line_breaks(
        arena,
        source,
        &comments,
        EmbedContext::default(),
        line_breaks,
    );
    printer
        .nested_raw_text_nesting
        .set(root.nested_raw_text_nesting);
    // Which fragment content edges are line-box edges — asked by the nested `<script>` /
    // `<style>` glue, and indexed before anything reads it.
    printer.index_fragment_edges(root);

    // Which fragment comments travel with which section: asked once per document and shared by
    // the lifted-run rewrite, the tail respell and the print — a caller that already classified
    // this document hands its answer in.
    let sections = known
        .sections
        .unwrap_or_else(|| printer.hoisted_comments(root));
    // Which sections a directive freezes — a caller that rewrote the document hands in the
    // original's answer, since the rewrite moves sections past comments (`frozen_sections`).
    let frozen = known
        .frozen
        .unwrap_or_else(|| printer.frozen_sections(root));

    // Asked ahead of everything the print does, the ledger included — and ahead of the tail
    // respell, since moving a run can change which text ends the template: a document with a
    // lifted run between template nodes is formatted from the rewritten source instead.
    match lift {
        LiftRuns::Allow => {
            if let Some(lifted) = printer.lifted_runs_source(root, &sections) {
                drop(printer.into_string()); // parks the line-break scratch
                return format_lifted_runs(root, source, &lifted, arena, tail, sections, frozen);
            }
        }
        LiftRuns::Lifted => debug_assert!(
            printer.lifted_runs_source(root, &sections).is_none(),
            "a lifted source must not ask to be lifted again"
        ),
        LiftRuns::Declined => {}
    }

    // A document whose template tail must be respelled is formatted from the respelled source
    // instead.
    match tail {
        TailRespell::Allow => {
            if let Some((at, ch)) = printer.template_tail_respell(root, &sections) {
                drop(printer.into_string()); // parks the line-break scratch
                let lift = match lift {
                    LiftRuns::Declined => LiftRuns::Declined,
                    LiftRuns::Allow | LiftRuns::Lifted => LiftRuns::Lifted,
                };
                return format_respelled_tail(root, source, at, ch, arena, lift, frozen);
            }
        }
        TailRespell::Respelled => debug_assert!(
            printer.template_tail_respell(root, &sections).is_none(),
            "a respelled template tail must not ask to be respelled again"
        ),
        TailRespell::Declined => {}
    }

    // The print-once comment ledger's expectation for this document (diagnostic; see
    // `tsv_lang::comment_ledger`). `Root.comments` is the `<script>` + template-expression
    // JS comments, registered as MERGED — the list the printers emit; the `<style>` island
    // registers its own through `tsv_css`. The template's
    // `<!-- -->` (`FragmentNode::Comment`) comments are AST nodes rather than detached, so
    // they register by span through a recursive fragment walk — hoisted section comments
    // included, since they still live in `Root.fragment.nodes` (see `print_root`).
    #[cfg(feature = "_internal_comment_check")]
    {
        tsv_lang::comment_ledger::register_parsed(source, &comments);
        let mut html_comment_spans = Vec::new();
        collect_html_comment_spans(&root.fragment, &mut html_comment_spans);
        tsv_lang::comment_ledger::register_parsed_spans(source, html_comment_spans);
    }

    print_document(printer, root, &sections, frozen)
}

/// Print `root` through `printer` and write a BOM ahead of a leading content U+FEFF
/// (`tsv_lang::printing::encode_leading_zwnbsp`).
fn print_document(
    mut printer: Printer<'_>,
    root: &ast::Root<'_>,
    sections: &HoistedComments,
    frozen: FrozenSections,
) -> String {
    printer.print_root(root, sections, frozen);
    // A content U+FEFF at output byte 0 needs a BOM ahead of it, or the next read strips it.
    tsv_lang::printing::encode_leading_zwnbsp(printer.into_string())
}

/// Format `source` with its character at byte `at` (`ch`, the template's last content
/// character — see `Printer::template_tail_respell`) spelled as an uppercase-hex character
/// reference (`&#xA0;`).
///
/// The respell is made in the SOURCE, ahead of the parse, so the layout measures the text the
/// output holds: the reference is wider than the character, and a line filled around the raw
/// character and substituted afterwards could overrun the print width and re-wrap on the next
/// pass. The respelled source renders the same (Svelte decodes the reference back to `ch`, and
/// at `at` the character was not yet at the end of the document), and the respelled text ends in
/// `;`, so the second format never asks again.
///
/// The respelled source differs from a source that parsed only by a character reference in
/// template text, so its parse is expected to fail only on the size limit (`Error`'s
/// `FileTooLarge`), which the few added bytes can cross — nothing proves that. Whatever the
/// failure, the original is then printed unrespelled.
fn format_respelled_tail(
    root: &ast::Root<'_>,
    source: &str,
    at: usize,
    ch: char,
    arena: &DocArena,
    lift: LiftRuns,
    frozen: FrozenSections,
) -> String {
    let mut respelled = String::with_capacity(source.len() + 10);
    respelled.push_str(&source[..at]);
    push_char_reference(&mut respelled, ch);
    respelled.push_str(&source[at + ch.len_utf8()..]);

    let bump = bumpalo::Bump::new();
    match crate::__private::parse(&respelled, &bump) {
        Ok(respelled_root) => {
            let line_breaks = LineBreaks::new(&respelled, arena.take_line_breaks_scratch());
            format_root(
                &respelled_root,
                &respelled,
                line_breaks,
                arena,
                TailRespell::Respelled,
                lift,
                Known::frozen(frozen),
            )
        }
        Err(_) => {
            let line_breaks = LineBreaks::new(source, arena.take_line_breaks_scratch());
            format_root(
                root,
                source,
                line_breaks,
                arena,
                TailRespell::Declined,
                lift,
                Known::frozen(frozen),
            )
        }
    }
}

/// Format `lifted` — `source` rewritten in the output's layout (`Printer::lifted_runs_source`)
/// — in its place.
///
/// The rewrite writes every section run where the output prints it, so it holds its comments in
/// the output's order and classifies them as the output's own next pass does; there is nothing
/// left to check it against. The one thing it cannot carry is a section's freeze: a directive
/// is read off what stands above the section, which the rewrite changes, so the original's
/// verdict (`frozen`) goes along with it. The rewrite only moves source text and respells
/// whitespace between two template nodes, so its parse is expected to fail only on the size
/// limit (`Error`'s `FileTooLarge`), which the few added line breaks can cross — nothing
/// proves that. Whatever the failure, the original is then printed with its runs where they
/// stand (`sections` is its classification).
fn format_lifted_runs(
    root: &ast::Root<'_>,
    source: &str,
    lifted: &str,
    arena: &DocArena,
    tail: TailRespell,
    sections: HoistedComments,
    frozen: FrozenSections,
) -> String {
    let bump = bumpalo::Bump::new();
    match crate::__private::parse(lifted, &bump) {
        Ok(lifted_root) => {
            let line_breaks = LineBreaks::new(lifted, arena.take_line_breaks_scratch());
            format_root(
                &lifted_root,
                lifted,
                line_breaks,
                arena,
                tail,
                LiftRuns::Lifted,
                Known::frozen(frozen),
            )
        }
        Err(_) => {
            let line_breaks = LineBreaks::new(source, arena.take_line_breaks_scratch());
            format_root(
                root,
                source,
                line_breaks,
                arena,
                tail,
                LiftRuns::Declined,
                Known {
                    sections: Some(sections),
                    frozen: Some(frozen),
                },
            )
        }
    }
}

/// Collect the spans of every `<!-- -->` (`FragmentNode::Comment`) in a fragment, recursing
/// into every nested fragment (elements, special elements, and the `{#if}` / `{#each}` /
/// `{#await}` / `{#key}` / `{#snippet}` block bodies). The print-once comment ledger reads
/// only the span, so no `HtmlComment` need be manufactured into a `Comment`.
#[cfg(feature = "_internal_comment_check")]
fn collect_html_comment_spans(fragment: &ast::Fragment<'_>, out: &mut Vec<Span>) {
    for node in fragment.nodes {
        match node {
            FragmentNode::Comment(comment) => out.push(comment.span),
            FragmentNode::Element(el) => collect_html_comment_spans(&el.fragment, out),
            FragmentNode::SpecialElement(el) => collect_html_comment_spans(&el.fragment, out),
            FragmentNode::IfBlock(block) => {
                collect_html_comment_spans(&block.consequent, out);
                if let Some(alternate) = &block.alternate {
                    collect_html_comment_spans(alternate, out);
                }
            }
            FragmentNode::EachBlock(block) => {
                collect_html_comment_spans(&block.body, out);
                if let Some(fallback) = &block.fallback {
                    collect_html_comment_spans(fallback, out);
                }
            }
            FragmentNode::AwaitBlock(block) => {
                if let Some(pending) = &block.pending {
                    collect_html_comment_spans(pending, out);
                }
                if let Some(then) = &block.then {
                    collect_html_comment_spans(then, out);
                }
                if let Some(catch) = &block.catch {
                    collect_html_comment_spans(catch, out);
                }
            }
            FragmentNode::KeyBlock(block) => collect_html_comment_spans(&block.fragment, out),
            FragmentNode::SnippetBlock(block) => collect_html_comment_spans(&block.body, out),
            _ => {}
        }
    }
}

impl<'a> Printer<'a> {
    /// Whether the gap `[start, end)` holds a directive that honors — the one freeze
    /// question the Svelte printer asks, in both of the shapes it has:
    ///
    /// - the **value head**: the `{`→value gap of a braced expression (a directive value,
    ///   an expression tag), the Svelte instance of the delimiter-owned head that `tsv_ts`
    ///   spells `Printer::value_head_frozen_span`. Freezes the whole value; the `}` that
    ///   closes it stays parent-owned.
    /// - **Rule A**: a function-binding sequence's inter-operand gap. Freezes the
    ///   FOLLOWING operand; the `,` stays parent-owned. The same rule `tsv_ts`'s sequence
    ///   printer applies — the bind value has its own operand loop only because Svelte
    ///   prints the pair bare.
    ///
    /// Both callers slice their own span from the `bool`, so unlike `tsv_ts` there is
    /// nothing for a per-rule name to carry; each call site names its rule in a comment
    /// instead of behind a hollow wrapper.
    ///
    /// It also decides the gap's **layout**, which is not a second question: an honored
    /// directive takes the broken block form, so the emitter never pulls it flush against
    /// the `{`, where it would be inert and the freeze would be lost on the second pass
    /// (the `{…}` instance of the declaration-header rule; see
    /// docs/conformance_prettier_ignore.md §Format-ignore directive).
    ///
    /// **In-source axis** — a directive is never owned, so the axes coincide, but naming
    /// the physical one keeps directive recognition a single deliberate question (as
    /// `tsv_ts`'s `member_gap_frozen` does). Opens on the document-level flag: every braced
    /// value in every component asks it.
    pub(in crate::printer) fn honored_directive_in_gap(&self, start: u32, end: u32) -> bool {
        self.has_format_ignore
            && self
                .comments_in_source_between(start, end)
                .any(|c| self.is_honored_directive(c))
    }

    /// Whether comment `c` is a format-ignore directive that HONORS — `tsv_ts`'s
    /// `Printer::is_honored_directive` against this document. The freeze tests ask it
    /// through [`Self::honored_directive_in_gap`]; an emitter asks it directly when a
    /// comment's own layout depends on the answer, because an honored directive must keep
    /// the line the author gave it — gluing the following construct onto that line makes the
    /// placement inert, and the freeze would be lost on the next pass.
    ///
    /// Carries the document-level `has_format_ignore` gate, so a directive-free component
    /// (≈ every component) pays one predicted branch instead of the content compare.
    pub(in crate::printer) fn is_honored_directive(&self, c: &Comment) -> bool {
        // The document start is 0, the component's own: every JS comment this printer asks
        // about sits in a template island — an expression tag, an attribute or directive
        // value, a block head, `{@const}` — which always has markup or its own `{` ahead of
        // it on its line, so no floor past the host's start could change an answer. (A
        // `<script>` body's directives are its program's, asked by `tsv_ts` from the
        // program's own start.)
        self.has_format_ignore && is_honored_format_ignore(self.source, c, 0)
    }

    /// Whether a section is frozen: the fragment node nearest above it (whitespace aside) is a
    /// `<!-- format-ignore -->` (or `prettier-ignore`) directive, with no other hoisted
    /// section (`hoisted`) between the two.
    ///
    /// The "no other section between" is the point: a section is not a fragment node, so the
    /// node nearest above a section can sit above ANOTHER section too, and a directive there
    /// belongs to that one (`<!-- prettier-ignore -->⏎<script module>…</script>⏎<script>…`
    /// freezes the module script alone). The nearest NODE rather than the section's travelling
    /// run, because a directive inside a `format-ignore` range never travels (the range prints
    /// it where it stands) and still freezes the section below it.
    fn section_is_frozen(
        &self,
        fragment: &ast::Fragment<'_>,
        section: Span,
        hoisted: &[Span],
    ) -> bool {
        let nodes = &fragment.nodes;
        let above = nodes.partition_point(|n| n.span().end <= section.start);
        let Some(FragmentNode::Comment(comment)) = nodes[..above]
            .iter()
            .rev()
            .find(|n| !n.is_whitespace_only_text())
        else {
            return false;
        };
        is_format_ignore_directive(comment.content(self.source))
            && !hoisted
                .iter()
                .any(|h| comment.span.end <= h.start && h.end <= section.start)
    }

    /// Every section's freeze verdict ([`Self::section_is_frozen`]) — `<svelte:options>`
    /// takes none, since it always prints normalized.
    fn frozen_sections(&self, root: &ast::Root<'_>) -> FrozenSections {
        let hoisted: SmallVec<[Span; 4]> = root_sections(root)
            .into_iter()
            .filter_map(|(span, _)| span)
            .collect();
        root_sections(root).map(|(span, section)| {
            section != HoistedSection::Options
                && span.is_some_and(|span| self.section_is_frozen(&root.fragment, span, &hoisted))
        })
    }

    /// The root fragment's [`IgnoreRanges`], paired on first ask and kept for the document —
    /// every reader asks of the one root this printer formats.
    fn ignore_ranges(&self, root_fragment: &ast::Fragment<'_>) -> &IgnoreRanges {
        let ranges = self
            .ignore_ranges
            .get_or_init(|| IgnoreRanges::new(root_fragment.nodes, self.source));
        debug_assert_eq!(
            ranges.nodes_addr,
            root_fragment.nodes.as_ptr() as usize,
            "the ignore ranges pair one root fragment per printer"
        );
        ranges
    }

    /// Classify which section a fragment comment should travel with during
    /// canonical reordering. Each comment attaches to the nearest section
    /// that follows it in source order.
    ///
    /// Two things pin a comment to the template: a real node between it and every section (it
    /// leads that node, not a section), and a **format-ignore range marker** — see
    /// [`range_marker`]'s role in the scan below.
    fn classify_fragment_comment(
        comment: &ast::HtmlComment,
        comment_idx: usize,
        root: &ast::Root<'_>,
        scan: &CommentScan<'_>,
    ) -> Option<HoistedSection> {
        // format-ignore-start/end mark ranges within the template —
        // they must stay in the fragment so the range preservation logic sees them
        if scan.ranges.markers[comment_idx].is_some() {
            return None;
        }

        // A comment INSIDE a frozen range is already emitted by the range's verbatim slice, so
        // hoisting it prints it twice. The barrier below cannot see this on its own: when the
        // *section* is inside the range too, its start precedes the closing marker and wins the
        // nearest-start contest.
        if scan.ranges.contains(comment_idx) {
            return None;
        }

        let comment_end = comment.span.end;

        // The first thing after the comment that pins it to the template: a real node (the
        // comment leads *it*), or a range marker.
        //
        // A marker is a BARRIER, not a skippable comment. Hoisting across one moves the comment
        // into or out of a frozen region — a reorder prettier does not make — and when the
        // comment sits INSIDE the range it is printed twice, since the fragment emits the whole
        // range verbatim while the section emits the comment again. Ordinary comments are still
        // skipped: a run of them all lead the same section.
        let mut nearest: Option<(u32, Option<HoistedSection>)> =
            scan.next_barrier[comment_idx].map(|barrier| (barrier, None));

        // Every root section competes on the same rule — the nearest start after the comment
        // wins. One loop over the shared [`root_sections`] table rather than four copies of
        // the comparison: the copies differ only in which field and which variant, which is
        // exactly the pair a copy-paste edit gets wrong silently.
        for (span, section) in root_sections(root) {
            let Some(start) = span.map(|s| s.start) else {
                continue;
            };
            if start >= comment_end && nearest.as_ref().is_none_or(|(p, _)| start < *p) {
                nearest = Some((start, Some(section)));
            }
        }

        nearest.and_then(|(_, section)| section)
    }

    /// Each hoisted section's region-end trail CANDIDATE ([`HoistedSection::ALL`] order):
    /// the fragment index of the first comment after the section's end, with nothing but
    /// whitespace between, spelled as a region end ([`is_region_end_marker`]) — or `None`.
    ///
    /// Comments travel with the section they precede ([`Self::classify_fragment_comment`]),
    /// so a comment after the last hoisted section — or one followed by template content —
    /// normally stays in the template, and after the canonical reorder it prints on the far
    /// side of whatever moved. A `#endregion` is the one comment whose meaning is BOUND to the
    /// block above it (an editor folds `#region` … `#endregion` as a pair), so it travels
    /// below the section it closes instead. prettier-plugin-svelte's rule (its
    /// `extractRegionEndTrailAfterHoistedEnd`), asked the plugin's way — of each hoisted END,
    /// not of each comment, so a document's template comments pay nothing for it. The one
    /// byte the two readings differ on is the form feed: the plugin's whitespace gate is
    /// `[\t\n\f\r ]`, [`ast::is_collapsible_ws`] deliberately lacks `\f`.
    ///
    /// A candidate only: the plugin's precedence is its evaluation order, and `print_root`
    /// applies it against the classification. A `#endregion` that a FOLLOWING `<script>` or
    /// `<style>` claims as its leading comment (`</script>⏎<!-- #endregion -->⏎<style>`)
    /// leads that section, since the plugin's embed pass takes those comments before the
    /// trail is extracted; a following `<svelte:options>` claims its comment AFTER the
    /// extraction, so there the trail wins (`</style>⏎<!-- #endregion -->⏎<svelte:options />`
    /// keeps the marker below the style). So a candidate is confirmed only when it classifies
    /// to the template (`None`) or to [`HoistedSection::Options`]. Range markers and comments
    /// inside a frozen range are excluded for the same reasons the leading classification
    /// excludes them.
    fn region_end_trails(&self, root: &ast::Root<'_>) -> [Option<usize>; 4] {
        let nodes = &root.fragment.nodes;
        let bytes = self.source.as_bytes();
        root_sections(root).map(|(span, _)| {
            let end = span?.end as usize;
            // The fragment holds no node of the section itself, so the first node at or past
            // its end is its successor; step over the whitespace text between them.
            let first = nodes.partition_point(|n| (n.span().start as usize) < end);
            let (idx, node) = nodes[first..]
                .iter()
                .enumerate()
                .find(|(_, n)| !n.is_whitespace_only_text())
                .map(|(k, n)| (first + k, n))?;
            let FragmentNode::Comment(comment) = node else {
                return None;
            };
            let start = comment.span.start as usize;
            (bytes[end..start].iter().all(|&b| ast::is_collapsible_ws(b))
                && is_region_end_marker(comment.content(self.source))
                && range_marker(comment, self.source).is_none()
                && !self.ignore_ranges(&root.fragment).contains(idx))
            .then_some(idx)
        })
    }

    /// The comment at fragment index `idx` — the one resolution of a classified comment index.
    /// Only comment indices are classified to a section, so `None` is an invariant violation:
    /// asserted under the fixture suite, skipped (never a panic — this is the shipped printer)
    /// in a release build.
    fn fragment_comment<'f>(
        fragment: &'f ast::Fragment<'_>,
        idx: usize,
    ) -> Option<&'f ast::HtmlComment> {
        let comment = match &fragment.nodes[idx] {
            FragmentNode::Comment(comment) => Some(comment),
            _ => None,
        };
        debug_assert!(comment.is_some(), "only comment indices are classified");
        comment
    }

    /// Print one hoisted-section comment on its own line: the author's blank line between
    /// `prev_end` (the previous comment, or the section's closing tag for a region-end trail)
    /// and the comment survives, then the comment, then the line break. The one emitter behind
    /// every comment a section prints around itself.
    fn print_comment_line(&mut self, comment: &ast::HtmlComment, prev_end: Option<u32>) {
        if let Some(end) = prev_end
            && text::has_authored_blank_line(
                &self.source[end as usize..comment.span.start as usize],
            )
        {
            self.write("\n");
        }
        self.print_comment(comment);
        self.write("\n");
    }

    /// Print a run of hoisted-section comments, each through [`Self::print_comment_line`].
    /// Returns the last comment's end, `None` when the run is empty.
    fn print_comment_run(
        &mut self,
        comment_indices: &[usize],
        fragment: &ast::Fragment<'_>,
    ) -> Option<u32> {
        let mut prev_end: Option<u32> = None;
        for &i in comment_indices {
            let Some(comment) = Self::fragment_comment(fragment, i) else {
                continue;
            };
            self.print_comment_line(comment, prev_end);
            prev_end = Some(comment.span.end);
        }
        prev_end
    }

    /// Print a section's region-end trail ([`Self::region_end_trails`]) below the section:
    /// the author's blank line between the closing tag and the marker survives (prettier
    /// keeps it too), then the comment on its own line.
    fn print_region_end_trail(
        &mut self,
        trail: Option<usize>,
        fragment: &ast::Fragment<'_>,
        section_end: u32,
    ) {
        if let Some(idx) = trail
            && let Some(comment) = Self::fragment_comment(fragment, idx)
        {
            self.print_comment_line(comment, Some(section_end));
        }
    }

    /// Print section-attached comments and preserve authorial blank lines.
    /// Returns true if any comments were printed.
    ///
    /// Both blank questions ask [`text::has_authored_blank_line`], the RUN scan, because neither
    /// gap is guaranteed whitespace-only: a `format-ignore` range marker classifies
    /// to the template while [`Self::classify_fragment_comment`] skips *every*
    /// comment when it looks for the nearest real node, so a marker can sit between two section
    /// comments — or between the last one and its section. A newline *total* would read that
    /// marker's two bracketing newlines as an authored blank and invent one.
    ///
    /// TODO: the marker only lands in those gaps because a section comment is hoisted **past**
    /// the range boundary in the first place — a reorder prettier does not make, and one that
    /// double-prints a comment written INSIDE the range (the fragment emits the range verbatim
    /// while the section emits the comment again). Classifying a comment separated from its
    /// section by a range marker as `Template` would fix the reorder, the double-print, and
    /// make these gaps whitespace-only again; it needs its own fixture cycle.
    fn print_section_comments(
        &mut self,
        comment_indices: &[usize],
        fragment: &ast::Fragment<'_>,
        section_start: u32,
    ) -> bool {
        let Some(last_end) = self.print_comment_run(comment_indices, fragment) else {
            return false;
        };
        // Preserve authorial blank line between last comment and section
        let between = &self.source[last_end as usize..section_start as usize];
        if text::has_authored_blank_line(between) {
            self.write("\n");
        }
        true
    }

    /// The fragment comments each hoisted section carries with it through the reorder: the
    /// run written directly above it, and its region-end trail. A region-end trail candidate is
    /// confirmed against the classification (the plugin's precedence — see
    /// [`Self::region_end_trails`]); each candidate names one section and each section at most
    /// one candidate, so a confirmed trail is written exactly once.
    fn hoisted_comments(&self, root: &ast::Root<'_>) -> HoistedComments {
        let trails = self.region_end_trails(root);
        let mut sections = HoistedComments::default();
        let scan = CommentScan::new(&root.fragment, self.ignore_ranges(&root.fragment));

        for (i, node) in root.fragment.nodes.iter().enumerate() {
            if let FragmentNode::Comment(comment) = node {
                let section = Self::classify_fragment_comment(comment, i, root, &scan);
                if matches!(section, None | Some(HoistedSection::Options))
                    && let Some(k) = trails.iter().position(|&trail| trail == Some(i))
                {
                    debug_assert!(sections.0[k].trail.is_none());
                    sections.0[k].trail = Some(i);
                    continue;
                }
                if let Some(section) = section {
                    sections[section].leading.push(i);
                }
            }
        }
        sections
    }

    /// The character to respell as a reference so the template's last text survives the
    /// reorder, as `(byte offset in the source, character)` — or `None`, the common case.
    ///
    /// Svelte's `parse` trims the END of the document with JavaScript's `trimEnd()`, whose class
    /// holds characters its compiler renders everywhere else
    /// ([`crate::whitespace::is_end_trimmed_content`]) — U+00A0, U+FEFF, U+2028, the form feed.
    /// At the end of the source they are already gone (the parse dropped them), so a text node
    /// ending in one was followed by something. When that something is a hoisted section (or a
    /// comment travelling with one) and no `<style>` prints after the template, the canonical
    /// reorder makes the text the document's end, and the next read would delete its last
    /// character — a render change. Spelled as a character reference it decodes to the same text,
    /// and its `;` is what the trim stops at.
    ///
    /// Read off the parsed text node (its own `raw`, trailing collapsible whitespace aside),
    /// never off source bytes past it. A `prettier-ignore`-frozen node answers the same: the
    /// move is tsv's, so the respell completes it.
    fn template_tail_respell(
        &self,
        root: &ast::Root<'_>,
        sections: &HoistedComments,
    ) -> Option<(usize, char)> {
        if root.css.is_some() {
            return None;
        }
        let nodes = &root.fragment.nodes;
        let mut tail = None;
        for (i, node) in nodes.iter().enumerate().rev() {
            match node {
                FragmentNode::Text(t) if t.is_collapsible_ws_only => {}
                FragmentNode::Comment(_) => {}
                FragmentNode::Text(t) => {
                    tail = Some((i, t));
                    break;
                }
                _ => return None,
            }
        }
        let (idx, text) = tail?;
        let content = ast::trim_end_collapsible_ws(text.raw(self.source));
        let ch = content.chars().next_back()?;
        if !crate::whitespace::is_end_trimmed_content(ch) {
            return None;
        }
        // A comment after the text either travels with a hoisted section (and prints above the
        // template) or stays in the template, where it ends the document instead of the text.
        let is_comment = |i: usize| matches!(nodes[i], FragmentNode::Comment(_));
        if (idx + 1..nodes.len()).any(is_comment) {
            let travels = sections.travelling(nodes.len());
            if (idx + 1..nodes.len()).any(|i| is_comment(i) && !travels[i]) {
                return None;
            }
        }
        Some((
            text.raw_span.start as usize + content.len() - ch.len_utf8(),
            ch,
        ))
    }

    /// The comment run that ENDS the fragment — comments after the last real template node,
    /// with nothing but whitespace between them and the end — when a `<style>` prints after
    /// the template, as fragment indices in source order. Printed as the style's leading run
    /// rather than as template content, for one fixed point: printed at the template's end,
    /// that run sits directly above the `<style>` in the OUTPUT, so the next pass reads it as
    /// the style's leading comments (that is what a comment above a section is) and inserts the
    /// section blank above it — a second pass that differs from the first.
    /// prettier-plugin-svelte converges on that second form too, so it is the one pass prints.
    /// A region-end trail is stepped over (it is the section's own, already placed); a range
    /// marker or a comment inside a frozen range ends the run, since moving either would move
    /// the freeze.
    fn style_trailing_comments(
        &self,
        root: &ast::Root<'_>,
        sections: &HoistedComments,
    ) -> Vec<usize> {
        let mut run: Vec<usize> = Vec::new();
        if root.css.is_none() {
            return run;
        }
        let nodes = &root.fragment.nodes;
        let travels = sections.travelling(nodes.len());
        for (i, node) in nodes.iter().enumerate().rev() {
            match node {
                FragmentNode::Text(t) if t.is_collapsible_ws_only => {}
                FragmentNode::Comment(_) if sections.0.iter().any(|s| s.trail == Some(i)) => {}
                FragmentNode::Comment(_) if !travels[i] => {
                    let ranges = self.ignore_ranges(&root.fragment);
                    if ranges.markers[i].is_some() || ranges.contains(i) {
                        break;
                    }
                    run.push(i);
                }
                _ => break,
            }
        }
        run.reverse();
        run
    }

    /// Format a Svelte Root node
    ///
    /// Orchestrates formatting of the four main sections of a .svelte file:
    /// 1. Module script: `<script context="module">`
    /// 2. Instance script: `<script>`
    /// 3. Template: The HTML/Svelte template
    /// 4. Style: `<style>`
    ///
    /// Sections are ordered canonically and separated by blank lines.
    /// Comments travel with the section they immediately precede in source order — and a
    /// `#endregion` marker directly after a section travels below it
    /// ([`Self::region_end_trails`]).
    fn print_root(
        &mut self,
        root: &ast::Root<'_>,
        sections: &HoistedComments,
        frozen: FrozenSections,
    ) {
        // Sections are lifted off the fragment and printed at canonical positions, but a
        // `format-ignore` range's verbatim slice is raw source and would re-emit any that sits
        // inside it — see `build_ignore_range_doc`.
        let hoisted: SmallVec<[Span; 4]> = root_sections(root)
            .into_iter()
            .filter_map(|(span, _)| span)
            .collect();

        // Non-template comments are skipped during fragment printing
        let mut printed_comment_indices: Vec<usize> = Vec::new();
        for section in &sections.0 {
            printed_comment_indices.extend(&section.leading);
            printed_comment_indices.extend(section.trail);
        }

        // The comment run that ends the fragment prints as the style's leading run
        // (`Self::style_trailing_comments`).
        let style_trailing = self.style_trailing_comments(root, sections);
        printed_comment_indices.extend(&style_trailing);

        let mut has_previous_section = false;

        // Format svelte:options (if present) - always first
        if let Some(options) = &root.options {
            let comments = &sections[HoistedSection::Options];
            self.print_section_comments(&comments.leading, &root.fragment, options.span.start);
            self.print_svelte_options(options);
            self.print_region_end_trail(comments.trail, &root.fragment, options.span.end);
            has_previous_section = true;
        }

        // Format scripts (module then instance)
        for (script, section) in [
            (root.module.as_ref(), HoistedSection::ModuleScript),
            (root.instance.as_ref(), HoistedSection::InstanceScript),
        ] {
            let comments = &sections[section];
            if let Some(script) = script {
                if has_previous_section {
                    self.write("\n"); // Blank line between sections
                }
                self.print_section_comments(&comments.leading, &root.fragment, script.span.start);
                if frozen[section.slot()] {
                    self.write_verbatim_span(script.span);
                    self.write("\n");
                } else {
                    self.print_script(script);
                }
                self.print_region_end_trail(comments.trail, &root.fragment, script.span.end);
                has_previous_section = true;
            }
        }

        // Format template fragment (if not empty)
        let has_content = root.fragment.nodes.iter().enumerate().any(|(i, node)| {
            if printed_comment_indices.contains(&i) {
                return false;
            }
            !matches!(node, FragmentNode::Text(text) if text.is_collapsible_ws_only)
        });

        if has_content {
            if has_previous_section {
                self.write("\n"); // Blank line between sections
            }
            self.print_root_fragment(&root.fragment, &printed_comment_indices, &hoisted);
            self.write("\n"); // Template needs explicit newline
            has_previous_section = true;
        }

        // Format style (if present)
        if let Some(style) = &root.css {
            let ignore_style = frozen[HoistedSection::Style.slot()];
            if has_previous_section {
                self.write("\n"); // Blank line between sections
            }
            if self
                .print_comment_run(&style_trailing, &root.fragment)
                .is_some()
            {
                // The run stands off the style's own leading run (or the tag) by a blank line —
                // the section blank it earned as template content, which is also where the
                // second pass would put it.
                self.write("\n");
            }
            let comments = &sections[HoistedSection::Style];
            self.print_section_comments(&comments.leading, &root.fragment, style.span.start);
            if ignore_style {
                self.write_verbatim_span(style.span);
                self.write("\n");
            } else {
                self.print_style(style);
            }
            self.print_region_end_trail(comments.trail, &root.fragment, style.span.end);
        }
    }

    /// Format the `<svelte:options ... />` tag, always in the self-closing form.
    ///
    /// Hoisted out of the fragment and printed here at its canonical position, so it is the
    /// one tag head outside the element pipeline — but its attribute list is read by the
    /// ordinary `read_attribute` like any other, comments included, so it goes through the
    /// same [`Printer::push_attrs_with_comments`] the pipeline uses. Doc-based from there on,
    /// for width-aware wrapping.
    fn print_svelte_options(&mut self, options: &ast::SvelteOptions<'_>) {
        let d = self.d();
        // Built before the empty check, not after: the attribute list can be empty and still
        // carry comments (`<svelte:options /* c */ />`), and an early return keyed on
        // `attributes.is_empty()` deletes them — the comment-blind alternate arm, at the one
        // tag whose head is printed from here rather than from the element pipeline.
        let mut parts: DocBuf = DocBuf::with_capacity(options.attributes.len() * 2);
        self.push_attrs_with_comments(
            &mut parts,
            options.attributes,
            d.line(),
            AttrGaps {
                first_range_start: options.name_end,
                open_tag_end: options.open_tag_end,
                // Nothing here is synthesized: `<svelte:options>` has no `this` binding, so
                // every attribute in the window is in `attributes`.
                claimed: None,
            },
            false,
        );
        if parts.is_empty() {
            self.write("<svelte:options />\n");
            return;
        }

        let attrs = d.concat(&parts);
        // A comment's own break counts the same as an attribute value's — both are reasons
        // the head cannot stay on one line — so the question is asked of the assembled list.
        let has_multiline = d.will_break(attrs);
        let attr_indent = d.indent(attrs);
        let line = d.line();
        let inner = d.concat(&[d.text("<svelte:options"), attr_indent, line, d.text("/>")]);

        let group = if has_multiline {
            d.group_break(inner)
        } else {
            d.group(inner)
        };

        self.render_doc_immediate(group);
        self.write("\n");
    }

    /// Render the whole template fragment through the same doc-based content path the
    /// elements use — the root is **not special**.
    ///
    /// Prettier prints the root markup with the same `printChildren` as element children,
    /// just inside a force-broken `group([…, hardline])`. [`Printer::build_nodes_doc_multiline`]
    /// *is* that force-broken layout, so the root's sibling separation, blank-line handling,
    /// block hugging, and the inline-element `>`-fold all come from the shared builder. Three
    /// root-only concerns are handled around that call:
    ///
    /// - **Boundary trim (B1):** the template content is the span of `fragment.nodes` from the
    ///   first to the last node that isn't a section comment printed with its section
    ///   (`skip_indices`) and isn't leading/trailing Unicode-whitespace-only text. Prettier trims
    ///   the fragment boundary with a Unicode `trim()`, so a leading nbsp-only node (content
    ///   mid-template) is dropped here. Section comments are *usually* boundary-contiguous, but a
    ///   section sitting mid-template leaves one interior; those are dropped by the segmentation
    ///   loop below (they are already printed with their hoisted section).
    /// - **Single-line inline runs (B4):** a `{x}{#if c}…{/if}` run with no newline must
    ///   *inner-break* a long body, not drop it — the load-bearing discriminator the element
    ///   path does not apply. [`Self::mark_root_inline_run_blocks`] marks those blocks so the
    ///   shared builder builds them in inline context (see `root_inline_run_block_starts`).
    /// - **`format-ignore` ranges (B6):** `<!-- format-ignore-start -->` … `-end` is a
    ///   *root-only* directive (it does not activate inside an element), so the content is
    ///   split at top-level ranges: each range emits its source verbatim up to its end marker,
    ///   and the surrounding segments go through the shared builder — the end marker heading the
    ///   segment after it, glued to the slice ([`Printer::build_range_tail_doc`]). (Single-node
    ///   `format-ignore` is handled by the shared builder itself.)
    fn print_root_fragment(
        &mut self,
        fragment: &ast::Fragment<'_>,
        skip_indices: &[usize],
        hoisted: &[Span],
    ) {
        // Effective template range: drop section comments (`skip_indices`) and collapsible-ws-only
        // boundary text. Both kinds only occur at the boundaries, so the kept content is a
        // contiguous slice.
        //
        // ⚠️ The class is `is_collapsible_ws` (the parser's precomputed `is_collapsible_ws_only`
        // flag, keyed on `raw`), NOT `str::trim` (the Unicode `White_Space` property, which is
        // wider). The root fragment is a fragment like any other, so it owes the same rule every
        // element boundary follows: the trim stops at content. `str::trim`
        // deleted a root-boundary NBSP — content the compiler keeps (`regex_not_whitespace` =
        // `/[^ \t\r\n]/` matches U+00A0, so the node is not whitespace-only and survives:
        // `\u{a0}<div>block</div>` compiles to `<!---->\u{a0}<div>…`). prettier deletes it too,
        // so only the compiler oracle sees it — `svelte/elements/root_leading_nbsp_prettier_divergence`.
        let skippable = |i: usize, n: &FragmentNode<'_>| {
            skip_indices.contains(&i)
                || matches!(n, FragmentNode::Text(t) if t.is_collapsible_ws_only)
        };
        let Some(start) = fragment
            .nodes
            .iter()
            .enumerate()
            .position(|(i, n)| !skippable(i, n))
        else {
            return;
        };
        // `rposition` finds at least `start`, so the fallback never triggers (panic-free).
        let end = fragment
            .nodes
            .iter()
            .enumerate()
            .rposition(|(i, n)| !skippable(i, n))
            .unwrap_or(start);
        let nodes = &fragment.nodes[start..=end];

        // Mark single-line-run control-flow blocks so the shared builder inner-breaks them (B4).
        self.mark_root_inline_run_blocks(nodes);

        // The ranges are paired over the whole fragment; the slice drops only whitespace text and
        // section comments, and a range marker is never a section comment (it pins itself to the
        // template), so every marker is in the slice and the pairing is the slice's own.
        let ranges = self.ignore_ranges(fragment);
        debug_assert!(
            skip_indices.iter().all(|&k| ranges.markers[k].is_none()),
            "a range marker never travels with a section"
        );

        // Split at `format-ignore` ranges and at interior section comments (both rare); most
        // templates are one segment.
        let mut out: DocBuf = DocBuf::new();
        let mut seg_start = 0;
        // Whether the segment starting at `seg_start` is a range's tail — headed by its end
        // marker, and so glued to the frozen slice before it (`build_range_tail_doc`).
        let mut seg_is_range_tail = false;
        let mut i = 0;
        while i < nodes.len() {
            // A comment printed with its (hoisted) section — `skip_indices` indexes the full
            // `fragment.nodes`, so offset by `start`. These are *usually* boundary-contiguous
            // (trimmed away by `start`/`end`), but a `<script>`/`<style>`/`<svelte:options>`
            // sitting **mid-template** (template content on both sides) leaves its comment
            // interior to the slice. Drop it here so the shared builder doesn't re-emit it as
            // template content (it is already printed with its section). The gap is re-bridged
            // with `hoisted_comment_separator`.
            if skip_indices.contains(&(start + i)) {
                if nodes[seg_start..i]
                    .iter()
                    .any(|n| !n.is_whitespace_only_text())
                {
                    out.push(self.build_segment_doc(&nodes[seg_start..i], seg_is_range_tail));
                    // TODO: this bridge still reads the hoisted comment's follower through
                    // `hoisted_comment_separator`, which answers adjacency with a hardline — a
                    // rendered space between two glued neighbours. It is reachable only when the
                    // lifted-runs rewrite declines (`LiftRuns::Declined`: the rewritten source
                    // fails to parse, in practice only past the size limit), since the rewrite
                    // otherwise takes every mid-template section and its comments out of the
                    // template. The range tail answers the same question by letting the shared
                    // builder lay out the gap (`build_range_tail_doc`); this one needs its own
                    // fixture cycle.
                    if let Some(sep) = self.hoisted_comment_separator(nodes, i) {
                        out.push(sep);
                    }
                }
                seg_is_range_tail = false;
                seg_start = i + 1;
                i += 1;
                continue;
            }
            if let Some(range_end) = ranges.end_of(start + i).map(|end| end - start) {
                // Segment up to and including the start comment (it prints normally).
                out.push(self.build_segment_doc(&nodes[seg_start..=i], seg_is_range_tail));
                // Verbatim source from just after the start comment up to the end comment —
                // emit the slice as a span, no allocation.
                let raw_start = nodes[i].span().end;
                let raw_end = nodes[range_end].span().start;
                out.push(self.build_ignore_range_doc(Span::new(raw_start, raw_end), hoisted));
                // The end comment heads the next segment rather than ending the slice, so the
                // shared builder lays out the whitespace after it — the only bytes of the range's
                // boundary that are the printer's — exactly as it does after any comment.
                seg_start = range_end;
                seg_is_range_tail = true;
                i = range_end + 1;
                continue;
            }
            i += 1;
        }
        if seg_start < nodes.len() {
            out.push(self.build_segment_doc(&nodes[seg_start..], seg_is_range_tail));
        }

        if !out.is_empty() {
            let doc = self.d().concat(&out);
            self.render_doc_immediate(doc);
        }
    }

    /// One root segment's doc: a range's tail ([`Printer::build_range_tail_doc`]) when its end
    /// marker heads it, else the shared multiline builder.
    fn build_segment_doc(&self, nodes: &[FragmentNode<'_>], range_tail: bool) -> DocId {
        if range_tail {
            self.build_range_tail_doc(nodes)
        } else {
            self.build_nodes_doc_multiline(nodes)
        }
    }

    /// The verbatim doc for a `format-ignore` range slice, with every **hoisted section** cut out.
    ///
    /// A `<script>` / `<style>` / `<svelte:options>` written inside the range is not a fragment
    /// node — it is lifted onto [`ast::Root`] and printed at its canonical position — but
    /// this slice is *raw source* between the two markers, which still holds its bytes. Emitting
    /// them verbatim prints the section **twice**, and the result is not a valid component:
    /// tsv's own parser rejects it (`Duplicate instance script found` / `Duplicate style tag
    /// found` / ``A component can only have one `<svelte:options>` element``). So the slice
    /// is emitted as the pieces *between* the hoisted spans. Prettier drops the section from
    /// its own ignored range the same way; the range freezes template formatting, it does not
    /// pin a section's position.
    ///
    /// The cuts are [`lifted_runs::range_cuts`]'s — the source rewrite that joins the neighbours
    /// of a section lifted out from between template nodes makes the same ones — and each takes
    /// the sections with the whitespace around them, leaving the one run of the author's that
    /// best separates the neighbours: source `</div>⏎⏎<script>…</script>⏎⏎<p>` ends at
    /// `</div>⏎⏎<p>`, and `{a} <script>…</script>{b}` at `{a} {b}`, since the section renders
    /// nothing where it was written and the space is all that separates the two. A glued cut
    /// whose two texts would join into a character reference neither spelled writes the first
    /// character after it as a reference instead (`x&amp` + `;y` → `x&amp&#x3B;y`,
    /// [`lifted_runs::RangeCut::respell`]) — the one byte of the slice's text the cut changes.
    fn build_ignore_range_doc(&self, span: Span, hoisted: &[Span]) -> DocId {
        let mut sections: SmallVec<[Span; 4]> = hoisted
            .iter()
            .copied()
            .filter(|h| span.contains(*h))
            .collect();
        if sections.is_empty() {
            return self.source_span_covering_comments_doc(span);
        }
        // `hoisted` is in canonical print order (options, module, instance, style), which is not
        // source order — the pieces must be emitted in source order.
        sections.sort_unstable_by_key(|s| s.start);

        let mut parts: DocBuf = DocBuf::new();
        let mut cursor = span.start;
        for cut in lifted_runs::range_cuts(self.source, span.start, &sections) {
            if cut.removed.start > cursor {
                parts.push(
                    self.source_span_covering_comments_doc(Span::new(cursor, cut.removed.start)),
                );
            }
            match cut.seam {
                lifted_runs::RangeSeam::Kept(seam) => {
                    parts.push(self.source_span_covering_comments_doc(seam));
                }
                lifted_runs::RangeSeam::Space => parts.push(self.d().text(" ")),
                lifted_runs::RangeSeam::Glued => {}
            }
            // The text after the cut would complete a reference with the text before it.
            if let Some(ch) = cut.respell {
                let mut reference = String::new();
                push_char_reference(&mut reference, ch);
                parts.push(self.d().text_pooled(&reference));
            }
            cursor = cut.resume();
        }
        if cursor < span.end {
            parts.push(self.source_span_covering_comments_doc(Span::new(cursor, span.end)));
        }
        self.d().concat(&parts)
    }

    /// Mark control-flow blocks in **single-line** root inline runs (`{x}{#if c}…{/if}` with no
    /// newline) so [`Printer::build_nodes_doc_multiline`] builds them in inline context — see
    /// [`Printer::root_inline_run_block_starts`]. A *multi-line* run (its content text spans
    /// source lines) keeps the multiline layout, so its blocks are left unmarked. Span-keyed,
    /// so only root-level run blocks are affected.
    fn mark_root_inline_run_blocks(&self, nodes: &[FragmentNode<'_>]) {
        let mut marks = self.root_inline_run_block_starts.borrow_mut();
        marks.clear();
        let mut i = 0;
        while i < nodes.len() {
            if let Some(run_end) = self.detect_root_inline_run(nodes, i) {
                let run = &nodes[i..=run_end];
                let multiline = run
                    .iter()
                    .any(|n| matches!(n, FragmentNode::Text(t) if t.has_newline()));
                if !multiline {
                    for n in run {
                        if nodes::is_control_flow_block(n) {
                            marks.insert(n.span().start);
                        }
                    }
                }
                i = run_end + 1;
            } else {
                i += 1;
            }
        }
    }

    /// The separator bridging a mid-template hoisted-section comment the root segmentation
    /// dropped, before the next segment: the whitespace immediately following the comment (which
    /// the next segment's boundary trim would otherwise drop). A blank line → `literalline` (the
    /// un-indented blank) + `hardline`; a single newline / adjacency → `hardline`. `None` when
    /// nothing follows.
    ///
    /// "Immediately following" is the whole rule, so the blank is read off the next node's
    /// **leading** whitespace run ([`text::has_leading_blank_line`]) rather than its text as a
    /// whole. A total newline count answers a different question and fabricates: trailing text
    /// that merely spans two lines (`-->⏎text1⏎text2`) reaches 2 newlines without the author
    /// writing a blank, and a blank *inside* that text (`-->⏎text1⏎⏎text2`) belongs to the text —
    /// relaying it here would relocate the author's blank onto the seam.
    fn hoisted_comment_separator(
        &self,
        nodes: &[FragmentNode<'_>],
        comment_idx: usize,
    ) -> Option<DocId> {
        if comment_idx + 1 >= nodes.len() {
            return None;
        }
        let d = self.d();
        let blank = matches!(
            &nodes[comment_idx + 1],
            FragmentNode::Text(t) if text::has_leading_blank_line(t.raw(self.source))
        );
        Some(if blank {
            d.concat(&[d.literalline(), d.hardline()])
        } else {
            d.hardline()
        })
    }

    /// Detect a "root inline run" starting at `start_idx` in the root fragment.
    ///
    /// A run is a maximal span-adjacent (no whitespace gap in source) sequence that
    /// contains at least one control-flow block **and** at least one content-text or
    /// inline node — e.g. `text{#if}…{/if}text`, `{#each}…{/each}text`, `{x}{#if}…`,
    /// or several chained together. The run renders through the element-content path
    /// (`build_nodes_doc_multiline`) so a directly-adjacent block hugs its text/inline
    /// neighbors (matching prettier and the inside-an-element layout) instead of the
    /// per-node root printer forcing a newline around the block (which would inject
    /// render-significant whitespace — a no-whitespace boundary must never gain a space).
    ///
    /// The walk starts at content text, an inline node, or a control-flow block, and
    /// breaks on whitespace-only text, a non-adjacent node, or any other node (block
    /// element, comment, `{@const}`/`{@debug}`, `{const}`/`{let}`). A content-text node
    /// bridges across the boundary (its content hugs, its own internal/edge newlines
    /// become line breaks in the multiline layout); the run's leading/trailing edge
    /// whitespace is carried as
    /// `pending_ws` by the caller. Lone blocks and pure-inline (no control-flow)
    /// sequences return `None`, keeping the per-node path's behavior for them.
    ///
    /// Returns `Some(end_idx)` (inclusive) for a qualifying run, else `None`.
    fn detect_root_inline_run(
        &self,
        nodes: &[FragmentNode<'_>],
        start_idx: usize,
    ) -> Option<usize> {
        let is_content_text =
            |n: &FragmentNode<'_>| matches!(n, FragmentNode::Text(t) if !t.is_collapsible_ws_only);

        // The start must be a node that can participate in a run.
        let start = &nodes[start_idx];
        if !(is_content_text(start)
            || self.is_inline_run_node(start)
            || nodes::is_control_flow_block(start))
        {
            return None;
        }

        let mut last_idx = start_idx;
        let mut has_control_flow = nodes::is_control_flow_block(start);
        let mut has_content_or_inline = is_content_text(start) || self.is_inline_run_node(start);

        for j in (start_idx + 1)..nodes.len() {
            tsv_lang::fanout_probe::predicate();
            // Must be directly adjacent (no whitespace gap in source).
            if nodes[j - 1].span().end != nodes[j].span().start {
                break;
            }

            let node = &nodes[j];
            if let FragmentNode::Text(text) = node {
                // Whitespace-only text separates runs (intentional separation).
                if text.is_collapsible_ws_only {
                    break;
                }
                last_idx = j;
                has_content_or_inline = true;
            } else if nodes::is_control_flow_block(node) {
                last_idx = j;
                has_control_flow = true;
            } else if self.is_inline_run_node(node) {
                last_idx = j;
                has_content_or_inline = true;
            } else {
                // Block element, comment, `{@const}`/`{@debug}`, etc. end the run.
                break;
            }
        }

        // Only route runs that genuinely need hugging: a control-flow block plus an
        // adjacent content-text/inline node. A lone block (`last_idx == start_idx`) or a
        // pure-inline / pure-block sequence keeps the per-node path's existing behavior.
        (has_control_flow && has_content_or_inline && last_idx > start_idx).then_some(last_idx)
    }

    /// Check if a fragment node can participate in an inline run (as start or intermediate node).
    fn is_inline_run_node(&self, node: &FragmentNode<'_>) -> bool {
        match node {
            FragmentNode::ExpressionTag(_)
            | FragmentNode::HtmlTag(_)
            | FragmentNode::RenderTag(_) => true,
            FragmentNode::Element(el) => !self.is_block_element(el),
            FragmentNode::SpecialElement(el) => !el.kind.is_block(),
            _ => false,
        }
    }

    /// Format an HTML comment: <!-- content -->
    fn print_comment(&mut self, comment: &ast::HtmlComment) {
        // The hoisted-section (direct-write) emit path for a `<!-- -->` comment, recorded at
        // the write like `tsv_css`'s `print_css_comment`; the template path is the doc-tagged
        // `build_html_comment_doc`. Registered by span in `format_svelte_in`. See
        // `tsv_lang::comment_ledger`.
        #[cfg(feature = "_internal_comment_check")]
        tsv_lang::comment_ledger::record_emitted(self.source, comment.span);

        // Verbatim whole span (`<!--…-->`), not re-assembled delimiters — see
        // `build_html_comment_doc`, the doc-path twin.
        self.write(comment.span.extract(self.source));
    }
}