flm-core 0.7.0

FLM semantic markup framework — core library, built on techy
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
//! The text emitter: it walks the text backend's lowered trees and lowered
//! pieces, builds one layout document from them, and prints it into a
//! [`TextOutput`].
//!
//! An emitter is a backend's emit stage: it walks the lowered trees and writes
//! the output's bytes into a table, from which the backend's final stage makes
//! the artifact set (see [backends, lowering, and
//! outputs](crate::guide::concepts_overview#backends-lowering-and-outputs)).
//! [`emit()`] is this module's entry point; the emit stage
//! ([`TextEmitStage`](super::stages::TextEmitStage)) calls it once per run.
//! The [layout engine](crate::layout) breaks the lines, indents and pads; this
//! module maps each presentation element onto the engine's constructors and
//! lets the engine produce the characters.
//!
//! # The pieces and the content
//!
//! The emitter prints, in order, the pieces placed before the content (such
//! as the title, the authors, the date and the table of contents), the
//! lowered trees in document order, and the pieces placed after the content
//! (such as the list of notes), each one blank line after the one before it.
//! A piece or a tree that prints nothing adds no blank line, so a document
//! with no piece starts with its content.
//!
//! # What each element prints
//!
//! In a **run of blocks** (a tree's top level, a block's body, a list item),
//! blocks are separated by one blank line. The blocks of a run are `par`,
//! `block`, `block-heading`, `list`, `cells`, `lines`, `subtree`, the construct
//! element `text.ruled`, a block `image`, a block `verbatim` and an `unknown`
//! environment, and the containers holding one of them. Everything else in
//! the run, a displayed formula, `unsupported` and `dropped` included, is
//! inline content: each maximal stretch of it is filled as one paragraph, as
//! inside a `par`, so a displayed formula takes lines of its own with no blank
//! line beside it, and a blank line separates blocks only. The table below
//! says how each element prints wherever it stands in a run of blocks:
//!
//! | lowered element | printed as |
//! |---|---|
//! | `par` | its inline content, filled word by word; decorations printed at their decoration marks |
//! | `block-heading` | the heading text, then a rule under it (see below) |
//! | `block` | its body as a run of blocks; the role and the kinds are dropped; a decoration whose decoration mark is among its blocks prints at that decoration mark, on a line of its own when a block follows |
//! | `list` | one entry per label/item pair, the item hanging after the label (see below) |
//! | `cells` | one table of the layout engine: each cell's blocks in its column, in the cell's own alignment, a spanned cell's content at the first position of its span; the leading rows of column headers above a rule (see below) |
//! | `lines` / `line` | one printed line per `line`, indented by its `indent_left` converted to columns ([`TextRenderOptions::columns`]) |
//! | `verbatim` (block) | the content byte for byte, indented like its surroundings |
//! | `unsupported` | `[unsupported: <element>]` |
//! | `dropped` | `[dropped: <detail>]` |
//! | `unknown` (environment) | its begin and end lines around its body blocks (see below) |
//! | `image` (block) | `[image: <alt or src>]` |
//! | `subtree` | the placed tree's lowered blocks, printed at this node |
//! | `text.ruled` ([`RULED`]) | its body as a run of blocks, with a rule line above it and one under it as its payload asks (see below) |
//! | `flm.container`, `flm.group`, `flm.opaque-wrapper` | their children: as a run of blocks when a block of a run is among their descendants, otherwise as inline content filled with the text around them |
//! | `flm.comment`, `flm.parbreak` | nothing; the blocks on either side of them are separate |
//!
//! The rows that need more room:
//!
//! - An unattributed environment (an environment no feature declares) prints
//!   `\begin{name}` on a line of its own, then its lowered body as a run of
//!   blocks, then `\end{name}` on a line of its own.
//! - A `block-heading` prints the heading text, then a rule as wide as the
//!   widest line that text prints, so a title that wraps gets a rule as wide
//!   as its longest line: `=` for a heading at the root heading level
//!   ([`TextRenderOptions::root_heading_level`], 1 by default), `-` for a
//!   heading one level deeper, or `═` and `─` when
//!   [`TextRenderOptions::heading_rules`] is
//!   [`Unicode`](super::HeadingRules::Unicode). A heading deeper still has no
//!   rule; it is preceded by `#` characters and a space: three `#` two levels
//!   below the root, one more for each further level. A heading above the root
//!   level is reported as `flm.pres.heading-above-root`
//!   ([`HeadingAboveRoot`](crate::stdlib::backends::pres::HeadingAboveRoot))
//!   and printed like one at the root level.
//! - A `list` prints, for each entry, the label's text (a superscript or
//!   subscript span in it written as in running text, below), padded to the
//!   width of the widest label plus one, and the item's blocks hanging at that
//!   column; when every label of the list is empty, the items start at the
//!   margin. An entry with an empty item prints its label alone. Entries are
//!   one blank line apart.
//! - A `cells` table is laid out as one table of the layout engine
//!   ([`DocBuf::table`]): one column per column of the grid, the column widths
//!   computed from their cells' content, each cell's blocks printed at its
//!   column's width and padded in the cell's own alignment (left where it has
//!   none). The positions covered by a span, other than the span's first, print
//!   nothing. The leading rows whose cells all head their columns are the
//!   header rows. [`TextRenderOptions::table_frame`] chooses how the table is
//!   drawn: its columns two spaces apart with a rule of `-` under the header
//!   rows (the default), or inside a frame of box-drawing characters with a
//!   rule of the frame under the header rows. Row headers, rules at the edges
//!   of cells and custom cell styles are not shown in this output.
//! - A `text.ruled` node, the construct element `flm.pres.text.ruled`
//!   ([`RULED`], [`RuledPayload`]), prints its body as a run of blocks on lines
//!   of its own, with a rule line above it when its payload's `above` is set
//!   and one under it when `below` is set. A rule line is the character of a
//!   heading at the root level (`=`, or `═` under
//!   [`Unicode`](super::HeadingRules::Unicode) rules) repeated to the width of
//!   the widest line the body prints, written under the same indentation as
//!   the body ([`DocBuf::ruled`]). A body that prints nothing prints no rule
//!   line either.
//!
//! In **inline content**, text is split into words at breakable whitespace
//! ([`is_breakable_space`]: every whitespace character except the
//! non-breaking spaces); each word is an atom of the layout engine, each
//! space between two words a place where the line may break, and nothing is
//! escaped:
//!
//! | lowered element | printed as |
//! |---|---|
//! | `span` | its content; a superscript or subscript style converts its text (see below); a `Bold`, `Italic`, `Emphasis`, `Underline`, `Monospace` or `SmallCaps` style is recorded as a style mark (below) and not printed; any other style, the role, the document role and the kinds are dropped |
//! | `runin-heading` | its content, with a style mark; the payload is dropped |
//! | `link` | its content, with a style mark, then ` <address>` for a link to an address outside the document, as the render options say (below) |
//! | `math-passthrough` (inline) | one atom, `\(source\)`, each run of whitespace replaced by one space |
//! | `math-passthrough` (display) | on lines of its own, the source inside `\[…\]` (or `\begin{env}…\end{env}` for an environment), indented by two columns |
//! | `verbatim` (inline) | one atom; content holding a newline or a tab is printed as a block instead |
//! | `deco-mark` | the decoration, printed at its decoration mark (see below) |
//! | `text.flush-right` ([`FLUSH_RIGHT`]) | its content on one line, ending at the last column of the line width where the columns already on its line, a gap of [`FLUSH_RIGHT_GAP`] columns and the content fit there; otherwise, and where the line has no width, the gap and then the content after what precedes it ([`DocBuf::flush_right`]); content that cannot print on one line is reported ([`FlushRightLines`]) and printed where the node stands |
//! | `unknown` (macro) | its source spelling, `\name`, as one atom |
//! | `image` (inline), `unsupported`, `dropped` | as in a run of blocks, as one atom |
//! | a `flm.parbreak` | a space |
//! | any block of a run, inside inline content | on lines of its own |
//!
//! ## Decorations
//!
//! A decoration is a node whose element carries the
//! [`Decoration`](crate::stdlib::backends::pres::Decoration) aspect (a run-in
//! heading, a margin note, a closing mark); the lowering driver moves it out of
//! the content it was written in into an attached slot of the enclosing
//! presentation node, and leaves a decoration mark (a `flm.pres.deco-mark`
//! node) where it was (see [decorations, roles and
//! kinds](crate::guide::concepts_overview#decorations-roles-and-kinds)). The
//! emitter prints each decoration at its decoration mark, as one atom made of
//! its text:
//!
//! - a run-in decoration (`flm.pres.deco-runin`) as its text followed by the
//!   stop [`TextRenderOptions::run_in_stop`] (a period by default), then a
//!   breakable space. The stop is added only where the decoration's content
//!   does not already end in sentence punctuation (`.`, `,`, `:`, `;`, `?` or
//!   `!`, as [`ends_in_sentence_punctuation`] tests): a feature that wants
//!   another stop, for instance a colon after a defined term, writes it in the
//!   content, and the emitter adds nothing;
//! - a closing decoration (`flm.pres.deco-final`) after a non-breaking space
//!   (U+00A0), so that it never starts a line by itself;
//! - a margin decoration (`flm.pres.deco-margin`) as `[text]`, between
//!   breakable spaces.
//!
//! A decoration whose content holds no text prints nothing. A decoration that
//! was not moved (because the content it is written in belongs to no
//! presentation node, for instance at the top level of a fragment laid out as
//! inline content) prints the same way where it is written.
//!
//! ## Links
//!
//! Under the default render options, a `link` to an address outside the
//! document prints the address after its content, as ` <address>`; it prints
//! its content alone when [`TextRenderOptions::link_addresses`] is off. A link
//! whose content already shows its address (the payload's
//! [`shows_target`](crate::stdlib::backends::pres::LinkPayload::shows_target),
//! set by `\url` and `\email`) prints its content alone unless
//! [`TextRenderOptions::link_addresses_when_shown`] is on as well. A link to a
//! place inside the document (an address beginning with `#`) prints its
//! content alone. A link with no content prints `<address>` where the address
//! would be printed, and nothing otherwise.
//!
//! # Position marks: where a printed byte came from
//!
//! The emitter wraps every presentation node it prints in a mark of the layout
//! engine, and records which lowered node each mark stands for: a
//! [`LoweredAddr`], which gives the document tree the node was lowered from
//! and the node's position in that tree's lowered form. [`TextOutput::marks`]
//! holds the result ([`TextMark`]): a range of printed bytes leads to a
//! lowered node, which [`LoweredAddr::resolve`] finds in the lowered-trees
//! table; that node's span and provenance lead to the source the text was
//! written from. A position mark never refers to a node of a [frozen
//! tree](crate::guide::concepts_overview#frozen-trees-and-computed-data),
//! because a lowered node may stand for no single node of the document. The
//! bytes printed for a piece carry no mark.
//!
//! # Style marks: what plain text could not show
//!
//! Some content carries a property that plain text cannot show: a heading's
//! title, a bold or an emphasized span, the address of a link. The emitter
//! prints such content as plain text, and records where it printed it in a
//! *style mark* ([`TextStyleMark`], in [`TextOutput::styles`]). It also records
//! a style mark for the characters it draws to set content apart: the rule
//! under a heading, the rule lines of a `text.ruled` node, the frame or the
//! rule of a table. A style mark holds the byte range and the line and column
//! range of the characters it covers, and the property ([`TextStyle`]). A
//! program that writes the text to a medium able to show the property reads
//! the style marks; the extension `profile-tty`, which is compiled into the
//! `flm` program, paints them with terminal escape sequences. A style mark
//! never changes the printed text.
//!
//! The marks belong to the text backend, and the painting to the program
//! that writes the text. Only the printer knows where a node's content lands
//! once the lines are broken and indented, so only the backend can say which
//! bytes are bold. A medium's codes, such as a terminal's escape sequences,
//! belong to the program that writes to that medium: the text output stays
//! the same for every reader, and a medium is served without a backend of
//! its own that would lay the text out a second time.
//!
//! The printed ranges that get a style mark:
//!
//! | lowered node | style mark |
//! |---|---|
//! | `block-heading` | [`Heading`](TextStyle::Heading), holding the heading's depth below the root heading level, over the title as printed, with the `#` characters in front of a deep heading; the rule under a heading is outside it; [`HeadingRule`](TextStyle::HeadingRule) over that rule, and over the `#` characters with the space after them |
//! | `runin-heading` | [`Heading`](TextStyle::Heading), holding the heading's depth, over the title; the stop written after it is outside it |
//! | `span` of style `Bold`, `Italic`, `Emphasis`, `Underline`, `Monospace` or `SmallCaps` | the style of the same name over the span's content |
//! | `link` | [`Link`](TextStyle::Link), holding the link's target as the payload has it, over the link's content; the ` <address>` printed after it is outside it |
//! | `verbatim`, inline or as a block | [`Verbatim`](TextStyle::Verbatim) over the content |
//! | `cells` | [`TableBorder`](TextStyle::TableBorder) over each run of characters drawn for the table on a line: a whole frame line or rule line, each bar of a line of the rows |
//! | `text.ruled` | [`Rule`](TextStyle::Rule) over each rule line, one mark per line |
//!
//! A superscript or subscript span gets no style mark, since its text is
//! already written in Unicode superscript or subscript forms; nor does any
//! other node. The text of a list label and of a decoration (a run-in heading,
//! a theorem's heading) is printed as one piece of flattened text, and the
//! styled nodes inside it get style marks over their parts of that text. The
//! style marks are recorded inside pieces too (the title, the list of notes,
//! the bibliography, the table of contents), unlike the position marks, because
//! a piece is printed with the same styles as the document's content.
//! [`TextOutput::styles`] holds them in the order the printer reaches their
//! nodes, a node's mark before the marks inside it, and the ranges of two style
//! marks are either nested or apart. A styled node whose content prints no
//! character gets no style mark, so the range of a style mark is never empty.
//!
//! The content of a `cells` table has its position marks and style marks
//! like any other content, each over its text where the cell stands in the
//! table. They follow the marks of the table's node: first the table's
//! [`TableBorder`](TextStyle::TableBorder) marks, then the marks inside its
//! cells, row by row and column by column. A mark over several lines of a
//! cell is one range per line of the cell on which it covers a character,
//! each over that line's part of the cell's text and the ranges of one mark
//! consecutive, because the table prints the cell's lines between the frame
//! or the gutter and the other cells of the row. A range never covers a
//! character its cell did not print.
//!
//! # Further rules of the mapping
//!
//! - **A group inside verbatim content prints without its braces.** A parse
//!   never produces a group inside a [verbatim
//!   region](crate::guide::concepts_overview#verbatim-regions), since `{` is an
//!   ordinary character there. A content group found inside one is therefore
//!   the wrapper of an argument that a user definition's template
//!   ([`template`](crate::lang::rewrites::userdefs::template)) substituted
//!   there, and its braces belong to the syntax of the call, not to the
//!   content: its children are printed and its braces are not. Every other
//!   node inside verbatim content is printed as its source spelling, braces
//!   included, since a macro's braces are part of what the author wrote.
//! - **Mathematics prints as its source, with delimiters**: `\(…\)` for inline
//!   mathematics, `\[…\]` for display mathematics, `\begin{env}…\end{env}` for
//!   a math environment. The delimiters the author wrote are not part of the
//!   payload, so every way of writing inline mathematics prints as `\(…\)`.
//! - **A superscript span prints its text raised, a subscript span lowered**:
//!   each character of the span's text is written in its Unicode superscript or
//!   subscript form ([`superscript_form`], [`subscript_form`]), and a character
//!   that has none is written unchanged, so `10` is `¹⁰`, `a` is `ᵃ`, and `q`
//!   stays `q`. No marker such as `^` is added, since the output is read by a
//!   person. The conversion applies to the text of everything nested inside the
//!   span (a link, another span), and a nested span of the other of the two
//!   styles converts its own text its own way. What is not text of the document
//!   is written unchanged: the address printed after a link, mathematics and
//!   verbatim content (printed as their source), a decoration moved out of the
//!   span, a stand-in such as `[dropped: …]`.
//! - **What plain text cannot express is dropped without a diagnostic**: a
//!   span's style other than superscript and subscript (a `Bold`, `Italic`,
//!   `Emphasis`, `Underline`, `Monospace` or `SmallCaps` style recorded as a
//!   style mark, but not printed); the document role of a
//!   block, a span or a link; a link's accessible name; the role and kinds of a
//!   block or a span; a list's kinds; every anchor; an image's width and
//!   alternative sources; a line's right indentation and its alignment; a
//!   verbatim node's kind and language; a link's kind and a target inside the
//!   document. Presentation is dropped that way; content never is.
//! - **A lowered tree need not be structured into blocks.** Consecutive inline
//!   nodes in a run of blocks are filled together as one paragraph, split at
//!   the blocks of the run and at paragraph breaks, so a tree that went through
//!   no block-structure pass still prints.
//! - **The walk is bounded** by a depth limit, read once when the walk starts
//!   from the stack that remains on its worker thread for guarded operations:
//!   that stack divided by an estimate of the stack one level of the walk uses
//!   (12 KiB). At the top of a thread of the library, which declares
//!   [`WORKER_STACK_SIZE`](crate::lang::guard::WORKER_STACK_SIZE), the limit is
//!   just under 4096 levels; a thread that declares a smaller stack gives a
//!   smaller limit. A tree that nests deeper, counting the trees it places,
//!   prints nothing and is reported as `flm.text.nesting-too-deep`
//!   ([`NestingTooDeep`]).
//!
//! # Diagnostics
//!
//! The emitter reports, at error severity: [`MissingSubtree`] and
//! [`SubtreeCycle`] for a tree placed inside another that cannot be printed;
//! [`PiecePlacement`] for a piece that places a tree; [`NestingTooDeep`] for a
//! tree nested beyond the depth limit; [`NoWorkerThread`] when it cannot run at
//! all; [`FlushRightLines`] for content of a `text.flush-right` node that
//! cannot print on one line; and the presentation condition
//! `flm.pres.heading-above-root`
//! ([`HeadingAboveRoot`](crate::stdlib::backends::pres::HeadingAboveRoot))
//! for a heading above the root heading level. A
//! [condition](crate::guide::concepts_overview#diagnostics) is the typed body
//! of a diagnostic; each condition's documentation states what the emitter
//! prints instead.

use std::borrow::Cow;
use std::collections::BTreeSet;
use std::fmt;
use std::ops::Range;
use std::sync::Arc;

use techy::core::node::{NodeId, NodeKind, NodeRef, NodeTree};
use techy::error::{Diagnostic, DiagnosticInfo};
use techy::serialize::SerialValue;

use crate::model::addr::TreeId;
use crate::model::element::element_of;
use crate::core::data::table::{PieceClass, ProjectCx, SingletonTable, Table, TableName};
use crate::lang::guard;
use crate::lang::structural;
use crate::lang::{nowhere, Flm, FlmDiagnostics, FlmGroupType, FlmOrigin};
use crate::layout::{
    self, ColAlign, ColSpec, DocBuf, DocId, LineCol, MarkId, Profile, RawPolicy, TableCell,
    display_width, is_breakable_space, print, print_full,
};
use crate::core::piece::PiecePlace;
use crate::model::names::Name;
use crate::stdlib::backends::lowering::{LoweredAddr, LoweredTrees};
use crate::stdlib::backends::pieces::{LoweredPiece, LoweredPieces};
use crate::stdlib::backends::pres::{
    self, CellAlign, CellHeader, CellsPayload, DroppedPayload, GridPosition, HeadingPayload, ImageDisplay, ImagePayload, LinePayload, LinkPayload, MathDisplay,
    MathPassthroughPayload, MathTextPayload, SpanPayload, SpanStyle, SubtreePayload, UnknownKind,
    UnknownPayload, UnsupportedPayload, VerbatimDisplay, VerbatimPayload, cells_of, decoration_at,
    ends_in_sentence_punctuation, heading_depth, holds_text, is_presentation, list_entries,
    payload_of, plain_text, recompose_source,
};

use super::construct::{FLUSH_RIGHT, FLUSH_RIGHT_GAP, RULED, RuledPayload};
use super::stages::{TableFrame, TextRenderOptions};
use super::superscript::{subscript_form, superscript_form};

// --- the output table --------------------------------------------------------------------

/// A position mark of the text output: where the text printed for one lowered
/// node is in [`TextOutput::text`].
///
/// It holds the layout engine's mark identifier, the lowered node it stands
/// for, and the byte range and the line and column range of that node's printed
/// content characters. [`TextOutput::marks`] holds one per printed presentation
/// node, except a node printed over several lines of a table's cell, which has
/// one mark per line of the cell on which it prints a character (see the
/// [module documentation](self#style-marks-what-plain-text-could-not-show));
/// and [`TextOutput::slice`] returns the text it covers.
///
/// Two runs over the same document produce equal marks, because a lowered node
/// is addressed by its position rather than by an identifier assigned during
/// the run.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextMark {
    /// The layout engine's identifier of the mark. The emitter assigns
    /// identifiers in the order it builds the marked parts, so the mark of an
    /// enclosing node has a larger identifier than the marks inside it; the
    /// order of [`TextOutput::marks`] is the order in which the printer opens
    /// the marks.
    pub id: MarkId,
    /// The lowered node this mark stands for. Find the node in the backend's
    /// lowered-trees table with
    /// [`LoweredAddr::resolve`](crate::stdlib::backends::lowering::LoweredAddr::resolve);
    /// the address refers to no node of a [frozen
    /// tree](crate::guide::concepts_overview#frozen-trees-and-computed-data).
    pub addr: LoweredAddr,
    /// The byte range of [`TextOutput::text`] that holds the node's printed
    /// content characters.
    pub bytes: Range<usize>,
    /// The line and column of the first content character printed for the
    /// node, counted from 0.
    pub start: LineCol,
    /// The line and column just after the last content character printed for
    /// the node.
    pub end: LineCol,
}

/// What a style mark ([`TextStyleMark`]) says about the printed range it
/// covers: a property of the content that plain text cannot show, such as
/// bold weight or the address of a link, or the characters the text output
/// draws to set content apart, such as the rule under a heading.
///
/// The emitter records one for each presentation node that carries such a
/// property, and one for each such drawing (the
/// [module documentation](self#style-marks-what-plain-text-could-not-show)
/// lists them). A program that writes the text to a medium able to show the
/// property reads the style marks: the extension `profile-tty`, which is
/// compiled into the `flm` program, paints them with terminal escape
/// sequences.
///
/// # Examples
///
/// ```
/// use flm_core::stdlib::backends::text::TextStyle;
///
/// assert_eq!(TextStyle::Bold.name(), "bold");
/// let link = TextStyle::Link { href: String::from("https://example.com") };
/// assert_eq!(link.name(), "link");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TextStyle {
    /// The title of a heading, block or run-in.
    Heading {
        /// How deep the heading is below the root heading level, as
        /// [`heading_depth`] counts it: 0 for a heading at the root level
        /// ([`TextRenderOptions::root_heading_level`]), 1 for one level
        /// deeper, and so on; 0 for a heading above the root level.
        depth: u8,
    },
    /// The characters the text output draws to mark a heading: the rule
    /// under a heading at depth 0 or 1, and the `#` characters in front of a
    /// deeper heading, with the space after them.
    HeadingRule {
        /// The depth of the heading the characters mark, as for
        /// [`Heading`](Self::Heading).
        depth: u8,
    },
    /// A rule line the text output draws above or under the body of a
    /// [`flm.pres.text.ruled`](super::construct::RULED) node, such as the
    /// rules around a document's title. The emitter records one mark for each
    /// rule line.
    Rule,
    /// The characters the text output draws for a table: its frame, or the
    /// rule of `-` under its header rows
    /// ([`TextRenderOptions::table_frame`]).
    /// The emitter records one mark for each maximal run of such characters on
    /// a line: a whole rule or frame line, and each bar before, between and
    /// after the cells on its own; the padding spaces around the cells are
    /// outside them.
    TableBorder,
    /// A span of bold weight (`\textbf`).
    Bold,
    /// A span of italic shape (`\textit`).
    Italic,
    /// A span of semantic emphasis (`\emph`).
    Emphasis,
    /// An underlined span.
    Underline,
    /// A span in a monospaced face (`\texttt`).
    Monospace,
    /// A span in small capitals.
    SmallCaps,
    /// Verbatim content, inline or as a block.
    Verbatim,
    /// The content of a link, without the address the text output may print
    /// after it.
    Link {
        /// The link's target exactly as the link's payload holds it
        /// ([`LinkPayload::href`](crate::stdlib::backends::pres::LinkPayload::href)):
        /// `#` followed by an anchor for a place inside the document, an
        /// address otherwise.
        href: String,
    },
}

impl TextStyle {
    /// Returns the style's name as the projection of [`TextOutput`] writes it
    /// (the `style` key of each style mark): `heading`, `heading-rule`, `rule`,
    /// `table-border`, `bold`, `italic`, `emphasis`, `underline`, `monospace`,
    /// `small-caps`, `verbatim` or `link`.
    pub fn name(&self) -> &'static str {
        match self {
            TextStyle::Heading { .. } => "heading",
            TextStyle::HeadingRule { .. } => "heading-rule",
            TextStyle::Rule => "rule",
            TextStyle::TableBorder => "table-border",
            TextStyle::Bold => "bold",
            TextStyle::Italic => "italic",
            TextStyle::Emphasis => "emphasis",
            TextStyle::Underline => "underline",
            TextStyle::Monospace => "monospace",
            TextStyle::SmallCaps => "small-caps",
            TextStyle::Verbatim => "verbatim",
            TextStyle::Link { .. } => "link",
        }
    }
}

/// A style mark of the text output: a range of [`TextOutput::text`] whose
/// content carries a property that plain text cannot show ([`TextStyle`]).
///
/// It holds the style, and the byte range and the line and column range of
/// the content characters it covers, counted as for a position mark
/// ([`TextMark`]). [`TextOutput::styles`] holds one per styled node printed,
/// or one per line of a table's cell for a node styled over several lines of
/// it, and [`TextOutput::style_slice`] returns the text it covers. Unlike
/// position marks, style marks are recorded inside pieces too (the title, the
/// list of notes), so that a program painting the text sees every styled
/// range.
///
/// # Examples
///
/// ```
/// use flm_core::layout::LineCol;
/// use flm_core::stdlib::backends::text::{TextOutput, TextStyle, TextStyleMark};
///
/// let output = TextOutput {
///     text: String::from("A bold word.\n"),
///     marks: Vec::new(),
///     styles: vec![TextStyleMark {
///         style: TextStyle::Bold,
///         bytes: 2..6,
///         start: LineCol { line: 0, col: 2 },
///         end: LineCol { line: 0, col: 6 },
///     }],
/// };
/// assert_eq!(output.style_slice(&output.styles[0]), "bold");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TextStyleMark {
    /// The property the covered content carries.
    pub style: TextStyle,
    /// The byte range of [`TextOutput::text`] that holds the styled content
    /// characters.
    pub bytes: Range<usize>,
    /// The line and column of the first styled content character, counted
    /// from 0.
    pub start: LineCol,
    /// The line and column just after the last styled content character.
    pub end: LineCol,
}

/// The value of the text backend's output table `flm.output.text`
/// ([`TEXT_OUTPUT`]): the printed document, its position marks and its style
/// marks.
///
/// The emit stage ([`TextEmitStage`](super::stages::TextEmitStage)) writes it
/// once per run, since the printed text is one document; the regions stage
/// and the final stage then publish its text as the `text` output's artifact
/// set (`flm.output.text.document`). A program that writes the text to a
/// medium able to show what plain text cannot reads its style marks, as the
/// extension `profile-tty` does to paint the text for a terminal. A caller
/// that wants the characters and where each part of the document was printed
/// reads this table; a caller that wants the file reads the artifact set.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TextOutput {
    /// The printed text: empty when nothing is printed, otherwise ending in
    /// exactly one newline.
    pub text: String,
    /// The position marks, in the order the printer reaches their nodes in
    /// the printed text (a node's mark before the marks of its descendants).
    /// The marks inside the cells of a table follow the table's own marks,
    /// row by row and column by column, each over its text where the cell
    /// stands in the table, one mark per line of the cell for a node printed
    /// over several lines of it.
    pub marks: Vec<TextMark>,
    /// The style marks, in the same order: the order the printer reaches
    /// their nodes, a node's mark before the marks inside it, and a table's
    /// [`TableBorder`](TextStyle::TableBorder) marks before the marks inside
    /// its cells, one mark per line of a cell for a node styled over several
    /// lines of it. See the [module
    /// documentation](self#style-marks-what-plain-text-could-not-show).
    pub styles: Vec<TextStyleMark>,
}

impl TextOutput {
    /// Returns the printed text that `mark` covers.
    ///
    /// # Panics
    ///
    /// Panics if the byte range of `mark` lies outside this output's text or
    /// does not start and end on character boundaries. A mark taken from this
    /// output's own [`marks`](Self::marks), with the output unchanged since
    /// printing, never panics; a mark from another output, a mark built or
    /// changed by hand, or an output whose `text` was changed after printing
    /// can.
    pub fn slice(&self, mark: &TextMark) -> &str {
        &self.text[mark.bytes.clone()]
    }

    /// Returns the printed text that the style mark `mark` covers.
    ///
    /// # Panics
    ///
    /// Panics if the byte range of `mark` lies outside this output's text or
    /// does not start and end on character boundaries. A mark taken from this
    /// output's own [`styles`](Self::styles), with the output unchanged since
    /// printing, never panics; a mark from another output, a mark built or
    /// changed by hand, or an output whose `text` was changed after printing
    /// can.
    pub fn style_slice(&self, mark: &TextStyleMark) -> &str {
        &self.text[mark.bytes.clone()]
    }

    /// Returns the marks that stand for the lowered node at `addr`, in the order
    /// of [`marks`](Self::marks). A node printed several times (for instance in a
    /// tree placed twice) has several marks; a node for which nothing was
    /// printed has none.
    pub fn marks_at(&self, addr: LoweredAddr) -> impl Iterator<Item = &TextMark> + '_ {
        self.marks.iter().filter(move |mark| mark.addr == addr)
    }

    /// Whether the output holds no text and no mark.
    fn is_empty(&self) -> bool {
        self.text.is_empty() && self.marks.is_empty() && self.styles.is_empty()
    }
}

impl Table for TextOutput {
    /// The table is written once per run, so it receives one table piece (the
    /// part of a table one stage invocation produced); a non-empty table piece
    /// replaces the value held so far.
    fn absorb(&mut self, piece: TextOutput) {
        if !piece.is_empty() {
            *self = piece;
        }
    }

    fn project(&self, _cx: &dyn ProjectCx) -> SerialValue {
        let position = |at: LineCol| SerialValue::Str(format!("{}:{}", at.line, at.col));
        let bytes = |range: &Range<usize>| {
            SerialValue::List(vec![
                SerialValue::Int(range.start as i64),
                SerialValue::Int(range.end as i64),
            ])
        };
        let styles = self
            .styles
            .iter()
            .map(|mark| {
                let mut entries =
                    vec![(String::from("style"), SerialValue::Str(String::from(mark.style.name())))];
                match &mark.style {
                    TextStyle::Heading { depth } | TextStyle::HeadingRule { depth } => {
                        entries.push((String::from("depth"), SerialValue::Int(i64::from(*depth))));
                    }
                    TextStyle::Link { href } => {
                        entries.push((String::from("href"), SerialValue::Str(href.clone())));
                    }
                    _ => {}
                }
                entries.push((String::from("bytes"), bytes(&mark.bytes)));
                entries.push((String::from("start"), position(mark.start)));
                entries.push((String::from("end"), position(mark.end)));
                SerialValue::Map(entries)
            })
            .collect();
        SerialValue::Map(vec![
            (String::from("text"), SerialValue::Str(self.text.clone())),
            (
                String::from("marks"),
                SerialValue::List(
                    self.marks
                        .iter()
                        .map(|mark| {
                            SerialValue::Map(vec![
                                (String::from("addr"), SerialValue::Str(mark.addr.to_string())),
                                (String::from("bytes"), bytes(&mark.bytes)),
                                (String::from("start"), position(mark.start)),
                                (String::from("end"), position(mark.end)),
                            ])
                        })
                        .collect(),
                ),
            ),
            (String::from("styles"), SerialValue::List(styles)),
        ])
    }

    fn piece_class(&self) -> PieceClass {
        if self.is_empty() {
            PieceClass::Empty
        } else {
            PieceClass::DocumentFact
        }
    }
}

impl SingletonTable for TextOutput {
    const NAME: &'static str = "flm.output.text";
}

/// The typed name of the text output table, `flm.output.text`, which holds a
/// [`TextOutput`].
pub const TEXT_OUTPUT: TableName<TextOutput> = TableName::new("flm.output.text");

// --- conditions ---------------------------------------------------------------------------

/// Condition `flm.text.flush-right-lines`: the content of a
/// [`flm.pres.text.flush-right`](super::construct::FLUSH_RIGHT) node prints on
/// more than one line, so it cannot be set at the right edge of one line.
///
/// Content takes several lines when it holds a line break: two blocks of a
/// run, for instance, or verbatim content of several lines. The lowering rule
/// that staged the node gave it that content, so this condition reports a
/// mistake in a feature rather than in a document. Reported at error severity, at the
/// node. Recovery: the content is printed where the node stands, as the
/// content of a span is, and nothing is set at the right edge.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
    id = "flm.text.flush-right-lines",
    message = "Misconfigured element ‘flm.pres.text.flush-right’: its content must fit on \
               one line (it takes {lines} lines)"
)]
pub struct FlushRightLines {
    /// The number of lines the content prints on when printed alone, with no
    /// line width.
    pub lines: usize,
}

/// Condition `flm.text.missing-subtree`: a `flm.pres.subtree` node places a
/// tree that has no lowered form for the text backend, because its lowering
/// failed or because the document has no tree with that identifier.
///
/// A `flm.pres.subtree` node stands for a tree placed inside another one (a
/// fragment placed inside another fragment); the emitter prints the placed
/// tree at that node. Reported at error severity, at the node. Recovery:
/// nothing is printed for the node.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
    id = "flm.text.missing-subtree",
    message = "the document tree `{tree}` is placed inside another tree, but it has no text to \
               print there: no tree has that identifier, or that tree could not be converted to \
               text"
)]
pub struct MissingSubtree {
    /// The placed tree's identifier.
    pub tree: String,
}

/// Condition `flm.text.subtree-cycle`: a `flm.pres.subtree` node places a
/// tree that is being printed already, because it contains this node,
/// directly or through other placed trees (a cycle of placements).
///
/// Reported at error severity, at the node. Recovery: nothing is printed for
/// the node; every tree of the cycle is still printed once.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
    id = "flm.text.subtree-cycle",
    message = "the document tree `{tree}` must not be placed inside itself, but it is, \
               directly or through other trees"
)]
pub struct SubtreeCycle {
    /// The placed tree's identifier.
    pub tree: String,
}

/// Condition `flm.text.piece-placement`: a `flm.pres.subtree` node is inside
/// a piece.
///
/// A piece ([`Piece`](crate::core::piece::Piece)) is a document-level value
/// that a backend places before or after the document's content (the title,
/// the list of footnotes); it is never placed inside a tree, and it must not
/// place a tree inside itself. Reported at error severity, at the node.
/// Recovery: nothing is printed for the node.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
    id = "flm.text.piece-placement",
    message = "the document tree `{tree}` cannot be placed inside `{piece}`, which the text \
               output places beside the document's content"
)]
pub struct PiecePlacement {
    /// The piece's name.
    pub piece: String,
    /// The identifier of the tree the node places.
    pub tree: String,
}

/// Condition `flm.text.worker-thread-unavailable`: the emitter could not run
/// on a worker thread, so it was not run.
///
/// A worker thread is a thread marked with the size of its stack
/// ([`mark_worker_thread`](crate::lang::guard::mark_worker_thread));
/// [`on_worker_thread`](crate::lang::guard::on_worker_thread) creates one, with
/// [`WORKER_STACK_SIZE`](crate::lang::guard::WORKER_STACK_SIZE) bytes of stack, when
/// the calling thread is not one (see [the recursion guard and worker
/// threads](crate::guide::concepts_overview#the-recursion-guard-and-worker-threads)). The emitter
/// needs one because its walk recurses as deeply as the trees nest, and its
/// depth limit is read from the stack that the thread declares. The
/// calling thread was not a worker thread, and the operating system refused to
/// create one. Reported at error severity, with no position in the document.
/// Recovery: the run has no text output.
// The emitter creates the worker thread itself rather than requiring the
// caller to run it on one, so that a deeply nested document never crashes the
// process. The refusal is the operating system's and cannot be provoked without
// injecting a failure, so no test covers this arm; the spawning half of the
// contract is what the emitter tests exercise.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
    id = "flm.text.worker-thread-unavailable",
    message = "printing the text output needs a thread with a large stack, and the operating \
               system refused to create one: {detail}"
)]
pub struct NoWorkerThread {
    /// The operating system's error message.
    pub detail: String,
}

/// The emitter's estimate of the stack one level of nesting of its walk uses:
/// an upper bound on two frames of the inline or of the block recursion,
/// measured under 4 KiB in a debug build (a thousand nested spans print on a
/// 4 MiB stack and overflow a 2 MiB one). It is three times the measurement,
/// so that the limit holds in every build profile. A walk's depth limit is the
/// stack that remains for guarded operations when it starts, divided by this
/// estimate.
const LEVEL_STACK_ESTIMATE: usize = 12 * 1024;

/// Condition `flm.text.nesting-too-deep`: a lowered tree, counting the trees
/// it places, nests deeper than the emitter's depth limit, which the walk
/// reads when it starts from the stack that remains on its thread (see the
/// [module documentation](self)). The detail gives the limit, in levels.
///
/// A tree that came from a parsed document never comes near the limit on a
/// thread of the library, since the parse refuses far shallower nesting. A
/// lowered tree can, when its lowering rules stage (build into the lowered
/// tree) levels of their own, or when placed trees form a long chain; the
/// levels of the placed trees count toward the depth of the tree that places
/// them.
///
/// Every recursive walk of a tree in this library is bounded in this way, and
/// each reports its own condition, so a diagnostic tells which step reached
/// its limit. Reported at error severity, once, at the root of the top-level
/// tree (or piece). Recovery: that tree prints nothing.
#[derive(Debug, Clone, PartialEq, Eq, DiagnosticInfo)]
#[diagnostic(
    id = "flm.text.nesting-too-deep",
    message = "the content nests too deeply to be printed as text: {detail}"
)]
pub struct NestingTooDeep {
    /// The limit that was exceeded, as text.
    pub detail: String,
}

/// The label `text backend` that a diagnostic shows in place of a position,
/// for a condition this backend reports that has no position in the document:
/// the label of the empty source that [`nowhere`] spans.
pub(crate) const NOWHERE_LABEL: &str = "text backend";

// --- the entry point ----------------------------------------------------------------------

/// The result of [`emit()`]: the output, and the diagnostics reported.
///
/// When the emitter cannot print at all, [`output`](Self::output) is `None`
/// and a diagnostic says why; [`emit()`] never returns an error.
#[derive(Debug)]
pub struct Emitted {
    /// The printed text and its position marks; `None` when the emitter could
    /// not run.
    pub output: Option<TextOutput>,
    /// The diagnostics, in the order they were reported.
    pub diags: FlmDiagnostics,
}

/// Prints the lowered trees of `trees` listed in `order`, in that order, with
/// the lowered `pieces` placed before and after them, under the render options
/// `options`, and returns the printed text with its position marks and the
/// diagnostics.
///
/// The pieces placed before the content come first, in their order, then the
/// trees, then the pieces placed after the content; any two of them are
/// separated by one blank line. Position marks are recorded for the bytes
/// printed for the trees, not for a piece's bytes. A `flm.pres.subtree` node
/// inside a piece prints nothing and is reported as [`PiecePlacement`].
///
/// A tree placed by a `flm.pres.subtree` node of another tree is printed at
/// that node, and is not printed again at the top level even when `order`
/// lists it. Trees that place each other in a cycle are printed after the
/// others, so that every tree of `order` is printed once; the cycle is
/// reported ([`SubtreeCycle`]). A placed tree that has no lowered form is
/// reported ([`MissingSubtree`]) and prints nothing. A tree of `order` that
/// has no lowered form in `trees` is left out without a diagnostic; when its
/// lowering failed, the lowering stage reported the failure. The module
/// documentation
/// lists what each element prints.
///
/// The walk recurses as deeply as the trees nest, so it must run on a worker
/// thread, a thread that declared its stack size
/// ([`on_worker_thread`](crate::lang::guard::on_worker_thread)): `emit` runs it
/// on the calling thread when that thread is a worker thread, and on a new
/// worker thread otherwise. A problem in the trees never makes `emit` fail or
/// panic: a tree that cannot be printed is left out and reported, and when the
/// emitter cannot run at all, [`Emitted::output`] is `None` beside an Error
/// diagnostic ([`NoWorkerThread`]).
pub fn emit(
    trees: &LoweredTrees,
    order: &[TreeId],
    pieces: &LoweredPieces,
    options: &TextRenderOptions,
) -> Emitted {
    match guard::on_worker_thread(|| emit_on_worker_thread(trees, order, pieces, options)) {
        Ok(emitted) => emitted,
        Err(error) => {
            let mut diags = FlmDiagnostics::new();
            diags.push(Diagnostic::error(
                NoWorkerThread { detail: error.to_string() },
                nowhere(FlmOrigin::synthetic(NOWHERE_LABEL)),
            ));
            Emitted { output: None, diags }
        }
    }
}

/// The emission itself, once the caller is known to be on a worker thread: the
/// pieces placed before the content, every tree of `order` that no other tree
/// places, in order, then the trees a placement cycle left unprinted, then the
/// pieces placed after the content, one blank line apart (see the [module
/// documentation](self#the-pieces-and-the-content)), printed at the width of
/// `options`.
fn emit_on_worker_thread(
    trees: &LoweredTrees,
    order: &[TreeId],
    pieces: &LoweredPieces,
    options: &TextRenderOptions,
) -> Emitted {
    let mut emitter = Emitter {
        buf: DocBuf::new(),
        trees,
        run_in_stop: &options.run_in_stop,
        link_addresses: options.link_addresses,
        link_addresses_when_shown: options.link_addresses_when_shown,
        options,
        tree: order.first().copied().unwrap_or(TreeId::tree(0)),
        placing: Vec::new(),
        printed: BTreeSet::new(),
        block_containers: Vec::new(),
        depth: 0,
        depth_limit: guard::levels_within_budget(LEVEL_STACK_ESTIMATE),
        refused: false,
        piece: None,
        script: None,
        marks: Vec::new(),
        diags: FlmDiagnostics::new(),
    };
    let placed = emitter.placed_trees();
    let mut parts: Vec<DocId> = Vec::new();
    for piece in pieces.at(PiecePlace::BeforeContent) {
        emitter.piece_part(piece, &mut parts);
    }
    // First the trees no other tree places, in order — each splices what it
    // places; then whatever is still unprinted (trees placing each other in
    // a cycle), so that every tree of the order prints once and a cycle is
    // diagnosed rather than swallowed.
    for pass in 0..2 {
        for id in order {
            if emitter.printed.contains(id) || (pass == 0 && placed.contains(id)) {
                continue;
            }
            let Some(lowered) = trees.get(*id) else { continue };
            let tree = Arc::clone(&lowered.tree);
            if let Some(doc) = emitter.tree_doc(*id, &tree) {
                if !parts.is_empty() {
                    let separator = emitter.buf.blocksep(1);
                    parts.push(separator);
                }
                parts.push(doc);
            }
        }
    }
    for piece in pieces.at(PiecePlace::AfterContent) {
        emitter.piece_part(piece, &mut parts);
    }
    let root = emitter.buf.concat(&parts);
    let Emitter { buf, marks, diags, .. } = emitter;
    let printed = print_full(&buf, root, &Profile::new(options.width));
    let mut output = TextOutput { text: printed.text, marks: Vec::new(), styles: Vec::new() };
    for span in printed.marks {
        match marks.get(span.id.0 as usize) {
            Some(MarkFor::Position(addr)) => output.marks.push(TextMark {
                id: span.id,
                addr: *addr,
                bytes: span.bytes,
                start: span.start,
                end: span.end,
            }),
            // A styled node that printed no character gets no style mark,
            // though the layout engine may report its mark as an empty range.
            Some(MarkFor::Style(style)) if !span.bytes.is_empty() => {
                output.styles.push(TextStyleMark {
                    style: style.clone(),
                    bytes: span.bytes,
                    start: span.start,
                    end: span.end,
                })
            }
            Some(MarkFor::Style(_)) => {}
            None => {}
        }
    }
    Emitted { output: Some(output), diags }
}

// --- the emitter ---------------------------------------------------------------------------

/// One token of an inline run: an atom (possibly itself filled prose), a
/// breakable space (a *gap*), a non-breaking space joining the atoms on either
/// side of it (a *tie*, which, like a gap, prints nothing at the start of a
/// run), or a node that takes lines of its own: a block of a run
/// ([`is_run_block`]) or a displayed formula.
enum Tok {
    Gap,
    Tie,
    Atom(DocId),
    Block(DocId),
}

/// The two ways a span's text is written through other forms of its
/// characters.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Script {
    /// Through the superscript forms ([`superscript_form`]).
    Raised,
    /// Through the subscript forms ([`subscript_form`]).
    Lowered,
}

impl Script {
    /// The way a span of `style` writes its text, if it has one of its own.
    fn of(style: Option<SpanStyle>) -> Option<Script> {
        match style {
            Some(SpanStyle::Superscript) => Some(Script::Raised),
            Some(SpanStyle::Subscript) => Some(Script::Lowered),
            _ => None,
        }
    }

    /// `word` with each character that has a form written in it; a
    /// character with none stays as it is.
    fn write(self, word: &str) -> String {
        let form = match self {
            Script::Raised => superscript_form,
            Script::Lowered => subscript_form,
        };
        word.chars().map(|c| form(c).unwrap_or(c)).collect()
    }
}

/// The walk in progress: the layout document being built, where in the trees
/// the walk is, and what it has collected.
struct Emitter<'t> {
    buf: DocBuf,
    trees: &'t LoweredTrees,
    /// The stop written after a run-in heading's title that does not already
    /// end in sentence punctuation; the empty text writes none.
    run_in_stop: &'t str,
    /// Whether a link to an address prints the address after its content
    /// ([`TextRenderOptions::link_addresses`]).
    link_addresses: bool,
    /// Whether a link showing its own address's display prints the address
    /// too ([`TextRenderOptions::link_addresses_when_shown`]).
    link_addresses_when_shown: bool,
    /// The render options, read for the conversion of lengths to columns
    /// ([`TextRenderOptions::columns`]) and for the root heading level.
    options: &'t TextRenderOptions,
    /// The document tree whose lowered form is being walked.
    tree: TreeId,
    /// The trees being printed, outermost first (the placement cycle guard).
    placing: Vec<TreeId>,
    /// The trees printed so far, at the top level or spliced.
    printed: BTreeSet<TreeId>,
    /// Per tree being printed (innermost last): the indices of its
    /// non-presentation containers holding a block of a run.
    block_containers: Vec<BTreeSet<usize>>,
    /// The open levels of the walk.
    depth: usize,
    /// The number of levels the walk may open, read when it starts.
    depth_limit: usize,
    /// Whether the depth limit was hit while printing the current top-level
    /// tree.
    refused: bool,
    /// The piece being printed, if any: its bytes carry no position mark,
    /// and it places no tree.
    piece: Option<Name>,
    /// How the text being walked is written: raised or lowered inside a
    /// superscript or subscript span, unchanged (`None`) elsewhere.
    script: Option<Script>,
    /// The mark table: index = mark id; each entry is a position mark or a
    /// style mark.
    marks: Vec<MarkFor>,
    diags: FlmDiagnostics,
}

/// What one layout mark of the emitter records.
#[derive(Debug, Clone)]
enum MarkFor {
    /// A position mark: the lowered node printed inside the mark.
    Position(LoweredAddr),
    /// A style mark: what the content printed inside the mark carries.
    Style(TextStyle),
}

/// The style mark a presentation node gets, if any: a block or run-in
/// heading's title, at its depth below the root heading level `root`
/// ([`heading_style_depth`]), a span of a style plain text cannot show (a
/// superscript or subscript span gets none, its text being written in Unicode
/// forms), a link's content, and verbatim content.
fn style_of(node: &NodeRef<'_, Flm>, root: u8) -> Option<TextStyle> {
    match element_of(node).name.as_str() {
        pres::BLOCK_HEADING | pres::RUNIN_HEADING => {
            Some(TextStyle::Heading { depth: heading_style_depth(node, root) })
        }
        pres::SPAN => match payload_of::<SpanPayload>(node)?.style? {
            SpanStyle::Bold => Some(TextStyle::Bold),
            SpanStyle::Italic => Some(TextStyle::Italic),
            SpanStyle::Emphasis => Some(TextStyle::Emphasis),
            SpanStyle::Underline => Some(TextStyle::Underline),
            SpanStyle::Monospace => Some(TextStyle::Monospace),
            SpanStyle::SmallCaps => Some(TextStyle::SmallCaps),
            SpanStyle::Superscript | SpanStyle::Subscript | SpanStyle::UnresolvedReference => None,
        },
        pres::LINK => {
            payload_of::<LinkPayload>(node).map(|payload| TextStyle::Link { href: payload.href.clone() })
        }
        pres::VERBATIM => Some(TextStyle::Verbatim),
        _ => None,
    }
}

/// The depth of the heading `node` below the root heading level `root`
/// ([`heading_depth`]), its level read from its payload (`root` when it has
/// none): 0 for a heading above the root level, which the emitter reports
/// where it writes a block heading.
fn heading_style_depth(node: &NodeRef<'_, Flm>, root: u8) -> u8 {
    let level = payload_of::<HeadingPayload>(node).map_or(root, |payload| payload.level);
    heading_depth(level, root).unwrap_or(0)
}

impl fmt::Debug for Emitter<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Emitter")
            .field("tree", &self.tree)
            .field("marks", &self.marks.len())
            .finish()
    }
}

/// Whether the element of `node` has the name `name`.
fn is_element(node: &NodeRef<'_, Flm>, name: &str) -> bool {
    element_of(node).name == name
}

/// Whether a node is a block of a run of blocks, separated from its
/// neighbors in the run by a blank line: a paragraph, a block, a block
/// heading, a list, cells, lines, a placed subtree, a ruled run of blocks
/// ([`RULED`]), a block image, a block verbatim, an unattributed environment.
///
/// An image is a block where its payload says it is one (the content of a
/// float, where two images are two blocks) and an atom of the text where it
/// is inline; verbatim content likewise follows its payload. A displayed
/// formula is not a block of a run: it stands in the inline content around it,
/// on lines of its own.
fn is_run_block(node: &NodeRef<'_, Flm>) -> bool {
    let name = element_of(node).name.as_str();
    match name {
        pres::PAR
        | pres::BLOCK
        | pres::BLOCK_HEADING
        | pres::LIST
        | pres::CELLS
        | pres::LINES
        | pres::SUBTREE
        | RULED => true,
        pres::IMAGE => payload_of::<ImagePayload>(node)
            .is_some_and(|payload| payload.display == ImageDisplay::Block),
        pres::VERBATIM => payload_of::<VerbatimPayload>(node)
            .is_some_and(|payload| payload.display == VerbatimDisplay::Block),
        // An unattributed environment prints its begin and end lines around its
        // body; an unattributed macro is one inline atom.
        pres::UNKNOWN => payload_of::<UnknownPayload>(node)
            .is_some_and(|payload| payload.kind == UnknownKind::Environment),
        _ => false,
    }
}

/// The layout engine's alignment for a cell's alignment.
fn col_align(align: CellAlign) -> ColAlign {
    match align {
        CellAlign::Left => ColAlign::Left,
        CellAlign::Center => ColAlign::Center,
        CellAlign::Right => ColAlign::Right,
    }
}

/// How many leading rows of a table of cells are rows of column headers: a
/// row counts when at least one of its positions holds a cell, and every cell
/// at its positions (at the cell's top-left or covered by its span) carries
/// [`CellHeader::Column`]; an empty position counts neither way. The engine
/// takes at most `u8::MAX` header rows.
fn header_rows(payload: &CellsPayload, grid: &[Vec<GridPosition>]) -> u8 {
    let is_header = |row: &Vec<GridPosition>| {
        let mut held = row.iter().filter_map(|position| match *position {
            GridPosition::TopLeft(index) | GridPosition::Covered(index) => Some(index),
            GridPosition::Empty => None,
        });
        let first = held.next();
        first.is_some()
            && first
                .into_iter()
                .chain(held)
                .all(|index| payload.cells[index].header == Some(CellHeader::Column))
    };
    let count = grid.iter().take_while(|row| is_header(row)).count();
    u8::try_from(count).unwrap_or(u8::MAX)
}

/// Whether a node is inert in a run (nothing is printed for it).
fn is_inert(node: &NodeRef<'_, Flm>) -> bool {
    node.is_comment() || is_element(node, structural::PARBREAK)
}

/// The containers of a tree that are not presentation nodes (lists, groups)
/// and hold a block of a run ([`is_run_block`]) somewhere below them; they are laid out as
/// runs of blocks. Computed in one pass in reverse storage order (a child's
/// index is always greater than its parent's), so the walk looks the
/// container up in a set instead of walking its subtree again.
fn block_containers(tree: &NodeTree<Flm>) -> BTreeSet<usize> {
    let nodes: Vec<NodeRef<'_, Flm>> = tree.iter_storage_order().collect();
    let mut set = BTreeSet::new();
    for node in nodes.iter().rev() {
        if is_presentation(node) || !matches!(node.kind(), NodeKind::List | NodeKind::Group(_)) {
            continue;
        }
        let holds = node
            .children()
            .iter()
            .any(|child| is_run_block(&child) || set.contains(&child.id().index()));
        if holds {
            set.insert(node.id().index());
        }
    }
    set
}

/// `text` with every line break and tab replaced by a space: the newline, the
/// carriage return, the tab, the vertical tab, the form feed, the next-line
/// character and the Unicode line and paragraph separators (an atom may hold
/// none of them).
fn one_line(text: &str) -> String {
    text.replace(
        ['\n', '\r', '\t', '\u{000B}', '\u{000C}', '\u{0085}', '\u{2028}', '\u{2029}'],
        " ",
    )
}

/// The text of a list label or of a decoration ([`label_text`]), with the
/// style marks of the nodes inside it as byte ranges of that text.
#[derive(Debug)]
struct Flat {
    /// The text, whitespace-normalized (one space between words).
    text: String,
    /// One entry per styled node that contributed text, in document order (a
    /// node before the nodes inside it); each range is non-empty, holds no
    /// space at either end, and lies inside the ranges of the nodes that
    /// contain its node.
    styles: Vec<(Range<usize>, TextStyle)>,
}

impl Flat {
    /// `text` with `before` written in front of it and `after` behind it, the
    /// style ranges moved with the text.
    fn around(self, before: &str, after: &str) -> Flat {
        let shift = before.len();
        Flat {
            text: format!("{before}{}{after}", self.text),
            styles: self
                .styles
                .into_iter()
                .map(|(range, style)| (range.start + shift..range.end + shift, style))
                .collect(),
        }
    }
}

/// The text of a list label or of a decoration: its plain text
/// ([`plain_text`]), whitespace-normalized ([`normalized`]), each character
/// inside a superscript or subscript span written in the forms of the
/// innermost such span, as in running text, and the range each styled node
/// inside it covers ([`style_of`]). A label and a decoration are printed as
/// one text, not walked as a run.
fn label_text<'t>(nodes: impl IntoIterator<Item = NodeRef<'t, Flm>>, root: u8) -> Flat {
    let mut text = String::new();
    // The styled nodes met so far, in document order, with the range of the
    // text they contributed so far (none yet: `None`).
    let mut styles: Vec<(Option<Range<usize>>, TextStyle)> = Vec::new();
    let mut styled: Vec<(NodeId, usize)> = Vec::new();
    let mut pending_space = false;
    for node in nodes {
        for piece in std::iter::once(node).chain(node.descendants()) {
            if let Some(style) = style_of(&piece, root) {
                styled.push((piece.id(), styles.len()));
                styles.push((None, style));
            }
            let Some(chars) = piece.chars() else { continue };
            let ancestors: Vec<NodeRef<'_, Flm>> = std::iter::successors(Some(piece), |at| {
                (at.id() != node.id()).then(|| at.parent()).flatten()
            })
            .collect();
            let script = ancestors
                .iter()
                .filter(|at| is_element(at, pres::SPAN))
                .find_map(|at| Script::of(payload_of::<SpanPayload>(at).and_then(|span| span.style)));
            let written = match script {
                Some(script) => Cow::Owned(script.write(chars)),
                None => Cow::Borrowed(chars),
            };
            let entries: Vec<usize> = ancestors
                .iter()
                .filter_map(|at| styled.iter().find(|(id, _)| *id == at.id()).map(|(_, index)| *index))
                .collect();
            for c in written.chars() {
                if is_breakable_space(c) {
                    pending_space = !text.is_empty();
                    continue;
                }
                if pending_space {
                    text.push(' ');
                    pending_space = false;
                }
                let at = text.len();
                text.push(c);
                for index in &entries {
                    let range = &mut styles[*index].0;
                    let start = range.as_ref().map_or(at, |range| range.start);
                    *range = Some(start..text.len());
                }
            }
        }
    }
    // A styled node that contributed no text has no range.
    let styles = styles.into_iter().filter_map(|(range, style)| Some((range?, style))).collect();
    Flat { text, styles }
}

/// The whitespace-normalized text of a run (one space between words). Words are
/// separated at breakable whitespace only ([`is_breakable_space`]), so a
/// non-breaking space stays in the text as written.
fn normalized(text: &str) -> String {
    text.split(is_breakable_space).filter(|word| !word.is_empty()).collect::<Vec<_>>().join(" ")
}

/// How this backend prints a decoration of the element `element`: the text to
/// print, what goes before it, and whether a breakable space goes after it.
///
/// A run-in decoration is its text followed by `stop`, with a space after it
/// and none before, since it starts the content it introduces. A closing
/// decoration follows a non-breaking space, so that it stays on the line of
/// the word before it (with nothing before it when nothing precedes it). A
/// margin decoration is written between brackets and spaces. The caller has
/// already chosen `stop`: the empty text when the title ends in sentence
/// punctuation, or when the render option asks for no stop. The style ranges
/// of `plain` move with its text; the stop and the brackets are outside them.
fn deco_shape(element: &str, plain: Flat, stop: &str) -> (Flat, Before, bool) {
    match element {
        pres::DECO_RUNIN => (plain.around("", stop), Before::Nothing, true),
        pres::DECO_FINAL => (plain, Before::Tie, false),
        pres::DECO_MARGIN => (plain.around("[", "]"), Before::Gap, true),
        _ => (plain, Before::Gap, true),
    }
}

/// What a decoration is preceded by ([`deco_shape`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Before {
    /// Nothing of its own.
    Nothing,
    /// A breakable space.
    Gap,
    /// A non-breaking space, joining it to the atom before it.
    Tie,
}

impl<'t> Emitter<'t> {
    /// The trees that a `subtree` node of another lowered tree places (a tree
    /// that places itself forms a cycle; it is printed at the top level and
    /// reported).
    fn placed_trees(&self) -> BTreeSet<TreeId> {
        let mut placed = BTreeSet::new();
        for (id, lowered) in &self.trees.trees {
            for node in lowered.tree.iter_storage_order() {
                if let Some(payload) = payload_of::<SubtreePayload>(&node) {
                    if payload.tree != *id {
                        placed.insert(payload.tree);
                    }
                }
            }
        }
        placed
    }

    /// Opens one level of the walk; returns `false`, and records the refusal,
    /// past the depth limit.
    fn descend(&mut self) -> bool {
        if self.depth >= self.depth_limit {
            self.refused = true;
            return false;
        }
        self.depth += 1;
        true
    }

    /// Closes one level of the walk.
    fn ascend(&mut self) {
        self.depth -= 1;
    }

    /// The blocks of one lowered tree; nothing, with the condition recorded
    /// at the root of the outermost tree, when the depth limit was reached.
    ///
    /// Inside a piece, `tree` is the piece's lowered value: it is not a
    /// document tree, so it is neither recorded as printed nor added to the
    /// chain of placing trees.
    fn tree_doc(&mut self, id: TreeId, tree: &Arc<NodeTree<Flm>>) -> Option<DocId> {
        if !self.descend() {
            return None;
        }
        let in_piece = self.piece.is_some();
        let saved = self.tree;
        if !in_piece {
            self.tree = id;
            self.placing.push(id);
            self.printed.insert(id);
        }
        self.block_containers.push(block_containers(tree));
        let root = tree.root();
        let children: Vec<NodeRef<'_, Flm>> = root.children().iter().collect();
        let doc = if root.is_list() { self.block_run(&children) } else { self.block_run(&[root]) };
        self.block_containers.pop();
        if !in_piece {
            self.placing.pop();
        }
        self.tree = saved;
        self.ascend();
        if !self.refused {
            return doc;
        }
        if self.placing.is_empty() {
            self.refused = false;
            self.diags.push(Diagnostic::error(
                NestingTooDeep {
                    detail: format!("more than {} levels", self.depth_limit),
                },
                root.span().clone(),
            ));
        }
        None
    }

    /// One piece at the top level, one block separation after what `parts`
    /// already holds; nothing when it prints nothing.
    fn piece_part(&mut self, piece: &LoweredPiece, parts: &mut Vec<DocId>) {
        let saved = self.piece.replace(piece.name.clone());
        let tree = Arc::clone(&piece.tree.tree);
        let doc = self.tree_doc(self.tree, &tree);
        self.piece = saved;
        if let Some(doc) = doc {
            if !parts.is_empty() {
                let separator = self.buf.blocksep(1);
                parts.push(separator);
            }
            parts.push(doc);
        }
    }

    /// Wraps `doc` in a new layout mark and records which lowered node that
    /// mark stands for; inside a piece, returns `doc` unchanged.
    fn marked(&mut self, node: &NodeRef<'_, Flm>, doc: DocId) -> DocId {
        if self.piece.is_some() {
            return doc;
        }
        self.mark(MarkFor::Position(LoweredAddr::new(self.tree, node.id())), doc)
    }

    /// Wraps `doc` in a new layout mark recording `what`.
    fn mark(&mut self, what: MarkFor, doc: DocId) -> DocId {
        let id = self.mark_id(what);
        self.buf.mark(id, doc)
    }

    /// A new layout mark recording `what`, for the layout engine to report
    /// under it.
    fn mark_id(&mut self, what: MarkFor) -> MarkId {
        let id = MarkId(self.marks.len() as u32);
        self.marks.push(what);
        id
    }

    /// Wraps `doc` in a style mark for `style`, inside a piece as well as
    /// outside one.
    fn styled(&mut self, style: TextStyle, doc: DocId) -> DocId {
        self.mark(MarkFor::Style(style), doc)
    }

    /// Wraps `doc` in the style mark that `node` gets ([`style_of`]); returns
    /// `doc` unchanged for a node that gets none.
    fn styled_as(&mut self, node: &NodeRef<'_, Flm>, doc: DocId) -> DocId {
        match style_of(node, self.options.root_heading_level) {
            Some(style) => self.styled(style, doc),
            None => doc,
        }
    }

    /// One atom printing the text of `flat`, each of its style ranges
    /// wrapped in a style mark. The atom prints exactly what one text node
    /// holding `flat.text` prints: the parts are text nodes concatenated with
    /// no place to break between them.
    fn flat_atom(&mut self, flat: Flat) -> DocId {
        // The levels open: the parts gathered so far, the style that closes
        // the level (none for the outermost), and where the level ends.
        let mut levels: Vec<(Vec<DocId>, Option<TextStyle>, usize)> =
            vec![(Vec::new(), None, flat.text.len())];
        let mut at = 0;
        for (range, style) in flat.styles {
            while levels.len() > 1 && levels.last().is_some_and(|(_, _, end)| *end <= range.start) {
                at = self.close_flat_level(&flat.text, at, &mut levels);
            }
            if at < range.start {
                let text = self.buf.text(&flat.text[at..range.start]);
                if let Some((parts, _, _)) = levels.last_mut() {
                    parts.push(text);
                }
                at = range.start;
            }
            levels.push((Vec::new(), Some(style), range.end));
        }
        while levels.len() > 1 {
            at = self.close_flat_level(&flat.text, at, &mut levels);
        }
        let (mut parts, _, end) = levels.pop().unwrap_or_default();
        if at < end {
            parts.push(self.buf.text(&flat.text[at..end]));
        }
        match parts.as_slice() {
            [] => self.buf.text(""),
            [single] => *single,
            _ => self.buf.concat(&parts),
        }
    }

    /// Closes the innermost level of [`flat_atom`](Self::flat_atom): its text
    /// up to its end, wrapped in its style mark and added to the level
    /// around it. Returns where the text written so far ends.
    fn close_flat_level(
        &mut self,
        text: &str,
        mut at: usize,
        levels: &mut Vec<(Vec<DocId>, Option<TextStyle>, usize)>,
    ) -> usize {
        let Some((mut parts, style, end)) = levels.pop() else { return at };
        if at < end {
            parts.push(self.buf.text(&text[at..end]));
            at = end;
        }
        let doc = self.buf.concat(&parts);
        let doc = match style {
            Some(style) => self.styled(style, doc),
            None => doc,
        };
        if let Some((outer, _, _)) = levels.last_mut() {
            outer.push(doc);
        }
        at
    }

    // --- block context ---------------------------------------------------------------------

    /// A run of nodes in block context: the blocks of the run
    /// ([`is_run_block`]) as blocks, maximal runs of the other nodes filled
    /// together, one blank line between blocks.
    fn block_run(&mut self, nodes: &[NodeRef<'_, Flm>]) -> Option<DocId> {
        self.block_run_of(None, nodes)
    }

    /// [`block_run`](Self::block_run) over the content run of the
    /// presentation node `carrier`, when there is one: a decoration the
    /// lowering driver moved out of that run is printed at its decoration
    /// mark, as inline
    /// content, on a line of its own when a block follows it.
    fn block_run_of(&mut self, carrier: Option<&NodeRef<'_, Flm>>, nodes: &[NodeRef<'_, Flm>]) -> Option<DocId> {
        let mut parts: Vec<DocId> = Vec::new();
        let mut inline: Vec<Tok> = Vec::new();
        let flush = |this: &mut Emitter<'_>, inline: &mut Vec<Tok>, parts: &mut Vec<DocId>| {
            if inline.is_empty() {
                return;
            }
            let toks = std::mem::take(inline);
            if let Some(doc) = this.fill(toks) {
                parts.push(doc);
            }
        };
        for node in nodes {
            if is_inert(node) {
                flush(self, &mut inline, &mut parts);
                continue;
            }
            if is_run_block(node) || self.is_block_container(node) {
                flush(self, &mut inline, &mut parts);
                if let Some(doc) = self.block(node) {
                    parts.push(doc);
                }
            } else if let (Some(carrier), true) = (carrier, is_element(node, pres::DECO_MARK)) {
                inline.extend(self.decoration(carrier, node));
            } else {
                inline.extend(self.inline_tokens(node));
            }
        }
        flush(self, &mut inline, &mut parts);
        if parts.is_empty() {
            return None;
        }
        let mut separated: Vec<DocId> = Vec::with_capacity(parts.len() * 2);
        for (index, part) in parts.into_iter().enumerate() {
            if index > 0 {
                let separator = self.buf.blocksep(1);
                separated.push(separator);
            }
            separated.push(part);
        }
        Some(self.buf.concat(&separated))
    }

    /// Whether a container that is not a presentation node, in a run of
    /// blocks, holds a block of a run; it is then laid out as a run of
    /// blocks (the set [`block_containers`] computed on entering the tree).
    fn is_block_container(&self, node: &NodeRef<'_, Flm>) -> bool {
        self.block_containers.last().is_some_and(|set| set.contains(&node.id().index()))
    }

    /// One block of a run (or a container of blocks), marked; nothing past
    /// the depth limit.
    fn block(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
        if !self.descend() {
            return None;
        }
        // A block standing inside a superscript or subscript span is not
        // raised or lowered with the span's text: it takes lines of its own.
        let script = self.script.take();
        let doc = self.block_at(node);
        self.script = script;
        self.ascend();
        doc
    }

    /// One block of a run at the level already opened: the element's own
    /// layout, marked; a node that is not a presentation node contributes its
    /// children as a run of blocks.
    fn block_at(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
        if !is_presentation(node) {
            let children: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
            return self.block_run(&children);
        }
        let name = element_of(node).name.clone();
        let doc = match name.as_str() {
            pres::PAR => {
                let body: Vec<NodeRef<'_, Flm>> =
                    node.body().map(|b| b.iter().collect()).unwrap_or_default();
                let toks = self.inline_run(node, &body);
                self.fill(toks)?
            }
            pres::BLOCK_HEADING => self.heading(node)?,
            pres::BLOCK => {
                let body: Vec<NodeRef<'_, Flm>> =
                    node.body().map(|b| b.iter().collect()).unwrap_or_default();
                self.block_run_of(Some(node), &body)?
            }
            pres::LIST => self.list(node)?,
            pres::CELLS => self.cells(node)?,
            pres::LINES => self.lines(node)?,
            pres::VERBATIM => self.verbatim_block(node)?,
            pres::SUBTREE => self.subtree(node)?,
            pres::UNKNOWN => self.unknown_environment(node)?,
            RULED => self.ruled(node)?,
            _ => {
                let toks = self.inline_tokens(node);
                return self.fill(toks);
            }
        };
        Some(self.marked(node, doc))
    }

    /// The address a `flm.pres.link` prints after its content, `<address>`,
    /// where the options ask for it: never for a link inside the document (a
    /// target beginning with `#`), and, for a link whose content already shows
    /// its address, only when
    /// [`link_addresses_when_shown`](TextRenderOptions::link_addresses_when_shown)
    /// is on. `None` where nothing is printed.
    fn printed_address(&self, node: &NodeRef<'_, Flm>) -> Option<String> {
        let payload = payload_of::<LinkPayload>(node)?;
        let printed = self.link_addresses
            && (!payload.shows_target || self.link_addresses_when_shown)
            && !payload.href.starts_with('#');
        printed.then(|| format!("<{}>", one_line(&payload.href)))
    }

    /// A `flm.pres.block-heading`: the heading text with a rule under it at
    /// depths 0 and 1 below the root heading level
    /// ([`TextRenderOptions::root_heading_level`], counted from 0 by
    /// [`heading_depth`]; a heading above the root is reported and written at
    /// depth 0), and `depth + 1` `#` characters in front of it below that — three
    /// for a heading two levels below the root. The rule is drawn by the layout
    /// engine ([`DocBuf::ruled`]), as wide as the widest line the title prints,
    /// with the characters [`heading_rules`](TextRenderOptions::heading_rules)
    /// chooses.
    fn heading(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
        let level = payload_of::<HeadingPayload>(node)
            .map_or(self.options.root_heading_level, |payload| payload.level);
        let depth = match heading_depth(level, self.options.root_heading_level) {
            Ok(depth) => depth,
            Err(above) => {
                self.diags.push(Diagnostic::error(above, node.span().clone()));
                0
            }
        };
        let body: Vec<NodeRef<'_, Flm>> =
            node.body().map(|b| b.iter().collect()).unwrap_or_default();
        let toks = self.inline_run(node, &body);
        let text = self.fill(toks);
        // The title carries the heading's style mark, and the rule under it or
        // the `#` prefix in front of it a style mark of its own; the prefix is
        // inside the title's mark, the rule outside it.
        match self.options.heading_rules.rule(depth) {
            Some(rule) => {
                let text = text?;
                let title = self.styled(TextStyle::Heading { depth }, text);
                let mark = self.mark_id(MarkFor::Style(TextStyle::HeadingRule { depth }));
                Some(self.buf.ruled(title, rule, false, true, Some(mark)))
            }
            None => {
                let prefix = format!("{} ", "#".repeat(usize::from(depth) + 1));
                let prefix = self.buf.text(&prefix);
                let prefix = self.styled(TextStyle::HeadingRule { depth }, prefix);
                let title = match text {
                    Some(text) => self.buf.concat(&[prefix, text]),
                    None => prefix,
                };
                Some(self.styled(TextStyle::Heading { depth }, title))
            }
        }
    }

    /// A [`flm.pres.text.ruled`](RULED) node: its body as a run of blocks,
    /// set by the layout engine ([`DocBuf::ruled`]) between the rule lines its
    /// payload asks for, drawn with the character of a heading at the root
    /// level ([`heading_rules`](TextRenderOptions::heading_rules)), each rule
    /// line under the style mark [`Rule`](TextStyle::Rule). Nothing when the
    /// body prints nothing.
    fn ruled(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
        let payload = payload_of::<RuledPayload>(node).copied().unwrap_or_default();
        let body: Vec<NodeRef<'_, Flm>> =
            node.body().map(|b| b.iter().collect()).unwrap_or_default();
        let content = self.block_run_of(Some(node), &body)?;
        let mark = self.mark_id(MarkFor::Style(TextStyle::Rule));
        // Depth 0 always has a rule character; `=` is the ASCII one.
        let rule = self.options.heading_rules.rule(0).unwrap_or('=');
        Some(self.buf.ruled(content, rule, payload.above, payload.below, Some(mark)))
    }

    /// The content of a [`flm.pres.text.flush-right`](FLUSH_RIGHT) node,
    /// `content`, set by the layout engine at the right edge of its line
    /// ([`DocBuf::flush_right`], with the gap [`FLUSH_RIGHT_GAP`]). Content
    /// that prints on more than one line when printed alone cannot be set
    /// there: it is reported as `flm.text.flush-right-lines`
    /// ([`FlushRightLines`]) and returned as it is, to stand where the node
    /// stands.
    fn flush_right(&mut self, node: &NodeRef<'_, Flm>, content: DocId) -> DocId {
        let alone = print(&self.buf, content, &Profile::new(None));
        let lines = alone.strip_suffix('\n').unwrap_or(&alone).split('\n').count();
        if lines > 1 {
            self.diags.push(Diagnostic::error(FlushRightLines { lines }, node.span().clone()));
            return content;
        }
        self.buf.flush_right(content, FLUSH_RIGHT_GAP)
    }

    /// A `flm.pres.list`: one entry per label/item pair, every item's blocks
    /// hanging at one column, the width of the widest label plus one, or at
    /// the margin when every label is empty.
    fn list(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
        let entries = list_entries(node);
        if entries.is_empty() {
            return None;
        }
        let root = self.options.root_heading_level;
        let labels: Vec<Flat> = entries.iter().map(|(label, _)| label_text(label.iter(), root)).collect();
        // A column is kept for the labels only where some label is written:
        // a list whose labels are all empty hangs its items at the margin.
        let column = match labels.iter().map(|label| display_width(&label.text)).max() {
            None | Some(0) => 0,
            Some(widest) => widest + 1,
        };
        let mut parts: Vec<DocId> = Vec::new();
        for ((_, item), label) in entries.iter().zip(labels) {
            if !parts.is_empty() {
                let separator = self.buf.blocksep(1);
                parts.push(separator);
            }
            let items: Vec<NodeRef<'_, Flm>> = item.iter().collect();
            match self.block_run(&items) {
                Some(body) => {
                    let width = display_width(&label.text);
                    let padding = " ".repeat(column.saturating_sub(width) as usize);
                    let label = self.flat_atom(label.around("", &padding));
                    let hung = self.buf.align(body);
                    parts.push(self.buf.concat(&[label, hung]));
                }
                // An empty item prints its label alone: padding it would end
                // the line in whitespace.
                None => parts.push(self.flat_atom(label)),
            }
        }
        Some(self.buf.concat(&parts))
    }

    /// A `flm.pres.cells`: one table of the layout engine, built from the
    /// payload's grid ([`CellsPayload::grid`]): one column per column, one
    /// row per row, each cell's content as a run of blocks at its top-left
    /// position in the cell's own alignment, and an empty document at every
    /// other position (covered by a span, or empty). The leading rows of
    /// column headers are the engine's header rows, with its rule under them.
    /// The table is drawn as [`TextRenderOptions::table_frame`] says, and the
    /// characters the engine draws for it get the style mark
    /// [`TableBorder`](TextStyle::TableBorder).
    /// Row headers, rules and custom styles are not shown in plain text.
    fn cells(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
        let (payload, contents) = cells_of(node)?;
        let contents: Vec<Option<DocId>> = contents
            .iter()
            .map(|content| {
                let nodes: Vec<NodeRef<'_, Flm>> =
                    content.map(|slice| slice.iter().collect()).unwrap_or_default();
                self.block_run(&nodes)
            })
            .collect();
        let empty = self.buf.concat(&[]);
        let grid = payload.grid();
        let rows: Vec<Vec<TableCell>> = grid
            .iter()
            .map(|row| {
                row.iter()
                    .map(|position| match *position {
                        GridPosition::TopLeft(index) => TableCell {
                            doc: contents[index].unwrap_or(empty),
                            align: payload.cells[index].align.map(col_align),
                        },
                        GridPosition::Covered(_) | GridPosition::Empty => TableCell::new(empty),
                    })
                    .collect()
            })
            .collect();
        let row_refs: Vec<&[TableCell]> = rows.iter().map(Vec::as_slice).collect();
        let cols = vec![ColSpec::left(); payload.cols as usize];
        let header_rows = header_rows(payload, &grid);
        let frame = match self.options.table_frame {
            TableFrame::None => layout::TableFrame::Gutter,
            TableFrame::Box => layout::TableFrame::Box,
        };
        let border = self.mark_id(MarkFor::Style(TextStyle::TableBorder));
        Some(self.buf.table(&cols, &row_refs, header_rows, frame, Some(border)))
    }

    /// A `flm.pres.lines`: one printed line per `flm.pres.line` child,
    /// indented by that line's left indentation.
    fn lines(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
        let body: Vec<NodeRef<'_, Flm>> =
            node.body().map(|b| b.iter().collect()).unwrap_or_default();
        let mut parts: Vec<DocId> = Vec::new();
        for line in &body {
            if is_inert(line) {
                continue;
            }
            let content: Vec<NodeRef<'_, Flm>> = if is_element(line, pres::LINE) {
                line.body().map(|b| b.iter().collect()).unwrap_or_default()
            } else {
                vec![*line]
            };
            let indent = payload_of::<LinePayload>(line)
                .map_or(0, |payload| self.options.columns(&payload.indent_left));
            // The layout engine indents by at most `u16::MAX` columns.
            let indent = u16::try_from(indent).unwrap_or(u16::MAX);
            let toks = self.inline_run(line, &content);
            let filled = self.fill(toks).unwrap_or_else(|| self.buf.text(""));
            let indented = if indent > 0 { self.buf.nest(indent, filled) } else { filled };
            let marked =
                if is_element(line, pres::LINE) { self.marked(line, indented) } else { indented };
            if !parts.is_empty() {
                let br = self.buf.hardline();
                parts.push(br);
            }
            parts.push(marked);
        }
        if parts.is_empty() {
            return None;
        }
        Some(self.buf.concat(&parts))
    }

    /// The text of verbatim content: text nodes as they are, the children of
    /// a group substituted into it without the group's braces (see the module
    /// documentation), anything else as its source spelling.
    fn verbatim_text(&mut self, nodes: &[NodeRef<'_, Flm>]) -> String {
        let mut out = String::new();
        for node in nodes {
            match node.kind() {
                NodeKind::Chars { .. } => out.push_str(node.chars().unwrap_or("")),
                NodeKind::Group(_) if node.group_type() == Some(FlmGroupType::Content) => {
                    if self.descend() {
                        let children: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
                        out.push_str(&self.verbatim_text(&children));
                        self.ascend();
                    }
                }
                _ => out.push_str(&recompose_source(&[*node])),
            }
        }
        out
    }

    /// A `flm.pres.verbatim` printed as a block: its content byte for byte,
    /// indented like its surroundings.
    fn verbatim_block(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
        let body: Vec<NodeRef<'_, Flm>> =
            node.body().map(|b| b.iter().collect()).unwrap_or_default();
        let text = self.verbatim_text(&body);
        if text.is_empty() {
            return None;
        }
        let raw = self.buf.raw(&text, RawPolicy::Indented);
        Some(self.styled(TextStyle::Verbatim, raw))
    }

    /// The body of a math node written out: its nodes as their source, with
    /// each text node among them ([`flm.pres.math-text`](pres::MATH_TEXT))
    /// written as the command it was written with, around its content on one
    /// line, and nothing at all for one with no content (a link target, which
    /// shows nothing).
    ///
    /// A text node of this kind is one of the direct nodes of the body, where
    /// the rule that puts text inside mathematics stages (builds) it. Such a
    /// node reached anywhere else is printed by this emitter's ordinary inline
    /// path, which writes its content without the command: outside a formula,
    /// the command means nothing this backend can print.
    ///
    /// The content is flattened into one line of text here, so a construct
    /// inside it contributes its text alone: mathematics inside it loses its
    /// delimiters on this path. No rule of the standard features stages that
    /// nesting on this backend, and a backend that renders formulas reads the
    /// content's nodes rather than this string.
    fn math_body(&self, body: &[NodeRef<'_, Flm>]) -> String {
        let mut out = String::new();
        let mut source: Vec<NodeRef<'_, Flm>> = Vec::new();
        for node in body {
            if !is_element(node, pres::MATH_TEXT) {
                source.push(*node);
                continue;
            }
            out.push_str(&recompose_source(&source));
            source.clear();
            let content: Vec<NodeRef<'_, Flm>> =
                node.body().map(|b| b.iter().collect()).unwrap_or_default();
            let content = normalized(&plain_text(content.iter().copied()));
            if content.is_empty() {
                continue;
            }
            match payload_of::<MathTextPayload>(node).and_then(|p| p.command.as_deref()) {
                Some(command) => out.push_str(&format!("\\{command}{{{content}}}")),
                None => out.push_str(&content),
            }
        }
        out.push_str(&recompose_source(&source));
        out
    }

    /// The source of a math node, with its delimiters.
    fn math_text(&self, node: &NodeRef<'_, Flm>) -> (MathDisplay, String) {
        let body: Vec<NodeRef<'_, Flm>> =
            node.body().map(|b| b.iter().collect()).unwrap_or_default();
        let source = self.math_body(&body);
        let payload = payload_of::<MathPassthroughPayload>(node);
        let display = payload.map_or(MathDisplay::Inline, |payload| payload.display);
        let text = match (display, payload.and_then(|payload| payload.env.as_deref())) {
            (_, Some(env)) => format!("\\begin{{{env}}}{source}\\end{{{env}}}"),
            (MathDisplay::Inline, None) => format!("\\({source}\\)"),
            (MathDisplay::Display, None) => format!("\\[{source}\\]"),
        };
        (display, text)
    }

    /// An unattributed environment: `\begin{name}` on a line of its own, the
    /// lowered body as a run of blocks, then `\end{name}` on a line of its own.
    /// What the author wrote is document content and is printed as such; the
    /// output does not say that the environment is unattributed (declared by
    /// no feature), which the run's diagnostics report instead.
    fn unknown_environment(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
        let name = payload_of::<UnknownPayload>(node)
            .map_or_else(String::new, |payload| one_line(&payload.spelling));
        let begin = self.buf.text(&format!("\\begin{{{name}}}"));
        let body: Vec<NodeRef<'_, Flm>> =
            node.body().map(|b| b.iter().collect()).unwrap_or_default();
        let content = self.block_run(&body);
        let end = self.buf.text(&format!("\\end{{{name}}}"));
        let mut parts = vec![begin];
        if let Some(content) = content {
            let br = self.buf.hardline();
            parts.push(br);
            parts.push(content);
        }
        let br = self.buf.hardline();
        parts.push(br);
        parts.push(end);
        Some(self.buf.concat(&parts))
    }

    /// A `flm.pres.subtree`: the placed tree's own blocks, printed here.
    /// Nothing, with a diagnostic, inside a piece, or when that tree is being
    /// printed already or has no lowered form.
    fn subtree(&mut self, node: &NodeRef<'_, Flm>) -> Option<DocId> {
        let payload = payload_of::<SubtreePayload>(node)?;
        let id = payload.tree;
        if let Some(piece) = &self.piece {
            self.diags.push(Diagnostic::error(
                PiecePlacement { piece: piece.to_string(), tree: id.to_string() },
                node.span().clone(),
            ));
            return None;
        }
        if self.placing.contains(&id) {
            self.diags.push(Diagnostic::error(
                SubtreeCycle { tree: id.to_string() },
                node.span().clone(),
            ));
            return None;
        }
        let Some(lowered) = self.trees.get(id) else {
            self.diags.push(Diagnostic::error(
                MissingSubtree { tree: id.to_string() },
                node.span().clone(),
            ));
            return None;
        };
        let tree = Arc::clone(&lowered.tree);
        self.tree_doc(id, &tree)
    }

    // --- inline context ---------------------------------------------------------------------

    /// A token stream as filled prose: gaps become spaces that break
    /// independently of each other (leading, trailing and repeated gaps
    /// collapse), a tie a non-breaking space (leading and trailing ties are
    /// dropped, and a tie next to a gap replaces it, so that what it joins
    /// stays together), and a [`Tok::Block`] takes lines of its own.
    /// `None` when nothing is printed.
    fn fill(&mut self, toks: Vec<Tok>) -> Option<DocId> {
        let mut parts: Vec<DocId> = Vec::new();
        let mut pending_gap = false;
        let mut pending_tie = false;
        let mut after_block = false;
        for tok in toks {
            match tok {
                Tok::Gap => pending_gap = !parts.is_empty(),
                Tok::Tie => pending_tie = !parts.is_empty() && !after_block,
                Tok::Atom(doc) => {
                    if after_block {
                        let br = self.buf.hardline();
                        parts.push(br);
                    } else if pending_tie {
                        let tie = self.buf.text("\u{a0}");
                        parts.push(tie);
                    } else if pending_gap {
                        let line = self.buf.line();
                        let separator = self.buf.group(line);
                        parts.push(separator);
                    }
                    pending_gap = false;
                    pending_tie = false;
                    after_block = false;
                    parts.push(doc);
                }
                Tok::Block(doc) => {
                    if !parts.is_empty() {
                        let br = self.buf.hardline();
                        parts.push(br);
                    }
                    pending_gap = false;
                    pending_tie = false;
                    after_block = true;
                    parts.push(doc);
                }
            }
        }
        if parts.is_empty() {
            return None;
        }
        Some(self.buf.concat(&parts))
    }

    /// The inline run of `carrier`: its content, with the decorations moved
    /// out of it printed at their decoration marks.
    fn inline_run(&mut self, carrier: &NodeRef<'_, Flm>, nodes: &[NodeRef<'_, Flm>]) -> Vec<Tok> {
        let mut toks = Vec::new();
        for node in nodes {
            if is_element(node, pres::DECO_MARK) {
                toks.extend(self.decoration(carrier, node));
            } else {
                toks.extend(self.inline_tokens(node));
            }
        }
        toks
    }

    /// A decoration moved into an attached slot, at the position of its
    /// decoration mark.
    fn decoration(&mut self, carrier: &NodeRef<'_, Flm>, mark: &NodeRef<'_, Flm>) -> Vec<Tok> {
        match decoration_at(carrier, mark) {
            Some(deco) => self.deco_tokens(&deco),
            None => Vec::new(),
        }
    }

    /// A decoration as tokens: its content flattened to text, shaped as its
    /// element asks ([`deco_shape`]) and surrounded by the breakable spaces
    /// that shape asks for. A decoration whose content holds no text
    /// ([`holds_text`]) contributes nothing.
    ///
    /// Every decoration is printed through this function, so a decoration the
    /// driver moved into an attached slot and one reached where no mark
    /// stands for it are printed alike.
    ///
    /// Whether a run-in decoration takes a stop is decided from its content
    /// tree, by the two tests every backend shares ([`holds_text`] and
    /// [`ends_in_sentence_punctuation`]), and never from the text this emitter
    /// has flattened it to.
    fn deco_tokens(&mut self, deco: &NodeRef<'_, Flm>) -> Vec<Tok> {
        let Some((text, before, after)) = self.deco_text(deco) else { return Vec::new() };
        let atom = self.flat_atom(text);
        let marked = self.marked(deco, atom);
        let mut toks = Vec::new();
        match before {
            Before::Nothing => {}
            Before::Gap => toks.push(Tok::Gap),
            Before::Tie => toks.push(Tok::Tie),
        }
        toks.push(Tok::Atom(marked));
        if after {
            toks.push(Tok::Gap);
        }
        toks
    }

    /// What [`deco_tokens`](Self::deco_tokens) sets for the decoration
    /// `deco`: its text, what goes before it and whether a breakable space
    /// goes after it ([`deco_shape`]); `None` for a decoration whose content
    /// holds no text ([`holds_text`]).
    fn deco_text(&self, deco: &NodeRef<'_, Flm>) -> Option<(Flat, Before, bool)> {
        let body: Vec<NodeRef<'_, Flm>> =
            deco.body().map(|b| b.iter().collect()).unwrap_or_default();
        if !holds_text(body.iter().copied()) {
            return None;
        }
        let plain = label_text(body.iter().copied(), self.options.root_heading_level);
        let element = element_of(deco).name.as_str();
        let stop = if element == pres::DECO_RUNIN
            && !ends_in_sentence_punctuation(body.iter().copied())
        {
            self.run_in_stop
        } else {
            ""
        };
        Some(deco_shape(element, plain, stop))
    }

    /// One node of an inline run, as tokens; none past the depth limit.
    fn inline_tokens(&mut self, node: &NodeRef<'_, Flm>) -> Vec<Tok> {
        if !self.descend() {
            return Vec::new();
        }
        let toks = self.inline_tokens_at(node);
        self.ascend();
        toks
    }

    /// One node of an inline run at the level already opened: text split into
    /// words and gaps, a presentation element as its own atom or block,
    /// anything else as its children.
    fn inline_tokens_at(&mut self, node: &NodeRef<'_, Flm>) -> Vec<Tok> {
        if let Some(text) = node.chars() {
            let mut toks = Vec::new();
            if text.starts_with(is_breakable_space) {
                toks.push(Tok::Gap);
            }
            for word in text.split(is_breakable_space).filter(|word| !word.is_empty()) {
                let word = match self.script {
                    Some(script) => Cow::Owned(script.write(word)),
                    None => Cow::Borrowed(word),
                };
                let atom = self.buf.text(&word);
                toks.push(Tok::Atom(atom));
                toks.push(Tok::Gap);
            }
            if !text.ends_with(is_breakable_space) && !text.is_empty() {
                toks.pop();
            }
            return toks;
        }
        if is_inert(node) {
            return if is_element(node, structural::PARBREAK) {
                vec![Tok::Gap]
            } else {
                Vec::new()
            };
        }
        if !is_presentation(node) {
            let children: Vec<NodeRef<'_, Flm>> = node.children().iter().collect();
            return self.inline_run(node, &children);
        }
        let name = element_of(node).name.clone();
        let doc = match name.as_str() {
            pres::SPAN | pres::RUNIN_HEADING => {
                let body: Vec<NodeRef<'_, Flm>> =
                    node.body().map(|b| b.iter().collect()).unwrap_or_default();
                // A superscript or subscript span writes the text of its
                // content through the forms of its style, nested content
                // included, so that a note's mark, a link inside a superscript
                // span, is raised too; a nested span of the other style writes
                // its own text its own way.
                let outer = self.script;
                if name.as_str() == pres::SPAN {
                    let style = payload_of::<SpanPayload>(node).and_then(|payload| payload.style);
                    if let Some(script) = Script::of(style) {
                        self.script = Some(script);
                    }
                }
                let toks = self.inline_run(node, &body);
                self.script = outer;
                match self.fill(toks) {
                    Some(doc) => self.styled_as(node, doc),
                    None => return Vec::new(),
                }
            }
            pres::LINK => {
                let body: Vec<NodeRef<'_, Flm>> =
                    node.body().map(|b| b.iter().collect()).unwrap_or_default();
                let toks = self.inline_run(node, &body);
                // The style mark covers the content, never the address
                // printed after it.
                let content = self.fill(toks).map(|content| self.styled_as(node, content));
                match (content, self.printed_address(node)) {
                    (Some(content), Some(address)) => {
                        let tail = self.buf.text(&format!(" {address}"));
                        self.buf.concat(&[content, tail])
                    }
                    (Some(content), None) => content,
                    (None, Some(address)) => self.buf.text(&address),
                    (None, None) => return Vec::new(),
                }
            }
            pres::MATH_PASSTHROUGH => {
                let (display, text) = self.math_text(node);
                match display {
                    MathDisplay::Inline => self.buf.text(&normalized(&text)),
                    MathDisplay::Display => {
                        let raw = self.buf.raw(&text, RawPolicy::Indented);
                        let nested = self.buf.nest(2, raw);
                        let marked = self.marked(node, nested);
                        return vec![Tok::Block(marked)];
                    }
                }
            }
            pres::VERBATIM => {
                let body: Vec<NodeRef<'_, Flm>> =
                    node.body().map(|b| b.iter().collect()).unwrap_or_default();
                let text = self.verbatim_text(&body);
                if text.is_empty() {
                    return Vec::new();
                }
                let block = payload_of::<VerbatimPayload>(node)
                    .is_some_and(|payload| payload.display == VerbatimDisplay::Block);
                if block || text.contains(['\n', '\t']) {
                    let raw = self.buf.raw(&text, RawPolicy::Indented);
                    let styled = self.styled(TextStyle::Verbatim, raw);
                    let marked = self.marked(node, styled);
                    return vec![Tok::Block(marked)];
                }
                let atom = self.buf.text(&text);
                self.styled(TextStyle::Verbatim, atom)
            }
            pres::IMAGE => {
                let label = payload_of::<ImagePayload>(node)
                    .map(|payload| {
                        let shown = payload.alt.as_deref().filter(|alt| !alt.trim().is_empty());
                        format!("[image: {}]", one_line(shown.unwrap_or(&payload.src)))
                    })
                    .unwrap_or_else(|| String::from("[image]"));
                self.buf.text(&label)
            }
            pres::UNSUPPORTED => {
                let element = payload_of::<UnsupportedPayload>(node)
                    .map_or_else(|| String::from("?"), |payload| payload.element.to_string());
                let text = format!("[unsupported: {element}]");
                self.buf.text(&text)
            }
            pres::DROPPED => {
                let detail = payload_of::<DroppedPayload>(node)
                    .map_or_else(|| String::from("?"), |payload| one_line(&payload.detail));
                let text = format!("[dropped: {detail}]");
                self.buf.text(&text)
            }
            // An unattributed macro, inline: its source spelling. The
            // environment kind is a block of a run and falls to the arm below.
            pres::UNKNOWN if !is_run_block(node) => {
                let text = payload_of::<UnknownPayload>(node)
                    .map_or_else(String::new, |payload| one_line(&payload.spelling));
                if text.is_empty() {
                    return Vec::new();
                }
                self.buf.text(&text)
            }
            FLUSH_RIGHT => {
                let body: Vec<NodeRef<'_, Flm>> =
                    node.body().map(|b| b.iter().collect()).unwrap_or_default();
                let toks = self.inline_run(node, &body);
                let Some(content) = self.fill(toks) else { return Vec::new() };
                self.flush_right(node, content)
            }
            pres::DECO_MARK => return Vec::new(),
            pres::DECO_RUNIN | pres::DECO_FINAL | pres::DECO_MARGIN => {
                // A decoration met in a run with no mark standing for it: it was
                // never hoisted, because the run it stands in is not the content
                // of a presentation node — an inline-layout fragment has no
                // paragraph to attach it to. It is set with the same idiom as a
                // hoisted one, so that one document reads alike under either
                // layout.
                return self.deco_tokens(node);
            }
            // A block of a run inside inline content takes lines of its own,
            // with no blank line beside it.
            _ if is_run_block(node) => {
                return match self.block(node) {
                    Some(doc) => vec![Tok::Block(doc)],
                    None => Vec::new(),
                };
            }
            _ => {
                let body: Vec<NodeRef<'_, Flm>> =
                    node.body().map(|b| b.iter().collect()).unwrap_or_default();
                let toks = self.inline_run(node, &body);
                match self.fill(toks) {
                    Some(doc) => doc,
                    None => return Vec::new(),
                }
            }
        };
        let marked = self.marked(node, doc);
        vec![Tok::Atom(marked)]
    }
}